<commit_before>#
# Kivy - Cross-platform UI framework
# https://kivy.org/
#
from __future__ import print_function

import sys
build_examples = False
if "--build_examples" in sys.argv:
    build_examples = True
    sys.argv.remove("--build_examples")

from copy import deepcopy
import os
from os.path import join, dirname, sep, exists, basename, isdir
from os import walk, environ
from distutils.version import LooseVersion
from distutils.sysconfig import get_python_inc
from collections import OrderedDict
from time import sleep, time
from subprocess import check_output, CalledProcessError
from datetime import datetime

if environ.get('KIVY_USE_SETUPTOOLS'):
    from setuptools import setup, Extension
    print('Using setuptools')
else:
    from distutils.core import setup
    from distutils.extension import Extension
    print('Using distutils')


PY3 = sys.version > '3'

if PY3:  # fix error with py3's LooseVersion comparisons
    def ver_equal(self, other):
        return self.version == other

    LooseVersion.__eq__ = ver_equal


def get_description():
    with open(join(dirname(__file__), 'README.md')) as fileh:
        return fileh.read()


def get_version(filename='kivy/version.py'):
    VERSION = kivy.__version__
    epoch = int(environ.get('SOURCE_DATE_EPOCH', time()))
    DATE = datetime.utcfromtimestamp(epoch).strftime('%Y%m%d')
    try:
        GIT_REVISION = check_output(
            ['git', 'rev-parse', 'HEAD']
        ).strip().decode('ascii')
    except (CalledProcessError, OSError, IOError) as e:
        # CalledProcessError has no errno
        errno = getattr(e, 'errno', None)
        if errno != 2 and 'CalledProcessError' not in repr(e):
            raise
        GIT_REVISION = "Unknown"

    cnt = (
        "# THIS FILE IS GENERATED FROM KIVY SETUP.PY\n"
        "__version__ = '%(version)s'\n"
        "__hash__ = '%(hash)s'\n"
        "__date__ = '%(date)s'\n"
    )

    with open(filename, 'w') as f:
        f.write(cnt % {
            'version': VERSION,
            'hash': GIT_REVISION,
            'date': DATE
        })
    return VERSION


MIN_CYTHON_STRING = '0.24'
MIN_CYTHON_VERSION = LooseVersion(MIN_CYTHON_STRING)
MAX_CYTHON_STRING = '0.28.5'
MAX_CYTHON_VERSION = LooseVersion(MAX_CYTHON_STRING)
CYTHON_UNSUPPORTED = (
    # ref https://github.com/cython/cython/issues/1968
    '0.27', '0.27.2'
)


def getoutput(cmd, env=None):
    import subprocess
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, env=env)
    p.wait()
    if p.returncode:  # if not returncode == 0
        print('WARNING: A problem occurred while running {0} (code {1})\n'
              .format(cmd, p.returncode))
        stderr_content = p.stderr.read()
        if stderr_content:
            print('{0}\n'.format(stderr_content))
        return ""
    return p.stdout.read()


def pkgconfig(*packages, **kw):
    flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
    lenviron = None
    pconfig = join(sys.prefix, 'libs', 'pkgconfig')

    if isdir(pconfig):
        lenviron = environ.copy()
        lenviron['PKG_CONFIG_PATH'] = '{};{}'.format(
            environ.get('PKG_CONFIG_PATH', ''), pconfig)
    cmd = 'pkg-config --libs --cflags {}'.format(' '.join(packages))
    results = getoutput(cmd, lenviron).split()
    for token in results:
        ext = token[:2].decode('utf-8')
        flag = flag_map.get(ext)
        if not flag:
            continue
        kw.setdefault(flag, []).append(token[2:].decode('utf-8'))
    return kw


# -----------------------------------------------------------------------------
# Determine on which platform we are

platform = sys.platform

# Detect 32/64bit for OSX (http://stackoverflow.com/a/1405971/798575)
if sys.platform == 'darwin':
    if sys.maxsize > 2 ** 32:
        osx_arch = 'x86_64'
    else:
        osx_arch = 'i386'

# Detect Python for android project (http://github.com/kivy/python-for-android)
ndkplatform = environ.get('NDKPLATFORM')
if ndkplatform is not None and environ.get('LIBLINK'):
    platform = 'android'
kivy_ios_root = environ.get('KIVYIOSROOT', None)
if kivy_ios_root is not None:
    platform = 'ios'
if exists('/opt/vc/include/bcm_host.h'):
    platform = 'rpi'
if exists('/usr/lib/arm-linux-gnueabihf/libMali.so'):
    platform = 'mali'

# -----------------------------------------------------------------------------
# Detect options
#
c_options = OrderedDict()
c_options['use_rpi'] = platform == 'rpi'
c_options['use_mali'] = platform == 'mali'
c_options['use_egl'] = False
c_options['use_opengl_es2'] = None
c_options['use_opengl_mock'] = environ.get('READTHEDOCS', None) == 'True'
c_options['use_sdl2'] = None
c_options['use_pangoft2'] = None
c_options['use_ios'] = False
c_options['use_mesagl'] = False
c_options['use_x11'] = False
c_options['use_wayland'] = False
c_options['use_gstreamer'] = None
c_options['use_avfoundation'] = platform == 'darwin'
c_options['use_osx_frameworks'] = platform == 'darwin'
c_options['debug_gl'] = False

# now check if environ is changing the default values
for key in list(c_options.keys()):
    ukey = key.upper()
    if ukey in environ:
        value = bool(int(environ[ukey]))
        print('Environ change {0} -> {1}'.format(key, value))
        c_options[key] = value


# -----------------------------------------------------------------------------
# Cython check
# on python-for-android and kivy-ios, cython usage is external

cython_unsupported_append = '''

  Please note that the following versions of Cython are not supported
  at all: {}
'''.format(', '.join(map(str, CYTHON_UNSUPPORTED)))

cython_min = '''\
  This version of Cython is not compatible with Kivy. Please upgrade to
  at least version {0}, preferably the newest supported version {1}.

  If your platform provides a Cython package, make sure you have upgraded
  to the newest version. If the newest version available is still too low,
  please remove it and install the newest supported Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append if CYTHON_UNSUPPORTED else '')

cython_max = '''\
  This version of Cython is untested with Kivy. While this version may
  work perfectly fine, it is possible that you may experience issues. If
  you do have issues, please downgrade to a supported version. It is
  best to use the newest supported version, {1}, but the minimum
  supported version is {0}.

  If your platform provides a Cython package, check if you can downgrade
  to a supported version. Otherwise, uninstall the platform package and
  install Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append if CYTHON_UNSUPPORTED else '')

cython_unsupported = '''\
  This version of Cython suffers from known bugs and is unsupported.
  Please install the newest supported version, {1}, if possible, but
  the minimum supported version is {0}.

  If your platform provides a Cython package, check if you can install
  a supported version. Otherwise, uninstall the platform package and
  install Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append)

have_cython = False
skip_cython = False
if platform in ('ios', 'android'):
    print('\nCython check avoided.')
    skip_cython = True
else:
    try:
        # check for cython
        from Cython.Distutils import build_ext
        have_cython = True
        import Cython
        cy_version_str = Cython.__version__
        cy_ver = LooseVersion(cy_version_str)
        print('\nDetected Cython version {}'.format(cy_version_str))
        if cy_ver < MIN_CYTHON_VERSION:
            print(cython_min)
            raise ImportError('Incompatible Cython Version')
        if cy_ver in CYTHON_UNSUPPORTED:
            print(cython_unsupported)
            raise ImportError('Incompatible Cython Version')
        if cy_ver > MAX_CYTHON_VERSION:
            print(cython_max)
            sleep(1)
    except ImportError:
        print("\nCython is missing, it's required for compiling kivy !\n\n")
        raise

if not have_cython:
    from distutils.command.build_ext import build_ext

# -----------------------------------------------------------------------------
# Setup classes

# the build path where kivy is being compiled
src_path = build_path = dirname(__file__)


class KivyBuildExt(build_ext):

    def finalize_options(self):
        retval = build_ext.finalize_options(self)
        global build_path
        if (self.build_lib is not None and exists(self.build_lib) and
                not self.inplace):
            build_path = self.build_lib
        return retval

    def build_extensions(self):
        # build files
        config_h_fn = ('include', 'config.h')
        config_pxi_fn = ('include', 'config.pxi')
        config_py_fn = ('setupconfig.py', )

        # generate headers
        config_h = '// Autogenerated file for Kivy C configuration\n'
        config_h += '#define __PY3 {0}\n'.format(int(PY3))
        config_pxi = '# Autogenerated file for Kivy Cython configuration\n'
        config_pxi += 'DEF PY3 = {0}\n'.format(int(PY3))
        config_py = '# Autogenerated file for Kivy configuration\n'
        config_py += 'PY3 = {0}\n'.format(int(PY3))
        config_py += 'CYTHON_MIN = {0}\nCYTHON_MAX = {1}\n'.format(
            repr(MIN_CYTHON_STRING), repr(MAX_CYTHON_STRING))
        config_py += 'CYTHON_BAD = {0}\n'.format(repr(', '.join(map(
            str, CYTHON_UNSUPPORTED))))

        # generate content
        print('Build configuration is:')
        for opt, value in c_options.items():
            value = int(bool(value))
            print(' * {0} = {1}'.format(opt, value))
            opt = opt.upper()
            config_h += '#define __{0} {1}\n'.format(opt, value)
            config_pxi += 'DEF {0} = {1}\n'.format(opt, value)
            config_py += '{0} = {1}\n'.format(opt, value)
        debug = bool(self.debug)
        print(' * debug = {0}'.format(debug))

        config_pxi += 'DEF DEBUG = {0}\n'.format(debug)
        config_py += 'DEBUG = {0}\n'.format(debug)
        config_pxi += 'DEF PLATFORM = "{0}"\n'.format(platform)
        config_py += 'PLATFORM = "{0}"\n'.format(platform)
        for fn, content in (
                (config_h_fn, config_h), (config_pxi_fn, config_pxi),
                (config_py_fn, config_py)):
            build_fn = expand(build_path, *fn)
            if self.update_if_changed(build_fn, content):
                print('Updated {}'.format(build_fn))
            src_fn = expand(src_path, *fn)
            if src_fn != build_fn and self.update_if_changed(src_fn, content):
                print('Updated {}'.format(src_fn))

        c = self.compiler.compiler_type
        print('Detected compiler is {}'.format(c))
        if c != 'msvc':
            for e in self.extensions:
                e.extra_link_args += ['-lm']

        build_ext.build_extensions(self)

    def update_if_changed(self, fn, content):
        need_update = True
        if exists(fn):
            with open(fn) as fd:
                need_update = fd.read() != content
        if need_update:
            with open(fn, 'w') as fd:
                fd.write(content)
        return need_update


def _check_and_fix_sdl2_mixer(f_path):
    print("Check if SDL2_mixer smpeg2 have an @executable_path")
    rpath_from = ("@executable_path/../Frameworks/SDL2.framework"
                  "/Versions/A/SDL2")
    rpath_to = "@rpath/../../../../SDL2.framework/Versions/A/SDL2"
    smpeg2_path = ("{}/Versions/A/Frameworks/smpeg2.framework"
                   "/Versions/A/smpeg2").format(f_path)
    output = getoutput(("otool -L '{}'").format(smpeg2_path)).decode('utf-8')
    if "@executable_path" not in output:
        return

    print("WARNING: Your SDL2_mixer version is invalid")
    print("WARNING: The smpeg2 framework embedded in SDL2_mixer contains a")
    print("WARNING: reference to @executable_path that will fail the")
    print("WARNING: execution of your application.")
    print("WARNING: We are going to change:")
    print("WARNING: from: {}".format(rpath_from))
    print("WARNING: to: {}".format(rpath_to))
    getoutput("install_name_tool -change {} {} {}".format(
        rpath_from, rpath_to, smpeg2_path))

    output = getoutput(("otool -L '{}'").format(smpeg2_path))
    if b"@executable_path" not in output:
        print("WARNING: Change successfully applied!")
        print("WARNING: You'll never see this message again.")
    else:
        print("WARNING: Unable to apply the changes, sorry.")


# -----------------------------------------------------------------------------
# extract version (simulate doc generation, kivy will be not imported)
environ['KIVY_DOC_INCLUDE'] = '1'
import kivy

# extra build commands go in the cmdclass dict {'command-name': CommandClass}
# see tools.packaging.{platform}.build.py for custom build commands for
# portable packages. Also e.g. we use build_ext command from cython if its
# installed for c extensions.
from kivy.tools.packaging.factory import FactoryBuild
cmdclass = {
    'build_factory': FactoryBuild,
    'build_ext': KivyBuildExt}

try:
    # add build rules for portable packages to cmdclass
    if platform == 'win32':
        from kivy.tools.packaging.win32.build import WindowsPortableBuild
        cmdclass['build_portable'] = WindowsPortableBuild
    elif platform == 'darwin':
        from kivy.tools.packaging.osx.build import OSXPortableBuild
        cmdclass['build_portable'] = OSXPortableBuild
except ImportError:
    print('User distribution detected, avoid portable command.')

# Detect which opengl version headers to use
if platform in ('android', 'darwin', 'ios', 'rpi', 'mali'):
    c_options['use_opengl_es2'] = True
elif c_options['use_opengl_es2'] is None:
    c_options['use_opengl_es2'] = \
        environ.get('KIVY_GRAPHICS', '').lower() == 'gles'

print('Using this graphics system: {}'.format(
    ['OpenGL', 'OpenGL ES 2'][int(c_options['use_opengl_es2'] or False)]))

# check if we are in a kivy-ios build
if platform == 'ios':
    print('Kivy-IOS project environment detect, use it.')
    print('Kivy-IOS project located at {0}'.format(kivy_ios_root))
    c_options['use_ios'] = True
    c_options['use_sdl2'] = True

elif platform == 'darwin':
    if c_options['use_osx_frameworks']:
        if osx_arch == "i386":
            print("Warning: building with frameworks fail on i386")
        else:
            print("OSX framework used, force to x86_64 only")
            environ["ARCHFLAGS"] = environ.get("ARCHFLAGS", "-arch x86_64")
            print("OSX ARCHFLAGS are: {}".format(environ["ARCHFLAGS"]))<commit_msg>Added USE_ANDROID kivy config boolean<commit_after>#
# Kivy - Cross-platform UI framework
# https://kivy.org/
#
from __future__ import print_function

import sys
build_examples = False
if "--build_examples" in sys.argv:
    build_examples = True
    sys.argv.remove("--build_examples")

from copy import deepcopy
import os
from os.path import join, dirname, sep, exists, basename, isdir
from os import walk, environ, makedirs
from distutils.version import LooseVersion
from distutils.sysconfig import get_python_inc
from collections import OrderedDict
from time import sleep, time
from subprocess import check_output, CalledProcessError
from datetime import datetime

if environ.get('KIVY_USE_SETUPTOOLS'):
    from setuptools import setup, Extension
    print('Using setuptools')
else:
    from distutils.core import setup
    from distutils.extension import Extension
    print('Using distutils')


PY3 = sys.version > '3'

if PY3:  # fix error with py3's LooseVersion comparisons
    def ver_equal(self, other):
        return self.version == other

    LooseVersion.__eq__ = ver_equal


def get_description():
    with open(join(dirname(__file__), 'README.md')) as fileh:
        return fileh.read()


def get_version(filename='kivy/version.py'):
    VERSION = kivy.__version__
    epoch = int(environ.get('SOURCE_DATE_EPOCH', time()))
    DATE = datetime.utcfromtimestamp(epoch).strftime('%Y%m%d')
    try:
        GIT_REVISION = check_output(
            ['git', 'rev-parse', 'HEAD']
        ).strip().decode('ascii')
    except (CalledProcessError, OSError, IOError) as e:
        # CalledProcessError has no errno
        errno = getattr(e, 'errno', None)
        if errno != 2 and 'CalledProcessError' not in repr(e):
            raise
        GIT_REVISION = "Unknown"

    cnt = (
        "# THIS FILE IS GENERATED FROM KIVY SETUP.PY\n"
        "__version__ = '%(version)s'\n"
        "__hash__ = '%(hash)s'\n"
        "__date__ = '%(date)s'\n"
    )

    with open(filename, 'w') as f:
        f.write(cnt % {
            'version': VERSION,
            'hash': GIT_REVISION,
            'date': DATE
        })
    return VERSION


MIN_CYTHON_STRING = '0.24'
MIN_CYTHON_VERSION = LooseVersion(MIN_CYTHON_STRING)
MAX_CYTHON_STRING = '0.28.5'
MAX_CYTHON_VERSION = LooseVersion(MAX_CYTHON_STRING)
CYTHON_UNSUPPORTED = (
    # ref https://github.com/cython/cython/issues/1968
    '0.27', '0.27.2'
)


def getoutput(cmd, env=None):
    import subprocess
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, env=env)
    p.wait()
    if p.returncode:  # if not returncode == 0
        print('WARNING: A problem occurred while running {0} (code {1})\n'
              .format(cmd, p.returncode))
        stderr_content = p.stderr.read()
        if stderr_content:
            print('{0}\n'.format(stderr_content))
        return ""
    return p.stdout.read()


def pkgconfig(*packages, **kw):
    flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
    lenviron = None
    pconfig = join(sys.prefix, 'libs', 'pkgconfig')

    if isdir(pconfig):
        lenviron = environ.copy()
        lenviron['PKG_CONFIG_PATH'] = '{};{}'.format(
            environ.get('PKG_CONFIG_PATH', ''), pconfig)
    cmd = 'pkg-config --libs --cflags {}'.format(' '.join(packages))
    results = getoutput(cmd, lenviron).split()
    for token in results:
        ext = token[:2].decode('utf-8')
        flag = flag_map.get(ext)
        if not flag:
            continue
        kw.setdefault(flag, []).append(token[2:].decode('utf-8'))
    return kw


# -----------------------------------------------------------------------------
# Determine on which platform we are

platform = sys.platform

# Detect 32/64bit for OSX (http://stackoverflow.com/a/1405971/798575)
if sys.platform == 'darwin':
    if sys.maxsize > 2 ** 32:
        osx_arch = 'x86_64'
    else:
        osx_arch = 'i386'

# Detect Python for android project (http://github.com/kivy/python-for-android)
ndkplatform = environ.get('NDKPLATFORM')
if ndkplatform is not None and environ.get('LIBLINK'):
    platform = 'android'
kivy_ios_root = environ.get('KIVYIOSROOT', None)
if kivy_ios_root is not None:
    platform = 'ios'
if exists('/opt/vc/include/bcm_host.h'):
    platform = 'rpi'
if exists('/usr/lib/arm-linux-gnueabihf/libMali.so'):
    platform = 'mali'

# -----------------------------------------------------------------------------
# Detect options
#
c_options = OrderedDict()
c_options['use_rpi'] = platform == 'rpi'
c_options['use_mali'] = platform == 'mali'
c_options['use_egl'] = False
c_options['use_opengl_es2'] = None
c_options['use_opengl_mock'] = environ.get('READTHEDOCS', None) == 'True'
c_options['use_sdl2'] = None
c_options['use_pangoft2'] = None
c_options['use_ios'] = False
c_options['use_android'] = False
c_options['use_mesagl'] = False
c_options['use_x11'] = False
c_options['use_wayland'] = False
c_options['use_gstreamer'] = None
c_options['use_avfoundation'] = platform == 'darwin'
c_options['use_osx_frameworks'] = platform == 'darwin'
c_options['debug_gl'] = False

# now check if environ is changing the default values
for key in list(c_options.keys()):
    ukey = key.upper()
    if ukey in environ:
        value = bool(int(environ[ukey]))
        print('Environ change {0} -> {1}'.format(key, value))
        c_options[key] = value


# -----------------------------------------------------------------------------
# Cython check
# on python-for-android and kivy-ios, cython usage is external

cython_unsupported_append = '''

  Please note that the following versions of Cython are not supported
  at all: {}
'''.format(', '.join(map(str, CYTHON_UNSUPPORTED)))

cython_min = '''\
  This version of Cython is not compatible with Kivy. Please upgrade to
  at least version {0}, preferably the newest supported version {1}.

  If your platform provides a Cython package, make sure you have upgraded
  to the newest version. If the newest version available is still too low,
  please remove it and install the newest supported Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append if CYTHON_UNSUPPORTED else '')

cython_max = '''\
  This version of Cython is untested with Kivy. While this version may
  work perfectly fine, it is possible that you may experience issues. If
  you do have issues, please downgrade to a supported version. It is
  best to use the newest supported version, {1}, but the minimum
  supported version is {0}.

  If your platform provides a Cython package, check if you can downgrade
  to a supported version. Otherwise, uninstall the platform package and
  install Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append if CYTHON_UNSUPPORTED else '')

cython_unsupported = '''\
  This version of Cython suffers from known bugs and is unsupported.
  Please install the newest supported version, {1}, if possible, but
  the minimum supported version is {0}.

  If your platform provides a Cython package, check if you can install
  a supported version. Otherwise, uninstall the platform package and
  install Cython via pip:

    pip install -I Cython=={1}{2}\
'''.format(MIN_CYTHON_STRING, MAX_CYTHON_STRING,
           cython_unsupported_append)

have_cython = False
skip_cython = False
if platform in ('ios', 'android'):
    print('\nCython check avoided.')
    skip_cython = True
else:
    try:
        # check for cython
        from Cython.Distutils import build_ext
        have_cython = True
        import Cython
        cy_version_str = Cython.__version__
        cy_ver = LooseVersion(cy_version_str)
        print('\nDetected Cython version {}'.format(cy_version_str))
        if cy_ver < MIN_CYTHON_VERSION:
            print(cython_min)
            raise ImportError('Incompatible Cython Version')
        if cy_ver in CYTHON_UNSUPPORTED:
            print(cython_unsupported)
            raise ImportError('Incompatible Cython Version')
        if cy_ver > MAX_CYTHON_VERSION:
            print(cython_max)
            sleep(1)
    except ImportError:
        print("\nCython is missing, it's required for compiling kivy !\n\n")
        raise

if not have_cython:
    from distutils.command.build_ext import build_ext

# -----------------------------------------------------------------------------
# Setup classes

# the build path where kivy is being compiled
src_path = build_path = dirname(__file__)


class KivyBuildExt(build_ext):

    def finalize_options(self):
        retval = build_ext.finalize_options(self)
        global build_path
        if (self.build_lib is not None and exists(self.build_lib) and
                not self.inplace):
            build_path = self.build_lib
        return retval

    def build_extensions(self):
        # build files
        config_h_fn = ('include', 'config.h')
        config_pxi_fn = ('include', 'config.pxi')
        config_py_fn = ('setupconfig.py', )

        # generate headers
        config_h = '// Autogenerated file for Kivy C configuration\n'
        config_h += '#define __PY3 {0}\n'.format(int(PY3))
        config_pxi = '# Autogenerated file for Kivy Cython configuration\n'
        config_pxi += 'DEF PY3 = {0}\n'.format(int(PY3))
        config_py = '# Autogenerated file for Kivy configuration\n'
        config_py += 'PY3 = {0}\n'.format(int(PY3))
        config_py += 'CYTHON_MIN = {0}\nCYTHON_MAX = {1}\n'.format(
            repr(MIN_CYTHON_STRING), repr(MAX_CYTHON_STRING))
        config_py += 'CYTHON_BAD = {0}\n'.format(repr(', '.join(map(
            str, CYTHON_UNSUPPORTED))))

        # generate content
        print('Build configuration is:')
        for opt, value in c_options.items():
            value = int(bool(value))
            print(' * {0} = {1}'.format(opt, value))
            opt = opt.upper()
            config_h += '#define __{0} {1}\n'.format(opt, value)
            config_pxi += 'DEF {0} = {1}\n'.format(opt, value)
            config_py += '{0} = {1}\n'.format(opt, value)
        debug = bool(self.debug)
        print(' * debug = {0}'.format(debug))

        config_pxi += 'DEF DEBUG = {0}\n'.format(debug)
        config_py += 'DEBUG = {0}\n'.format(debug)
        config_pxi += 'DEF PLATFORM = "{0}"\n'.format(platform)
        config_py += 'PLATFORM = "{0}"\n'.format(platform)
        for fn, content in (
                (config_h_fn, config_h), (config_pxi_fn, config_pxi),
                (config_py_fn, config_py)):
            build_fn = expand(build_path, *fn)
            if self.update_if_changed(build_fn, content):
                print('Updated {}'.format(build_fn))
            src_fn = expand(src_path, *fn)
            if src_fn != build_fn and self.update_if_changed(src_fn, content):
                print('Updated {}'.format(src_fn))

        c = self.compiler.compiler_type
        print('Detected compiler is {}'.format(c))
        if c != 'msvc':
            for e in self.extensions:
                e.extra_link_args += ['-lm']

        build_ext.build_extensions(self)

    def update_if_changed(self, fn, content):
        need_update = True
        if exists(fn):
            with open(fn) as fd:
                need_update = fd.read() != content
        if need_update:
            directory_name = dirname(fn)
            if not exists(directory_name):
                makedirs(directory_name)
            with open(fn, 'w') as fd:
                fd.write(content)
        return need_update


def _check_and_fix_sdl2_mixer(f_path):
    print("Check if SDL2_mixer smpeg2 have an @executable_path")
    rpath_from = ("@executable_path/../Frameworks/SDL2.framework"
                  "/Versions/A/SDL2")
    rpath_to = "@rpath/../../../../SDL2.framework/Versions/A/SDL2"
    smpeg2_path = ("{}/Versions/A/Frameworks/smpeg2.framework"
                   "/Versions/A/smpeg2").format(f_path)
    output = getoutput(("otool -L '{}'").format(smpeg2_path)).decode('utf-8')
    if "@executable_path" not in output:
        return

    print("WARNING: Your SDL2_mixer version is invalid")
    print("WARNING: The smpeg2 framework embedded in SDL2_mixer contains a")
    print("WARNING: reference to @executable_path that will fail the")
    print("WARNING: execution of your application.")
    print("WARNING: We are going to change:")
    print("WARNING: from: {}".format(rpath_from))
    print("WARNING: to: {}".format(rpath_to))
    getoutput("install_name_tool -change {} {} {}".format(
        rpath_from, rpath_to, smpeg2_path))

    output = getoutput(("otool -L '{}'").format(smpeg2_path))
    if b"@executable_path" not in output:
        print("WARNING: Change successfully applied!")
        print("WARNING: You'll never see this message again.")
    else:
        print("WARNING: Unable to apply the changes, sorry.")


# -----------------------------------------------------------------------------
# extract version (simulate doc generation, kivy will be not imported)
environ['KIVY_DOC_INCLUDE'] = '1'
import kivy

# extra build commands go in the cmdclass dict {'command-name': CommandClass}
# see tools.packaging.{platform}.build.py for custom build commands for
# portable packages. Also e.g. we use build_ext command from cython if its
# installed for c extensions.
from kivy.tools.packaging.factory import FactoryBuild
cmdclass = {
    'build_factory': FactoryBuild,
    'build_ext': KivyBuildExt}

try:
    # add build rules for portable packages to cmdclass
    if platform == 'win32':
        from kivy.tools.packaging.win32.build import WindowsPortableBuild
        cmdclass['build_portable'] = WindowsPortableBuild
    elif platform == 'darwin':
        from kivy.tools.packaging.osx.build import OSXPortableBuild
        cmdclass['build_portable'] = OSXPortableBuild
except ImportError:
    print('User distribution detected, avoid portable command.')

# Detect which opengl version headers to use
if platform in ('android', 'darwin', 'ios', 'rpi', 'mali'):
    c_options['use_opengl_es2'] = True
elif c_options['use_opengl_es2'] is None:
    c_options['use_opengl_es2'] = \
        environ.get('KIVY_GRAPHICS', '').lower() == 'gles'

print('Using this graphics system: {}'.format(
    ['OpenGL', 'OpenGL ES 2'][int(c_options['use_opengl_es2'] or False)]))

# check if we are in a kivy-ios build
if platform == 'ios':
    print('Kivy-IOS project environment detect, use it.')
    print('Kivy-IOS project located at {0}'.format(kivy_ios_root))
    c_options['use_ios'] = True
    c_options['use_sdl2'] = True

elif platform == 'android':
    c_options['use_android'] = True

elif platform == 'darwin':
    if c_options['use_osx_frameworks']:
        if osx_arch == "i386":
            print("Warning: building with frameworks fail on i386")
        else:
            print("OSX framework used, force to x86_64 only")
            environ["ARCHFLAGS"] = environ.get("ARCHFLAGS", "-arch x86_64")
            print("OSX ARCHFLAGS are: {}".format(environ["ARCHFLAGS"]))
{'fraction_non_alphanumeric': 0.14399786174868864, 'fraction_numerical': 0.009755771608031807, 'mean_word_length': 2.777385159010601, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6448277', 'n_tokens_mistral': 9546, 'n_tokens_neox': 9326, 'n_words': 2475}