• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kivy / python-for-android / 47612246520

06 Dec 2026 05:16AM UTC coverage: 62.636% (-0.3%) from 62.914%
47612246520

Pull #3419

github

web-flow
Merge 3db8d13ed into 699e62353
Pull Request #3419: Add cglm and datoviz recipes

1925 of 3317 branches covered (58.03%)

Branch coverage included in aggregate %.

42 of 109 new or added lines in 4 files covered. (38.53%)

1 existing line in 1 file now uncovered.

5622 of 8732 relevant lines covered (64.38%)

3.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

49.44
/pythonforandroid/recipe.py
1
from os.path import basename, dirname, exists, isdir, isfile, join, realpath, split
6 ✔
2
import glob
6 ✔
3
import hashlib
6 ✔
4
import json
6 ✔
5
from re import match
6 ✔
6

7
import sh
6 ✔
8
import subprocess
6 ✔
9
import shutil
6 ✔
10
import fnmatch
6 ✔
11
import zipfile
6 ✔
12
import urllib.request
6 ✔
13
from urllib.request import urlretrieve
6 ✔
14
from os import listdir, unlink, environ, curdir, walk, chmod
6 ✔
15
from sys import executable, stdout
6 ✔
16
from packaging.version import Version
6 ✔
17
from multiprocessing import cpu_count
6 ✔
18
import time
6 ✔
19
from urllib.parse import urlparse
6 ✔
20

21
import packaging.version
6 ✔
22

23
from pythonforandroid.logger import (
6 ✔
24
    logger, info, warning, debug, shprint, info_main, error)
25
from pythonforandroid.util import (
6 ✔
26
    current_directory, ensure_dir, BuildInterruptingException, rmdir, move,
27
    touch, patch_wheel_setuptools_logging)
28
from pythonforandroid.util import load_source as import_recipe
6 ✔
29

30

31
url_opener = urllib.request.build_opener()
6 ✔
32
url_orig_headers = url_opener.addheaders
6 ✔
33
urllib.request.install_opener(url_opener)
6 ✔
34

35

36
class RecipeMeta(type):
6 ✔
37
    def __new__(cls, name, bases, dct):
6 ✔
38
        if name != 'Recipe':
6 ✔
39
            if 'url' in dct:
6 ✔
40
                dct['_url'] = dct.pop('url')
6 ✔
41
            if 'version' in dct:
6 ✔
42
                dct['_version'] = dct.pop('version')
6 ✔
43

44
        return super().__new__(cls, name, bases, dct)
6 ✔
45

46

47
class Recipe(metaclass=RecipeMeta):
6 ✔
48
    _url = None
6 ✔
49
    '''The address from which the recipe may be downloaded. This is not
6 ✔
50
    essential, it may be omitted if the source is available some other
51
    way, such as via the :class:`IncludedFilesBehaviour` mixin.
52

53
    If the url includes the version, you may (and probably should)
54
    replace this with ``{version}``, which will automatically be
55
    replaced by the :attr:`version` string during download.
56

57
    .. note:: Methods marked (internal) are used internally and you
58
              probably don't need to call them, but they are available
59
              if you want.
60
    '''
61

62
    _download_headers = None
6 ✔
63
    '''Add additional headers used when downloading the package, typically
6 ✔
64
    for authorization purposes.
65

66
    Specified as an array of tuples:
67
    [("header1", "foo"), ("header2", "bar")]
68

69
    When specifying as an environment variable (DOWNLOAD_HEADER_my-package-name), use a JSON formatted fragement:
70
    [["header1","foo"],["header2", "bar"]]
71

72
    For example, when downloading from a private
73
    github repository, you can specify the following:
74
    [('Authorization', 'token <your personal access token>'), ('Accept', 'application/vnd.github+json')]
75
    '''
76

77
    _version = None
6 ✔
78
    '''A string giving the version of the software the recipe describes,
6 ✔
79
    e.g. ``2.0.3`` or ``master``.'''
80

81
    md5sum = None
6 ✔
82
    '''The md5sum of the source from the :attr:`url`. Non-essential, but
6 ✔
83
    you should try to include this, it is used to check that the download
84
    finished correctly.
85
    '''
86

87
    sha512sum = None
6 ✔
88
    '''The sha512sum of the source from the :attr:`url`. Non-essential, but
6 ✔
89
    you should try to include this, it is used to check that the download
90
    finished correctly.
91
    '''
92

93
    blake2bsum = None
6 ✔
94
    '''The blake2bsum of the source from the :attr:`url`. Non-essential, but
6 ✔
95
    you should try to include this, it is used to check that the download
96
    finished correctly.
97
    '''
98

99
    depends = []
6 ✔
100
    '''A list containing the names of any recipes that this recipe depends on.
6 ✔
101
    '''
102

103
    conflicts = []
6 ✔
104
    '''A list containing the names of any recipes that are known to be
6 ✔
105
    incompatible with this one.'''
106

107
    opt_depends = []
6 ✔
108
    '''A list of optional dependencies, that must be built before this
6 ✔
109
    recipe if they are built at all, but whose presence is not essential.'''
110

111
    patches = []
6 ✔
112
    '''A list of patches to apply to the source. Values can be either a string
6 ✔
113
    referring to the patch file relative to the recipe dir, or a tuple of the
114
    string patch file and a callable, which will receive the kwargs `arch` and
115
    `recipe`, which should return True if the patch should be applied.'''
116

117
    python_depends = []
6 ✔
118
    '''A list of pure-Python packages that this package requires. These
6 ✔
119
    packages will NOT be available at build time, but will be added to the
120
    list of pure-Python packages to install via pip. If you need these packages
121
    at build time, you must create a recipe.'''
122

123
    archs = ['armeabi']  # Not currently implemented properly
6 ✔
124

125
    built_libraries = {}
6 ✔
126
    """Each recipe that builds a system library (e.g.:libffi, openssl, etc...)
6 ✔
127
    should contain a dict holding the relevant information of the library. The
128
    keys should be the generated libraries and the values the relative path of
129
    the library inside his build folder. This dict will be used to perform
130
    different operations:
131

132
        - copy the library into the right location, depending on if it's shared
133
          or static)
134
        - check if we have to rebuild the library
135

136
    Here an example of how it would look like for `libffi` recipe:
137

138
        - `built_libraries = {'libffi.so': '.libs'}`
139

140
    .. note:: in case that the built library resides in recipe's build
141
              directory, you can set the following values for the relative
142
              path: `'.', None or ''`
143
    """
144

145
    need_stl_shared = False
6 ✔
146
    '''Some libraries or python packages may need the c++_shared in APK.
6 ✔
147
    We can automatically do this for any recipe if we set this property to
148
    `True`'''
149

150
    stl_lib_name = 'c++_shared'
6 ✔
151
    '''
6 ✔
152
    The default STL shared lib to use: `c++_shared`.
153

154
    .. note:: Android NDK version > 17 only supports 'c++_shared', because
155
        starting from NDK r18 the `gnustl_shared` lib has been deprecated.
156
    '''
157

158
    min_ndk_api_support = 20
6 ✔
159
    '''
6 ✔
160
    Minimum ndk api recipe will support.
161
    '''
162

163
    def __init__(self, *args, **kwargs):
6 ✔
164
        super().__init__(*args, **kwargs)
6 ✔
165
        self.depends = list(self.depends)
6 ✔
166
        self.conflicts = list(self.conflicts)
6 ✔
167
        self.opt_depends = list(self.opt_depends)
6 ✔
168
        self.patches = list(self.patches)
6 ✔
169
        self.python_depends = list(self.python_depends)
6 ✔
170
        self.archs = list(self.archs)
6 ✔
171
        self.built_libraries = dict(self.built_libraries)
6 ✔
172

173
    def get_stl_library(self, arch):
6 ✔
174
        return join(
6 ✔
175
            arch.ndk_lib_dir,
176
            'lib{name}.so'.format(name=self.stl_lib_name),
177
        )
178

179
    def install_stl_lib(self, arch):
6 ✔
180
        if not self.ctx.has_lib(
6 !
181
            arch.arch, 'lib{name}.so'.format(name=self.stl_lib_name)
182
        ):
183
            self.install_libs(arch, self.get_stl_library(arch))
6 ✔
184

185
    @property
6 ✔
186
    def version(self):
6 ✔
187
        key = 'VERSION_' + self.name
6 ✔
188
        return environ.get(key, self._version)
6 ✔
189

190
    @property
6 ✔
191
    def url(self):
6 ✔
192
        key = 'URL_' + self.name
6 ✔
193
        return environ.get(key, self._url)
6 ✔
194

195
    @property
6 ✔
196
    def versioned_url(self):
6 ✔
197
        '''A property returning the url of the recipe with ``{version}``
198
        replaced by the :attr:`url`. If accessing the url, you should use this
199
        property, *not* access the url directly.'''
200
        if self.url is None:
6 !
201
            return None
×
202
        return self.url.format(version=self.version)
6 ✔
203

204
    @property
6 ✔
205
    def download_headers(self):
6 ✔
206
        key = "DOWNLOAD_HEADERS_" + self.name
6 ✔
207
        env_headers = environ.get(key)
6 ✔
208
        if env_headers:
6 ✔
209
            try:
6 ✔
210
                return [tuple(h) for h in json.loads(env_headers)]
6 ✔
211
            except Exception as ex:
×
212
                raise ValueError(f'Invalid Download headers for {key} - must be JSON formatted as [["header1","foo"],["header2","bar"]]: {ex}')
×
213

214
        return environ.get(key, self._download_headers)
6 ✔
215

216
    def download_file(self, url, target, cwd=None):
6 ✔
217
        """
218
        (internal) Download an ``url`` to a ``target``.
219
        """
220
        if not url:
6 !
221
            return
×
222

223
        info('Downloading {} from {}'.format(self.name, url))
6 ✔
224

225
        if cwd:
6 !
226
            target = join(cwd, target)
×
227

228
        parsed_url = urlparse(url)
6 ✔
229
        if parsed_url.scheme in ('http', 'https'):
6 !
230
            def report_hook(index, blksize, size):
6 ✔
231
                if size <= 0:
×
232
                    progression = '{0} bytes'.format(index * blksize)
×
233
                else:
234
                    progression = '{0:.2f}%'.format(
×
235
                        index * blksize * 100. / float(size))
236
                if "CI" not in environ:
×
237
                    stdout.write('- Download {}\r'.format(progression))
×
238
                    stdout.flush()
×
239

240
            if exists(target):
6 !
241
                unlink(target)
×
242

243
            # Download item with multiple attempts (for bad connections):
244
            attempts = 0
6 ✔
245
            seconds = 1
6 ✔
246
            while True:
6 ✔
247
                try:
6 ✔
248
                    # jqueryui.com returns a 403 w/ the default user agent
249
                    # Mozilla/5.0 does not handle redirection for liblzma
250
                    url_opener.addheaders = [('User-agent', 'Wget/1.0')]
6 ✔
251
                    if self.download_headers:
6 !
252
                        url_opener.addheaders += self.download_headers
×
253
                    urlretrieve(url, target, report_hook)
6 ✔
254
                except OSError as e:
6 ✔
255
                    attempts += 1
6 ✔
256
                    if attempts >= 5:
6 ✔
257
                        raise
6 ✔
258
                    stdout.write('Download failed: {}; retrying in {} second(s)...'.format(e, seconds))
6 ✔
259
                    time.sleep(seconds)
6 ✔
260
                    seconds *= 2
6 ✔
261
                    continue
6 ✔
262
                finally:
263
                    url_opener.addheaders = url_orig_headers
6 ✔
264
                break
6 ✔
265
            return target
6 ✔
266
        elif parsed_url.scheme in ('git', 'git+file', 'git+ssh', 'git+http', 'git+https'):
×
267
            if not isdir(target):
×
268
                if url.startswith('git+'):
×
269
                    url = url[4:]
×
270
                # if 'version' is specified, do a shallow clone
271
                if self.version:
×
272
                    ensure_dir(target)
×
273
                    with current_directory(target):
×
274
                        shprint(sh.git, 'init')
×
275
                        shprint(sh.git, 'remote', 'add', 'origin', url)
×
276
                else:
277
                    shprint(sh.git, 'clone', '--recursive', url, target)
×
278
            with current_directory(target):
×
NEW
279
                env = environ.copy()
×
NEW
280
                if getattr(self, 'git_lfs_skip_smudge', False):
×
NEW
281
                    env['GIT_LFS_SKIP_SMUDGE'] = '1'
×
282
                if self.version:
×
NEW
283
                    try:
×
NEW
284
                        shprint(sh.git, 'fetch', '--depth', '1', 'origin', self.version, _env=env)
×
NEW
285
                        shprint(sh.git, 'checkout', '--detach', 'FETCH_HEAD', _env=env)
×
NEW
286
                    except sh.ErrorReturnCode:
×
NEW
287
                        shprint(sh.git, 'fetch', '--tags', '--depth', '1', _env=env)
×
NEW
288
                        shprint(sh.git, 'checkout', self.version, _env=env)
×
289
                branch = sh.git('branch', '--show-current')
×
290
                if branch:
×
NEW
291
                    shprint(sh.git, 'pull', _env=env)
×
NEW
292
                    shprint(sh.git, 'pull', '--recurse-submodules', _env=env)
×
NEW
293
                shprint(sh.git, 'submodule', 'update', '--recursive', '--init', '--depth', '1', _env=env)
×
UNCOV
294
            return target
×
295

296
    def apply_patch(self, filename, arch, build_dir=None):
6 ✔
297
        """
298
        Apply a patch from the current recipe directory into the current
299
        build directory.
300

301
        .. versionchanged:: 0.6.0
302
            Add ability to apply patch from any dir via kwarg `build_dir`'''
303
        """
304
        info("Applying patch {}".format(filename))
6 ✔
305
        build_dir = build_dir if build_dir else self.get_build_dir(arch)
6 ✔
306
        filename = join(self.get_recipe_dir(), filename)
6 ✔
307
        shprint(sh.patch, "-t", "-d", build_dir, "-p1",
6 ✔
308
                "-i", filename, _tail=10)
309

310
    def copy_file(self, filename, dest):
6 ✔
311
        info("Copy {} to {}".format(filename, dest))
×
312
        filename = join(self.get_recipe_dir(), filename)
×
313
        dest = join(self.build_dir, dest)
×
314
        shutil.copy(filename, dest)
×
315

316
    def append_file(self, filename, dest):
6 ✔
317
        info("Append {} to {}".format(filename, dest))
×
318
        filename = join(self.get_recipe_dir(), filename)
×
319
        dest = join(self.build_dir, dest)
×
320
        with open(filename, "rb") as fd:
×
321
            data = fd.read()
×
322
        with open(dest, "ab") as fd:
×
323
            fd.write(data)
×
324

325
    @property
6 ✔
326
    def name(self):
6 ✔
327
        '''The name of the recipe, the same as the folder containing it.'''
328
        modname = self.__class__.__module__
6 ✔
329
        return modname.split(".", 2)[-1]
6 ✔
330

331
    @property
6 ✔
332
    def filtered_archs(self):
6 ✔
333
        '''Return archs of self.ctx that are valid build archs
334
        for the Recipe.'''
335
        result = []
×
336
        for arch in self.ctx.archs:
×
337
            if not self.archs or (arch.arch in self.archs):
×
338
                result.append(arch)
×
339
        return result
×
340

341
    def check_recipe_choices(self):
6 ✔
342
        '''Checks what recipes are being built to see which of the alternative
343
        and optional dependencies are being used,
344
        and returns a list of these.'''
345
        recipes = []
6 ✔
346
        built_recipes = self.ctx.recipe_build_order
6 ✔
347
        for recipe in self.depends:
6 ✔
348
            if isinstance(recipe, (tuple, list)):
6 !
349
                for alternative in recipe:
×
350
                    if alternative in built_recipes:
×
351
                        recipes.append(alternative)
×
352
                        break
×
353
        for recipe in self.opt_depends:
6 ✔
354
            if recipe in built_recipes:
6 !
355
                recipes.append(recipe)
×
356
        return sorted(recipes)
6 ✔
357

358
    def get_opt_depends_in_list(self, recipes):
6 ✔
359
        '''Given a list of recipe names, returns those that are also in
360
        self.opt_depends.
361
        '''
362
        return [recipe for recipe in recipes if recipe in self.opt_depends]
6 ✔
363

364
    def get_build_container_dir(self, arch):
6 ✔
365
        '''Given the arch name, returns the directory where it will be
366
        built.
367

368
        This returns a different directory depending on what
369
        alternative or optional dependencies are being built.
370
        '''
371
        dir_name = self.get_dir_name()
6 ✔
372
        return join(self.ctx.build_dir, 'other_builds',
6 ✔
373
                    dir_name, '{}__ndk_target_{}'.format(arch, self.ctx.ndk_api))
374

375
    def get_dir_name(self):
6 ✔
376
        choices = self.check_recipe_choices()
6 ✔
377
        dir_name = '-'.join([self.name] + choices)
6 ✔
378
        return dir_name
6 ✔
379

380
    def get_build_dir(self, arch):
6 ✔
381
        '''Given the arch name, returns the directory where the
382
        downloaded/copied package will be built.'''
383

384
        return join(self.get_build_container_dir(arch), self.name)
6 ✔
385

386
    def get_recipe_dir(self):
6 ✔
387
        """
388
        Returns the local recipe directory or defaults to the core recipe
389
        directory.
390
        """
391
        if self.ctx.local_recipes is not None:
6 !
392
            local_recipe_dir = join(self.ctx.local_recipes, self.name)
×
393
            if exists(local_recipe_dir):
×
394
                return local_recipe_dir
×
395
        return join(self.ctx.root_dir, 'recipes', self.name)
6 ✔
396

397
    # Public Recipe API to be subclassed if needed
398

399
    def download_if_necessary(self):
6 ✔
400
        if self.ctx.ndk_api < self.min_ndk_api_support:
6 !
401
            error(f"In order to build '{self.name}', you must set minimum ndk api (minapi) to `{self.min_ndk_api_support}`.\n")
×
402
            exit(1)
×
403
        info_main('Downloading {}'.format(self.name))
6 ✔
404
        user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower()))
6 ✔
405
        if user_dir is not None:
6 ✔
406
            info('P4A_{}_DIR is set, skipping download for {}'.format(
6 ✔
407
                self.name, self.name))
408
            return
6 ✔
409
        self.download()
6 ✔
410

411
    def download(self):
6 ✔
412
        if self.url is None:
6 ✔
413
            info('Skipping {} download as no URL is set'.format(self.name))
6 ✔
414
            return
6 ✔
415

416
        url = self.versioned_url
6 ✔
417
        expected_digests = {}
6 ✔
418
        for alg in set(hashlib.algorithms_guaranteed) | set(('md5', 'sha512', 'blake2b')):
6 ✔
419
            expected_digest = getattr(self, alg + 'sum') if hasattr(self, alg + 'sum') else None
6 ✔
420
            ma = match(u'^(.+)#' + alg + u'=([0-9a-f]{32,})$', url)
6 ✔
421
            if ma:                # fragmented URL?
6 !
422
                if expected_digest:
×
423
                    raise ValueError(
×
424
                        ('Received {}sum from both the {} recipe '
425
                         'and its url').format(alg, self.name))
426
                url = ma.group(1)
×
427
                expected_digest = ma.group(2)
×
428
            if expected_digest:
6 !
429
                expected_digests[alg] = expected_digest
×
430

431
        ensure_dir(join(self.ctx.packages_path, self.name))
6 ✔
432

433
        with current_directory(join(self.ctx.packages_path, self.name)):
6 ✔
434
            filename = shprint(sh.basename, url).stdout[:-1].decode('utf-8')
6 ✔
435

436
            do_download = True
6 ✔
437
            marker_filename = '.mark-{}'.format(filename)
6 ✔
438
            if exists(filename) and isfile(filename):
6 !
439
                if not exists(marker_filename):
×
440
                    shprint(sh.rm, filename)
×
441
                else:
442
                    for alg, expected_digest in expected_digests.items():
×
443
                        current_digest = algsum(alg, filename)
×
444
                        if current_digest != expected_digest:
×
445
                            debug('* Generated {}sum: {}'.format(alg,
×
446
                                                                 current_digest))
447
                            debug('* Expected {}sum: {}'.format(alg,
×
448
                                                                expected_digest))
449
                            raise ValueError(
×
450
                                ('Generated {0}sum does not match expected {0}sum '
451
                                 'for {1} recipe').format(alg, self.name))
452
                    do_download = False
×
453

454
            # If we got this far, we will download
455
            if do_download:
6 !
456
                debug('Downloading {} from {}'.format(self.name, url))
6 ✔
457

458
                shprint(sh.rm, '-f', marker_filename)
6 ✔
459
                self.download_file(self.versioned_url, filename)
6 ✔
460
                touch(marker_filename)
6 ✔
461

462
                if exists(filename) and isfile(filename):
6 !
463
                    for alg, expected_digest in expected_digests.items():
×
464
                        current_digest = algsum(alg, filename)
×
465
                        if current_digest != expected_digest:
×
466
                            debug('* Generated {}sum: {}'.format(alg,
×
467
                                                                 current_digest))
468
                            debug('* Expected {}sum: {}'.format(alg,
×
469
                                                                expected_digest))
470
                            raise ValueError(
×
471
                                ('Generated {0}sum does not match expected {0}sum '
472
                                 'for {1} recipe').format(alg, self.name))
473
            else:
474
                info('{} download already cached, skipping'.format(self.name))
×
475

476
    def unpack(self, arch):
6 ✔
477
        info_main('Unpacking {} for {}'.format(self.name, arch))
×
478

479
        build_dir = self.get_build_container_dir(arch)
×
480

481
        user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower()))
×
482
        if user_dir is not None:
×
483
            info('P4A_{}_DIR exists, symlinking instead'.format(
×
484
                self.name.lower()))
485
            if exists(self.get_build_dir(arch)):
×
486
                return
×
487
            rmdir(build_dir)
×
488
            ensure_dir(build_dir)
×
489
            shprint(sh.cp, '-a', user_dir, self.get_build_dir(arch))
×
490
            return
×
491

492
        if self.url is None:
×
493
            info('Skipping {} unpack as no URL is set'.format(self.name))
×
494
            return
×
495

496
        filename = shprint(
×
497
            sh.basename, self.versioned_url).stdout[:-1].decode('utf-8')
498
        ma = match(u'^(.+)#[a-z0-9_]{3,}=([0-9a-f]{32,})$', filename)
×
499
        if ma:                  # fragmented URL?
×
500
            filename = ma.group(1)
×
501

502
        with current_directory(build_dir):
×
503
            directory_name = self.get_build_dir(arch)
×
504

505
            if not exists(directory_name) or not isdir(directory_name):
×
506
                extraction_filename = join(
×
507
                    self.ctx.packages_path, self.name, filename)
508
                if isfile(extraction_filename):
×
509
                    if extraction_filename.endswith(('.zip', '.whl')):
×
510
                        try:
×
511
                            sh.unzip(extraction_filename)
×
512
                        except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2):
×
513
                            # return code 1 means unzipping had
514
                            # warnings but did complete,
515
                            # apparently happens sometimes with
516
                            # github zips
517
                            pass
×
518
                        fileh = zipfile.ZipFile(extraction_filename, 'r')
×
519
                        root_directory = fileh.filelist[0].filename.split('/')[0]
×
520
                        if root_directory != basename(directory_name):
×
521
                            move(root_directory, directory_name)
×
522
                    elif extraction_filename.endswith(
×
523
                            ('.tar.gz', '.tgz', '.tar.bz2', '.tbz2', '.tar.xz', '.txz')):
524
                        sh.tar('xf', extraction_filename)
×
525
                        root_directory = sh.tar('tf', extraction_filename).split('\n')[0].split('/')[0]
×
526
                        if root_directory != basename(directory_name):
×
527
                            move(root_directory, directory_name)
×
528
                    else:
529
                        raise Exception(
×
530
                            'Could not extract {} download, it must be .zip, '
531
                            '.tar.gz or .tar.bz2 or .tar.xz'.format(extraction_filename))
532
                elif isdir(extraction_filename):
×
533
                    ensure_dir(directory_name)
×
534
                    for entry in listdir(extraction_filename):
×
535
                        # Previously we filtered out the .git folder, but during the build process for some recipes
536
                        # (e.g. when version is parsed by `setuptools_scm`) that may be needed.
537
                        shprint(sh.cp, '-R',
×
538
                                join(extraction_filename, entry),
539
                                directory_name)
540
                else:
541
                    raise Exception(
×
542
                        'Given path is neither a file nor a directory: {}'
543
                        .format(extraction_filename))
544

545
            else:
546
                info('{} is already unpacked, skipping'.format(self.name))
×
547

548
    def get_recipe_env(self, arch=None, with_flags_in_cc=True):
6 ✔
549
        """Return the env specialized for the recipe
550
        """
551
        arch = arch or self.filtered_archs[0]
6 ✔
552
        env = arch.get_env(with_flags_in_cc=with_flags_in_cc)
6 ✔
553

554
        for proxy_key in ('HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy'):
6 ✔
555
            if proxy_key in environ:
6 !
556
                env[proxy_key] = environ[proxy_key]
×
557

558
        return env
6 ✔
559

560
    def prebuild_arch(self, arch):
6 ✔
561
        '''Run any pre-build tasks for the Recipe. By default, this checks if
562
        any prebuild_archname methods exist for the archname of the current
563
        architecture, and runs them if so.'''
564
        prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
6 ✔
565
        if hasattr(self, prebuild):
6 !
566
            getattr(self, prebuild)()
×
567
        else:
568
            info('{} has no {}, skipping'.format(self.name, prebuild))
6 ✔
569

570
    def is_patched(self, arch):
6 ✔
571
        build_dir = self.get_build_dir(arch.arch)
×
572
        return exists(join(build_dir, '.patched'))
×
573

574
    def apply_patches(self, arch, build_dir=None):
6 ✔
575
        '''Apply any patches for the Recipe.
576

577
        .. versionchanged:: 0.6.0
578
            Add ability to apply patches from any dir via kwarg `build_dir`'''
579
        if self.patches:
×
580
            info_main('Applying patches for {}[{}]'
×
581
                      .format(self.name, arch.arch))
582

583
            if self.is_patched(arch):
×
584
                info_main('{} already patched, skipping'.format(self.name))
×
585
                return
×
586

587
            build_dir = build_dir if build_dir else self.get_build_dir(arch.arch)
×
588
            for patch in self.patches:
×
589
                if isinstance(patch, (tuple, list)):
×
590
                    patch, patch_check = patch
×
591
                    if not patch_check(arch=arch, recipe=self):
×
592
                        continue
×
593

594
                self.apply_patch(
×
595
                        patch.format(version=self.version, arch=arch.arch),
596
                        arch.arch, build_dir=build_dir)
597

598
            touch(join(build_dir, '.patched'))
×
599

600
    def should_build(self, arch):
6 ✔
601
        '''Should perform any necessary test and return True only if it needs
602
        building again. Per default we implement a library test, in case that
603
        we detect so.
604
        '''
605
        if self.built_libraries:
6 !
606
            return not all(
6 ✔
607
                exists(lib) for lib in self.get_libraries(arch.arch)
608
            )
609
        return True
×
610

611
    def build_arch(self, arch):
6 ✔
612
        '''Run any build tasks for the Recipe. By default, this checks if
613
        any build_archname methods exist for the archname of the current
614
        architecture, and runs them if so.'''
615
        build = "build_{}".format(arch.arch)
×
616
        if hasattr(self, build):
×
617
            getattr(self, build)()
×
618

619
    def install_libraries(self, arch):
6 ✔
620
        '''This method is always called after `build_arch`. In case that we
621
        detect a library recipe, defined by the class attribute
622
        `built_libraries`, we will copy all defined libraries into the
623
        right location.
624
        '''
625
        if not self.built_libraries:
6 !
626
            return
×
627
        shared_libs = [
6 ✔
628
            lib for lib in self.get_libraries(arch) if lib.endswith(".so")
629
        ]
630
        self.install_libs(arch, *shared_libs)
6 ✔
631

632
    def postbuild_arch(self, arch):
6 ✔
633
        '''Run any post-build tasks for the Recipe. By default, this checks if
634
        any postbuild_archname methods exist for the archname of the
635
        current architecture, and runs them if so.
636
        '''
637
        postbuild = "postbuild_{}".format(arch.arch)
6 ✔
638
        if hasattr(self, postbuild):
6 !
639
            getattr(self, postbuild)()
×
640

641
        if self.need_stl_shared:
6 !
642
            self.install_stl_lib(arch)
6 ✔
643

644
    def prepare_build_dir(self, arch):
6 ✔
645
        '''Copies the recipe data into a build dir for the given arch. By
646
        default, this unpacks a downloaded recipe. You should override
647
        it (or use a Recipe subclass with different behaviour) if you
648
        want to do something else.
649
        '''
650
        self.unpack(arch)
×
651

652
    def clean_build(self, arch=None):
6 ✔
653
        '''Deletes all the build information of the recipe.
654

655
        If arch is not None, only this arch dir is deleted. Otherwise
656
        (the default) all builds for all archs are deleted.
657

658
        By default, this just deletes the main build dir. If the
659
        recipe has e.g. object files biglinked, or .so files stored
660
        elsewhere, you should override this method.
661

662
        This method is intended for testing purposes, it may have
663
        strange results. Rebuild everything if this seems to happen.
664

665
        '''
666
        if arch is None:
×
667
            base_dir = join(self.ctx.build_dir, 'other_builds', self.name)
×
668
        else:
669
            base_dir = self.get_build_container_dir(arch)
×
670
        dirs = glob.glob(base_dir + '-*')
×
671
        if exists(base_dir):
×
672
            dirs.append(base_dir)
×
673
        if not dirs:
×
674
            warning('Attempted to clean build for {} but found no existing '
×
675
                    'build dirs'.format(self.name))
676

677
        for directory in dirs:
×
678
            rmdir(directory)
×
679

680
        # Delete any Python distributions to ensure the recipe build
681
        # doesn't persist in site-packages
682
        rmdir(self.ctx.python_installs_dir)
×
683

684
    def install_libs(self, arch, *libs):
6 ✔
685
        libs_dir = self.ctx.get_libs_dir(arch.arch)
6 ✔
686
        if not libs:
6 !
687
            warning('install_libs called with no libraries to install!')
×
688
            return
×
689
        args = libs + (libs_dir,)
6 ✔
690
        shprint(sh.cp, *args)
6 ✔
691

692
    def has_libs(self, arch, *libs):
6 ✔
693
        return all(map(lambda lib: self.ctx.has_lib(arch.arch, lib), libs))
×
694

695
    def get_libraries(self, arch_name, in_context=False):
6 ✔
696
        """Return the full path of the library depending on the architecture.
697
        Per default, the build library path it will be returned, unless
698
        `get_libraries` has been called with kwarg `in_context` set to
699
        True.
700

701
        .. note:: this method should be used for library recipes only
702
        """
703
        recipe_libs = set()
6 ✔
704
        if not self.built_libraries:
6 !
705
            return recipe_libs
×
706
        for lib, rel_path in self.built_libraries.items():
6 ✔
707
            if not in_context:
6 !
708
                abs_path = join(self.get_build_dir(arch_name), rel_path, lib)
6 ✔
709
                if rel_path in {".", "", None}:
6 ✔
710
                    abs_path = join(self.get_build_dir(arch_name), lib)
6 ✔
711
            else:
712
                abs_path = join(self.ctx.get_libs_dir(arch_name), lib)
×
713
            recipe_libs.add(abs_path)
6 ✔
714
        return recipe_libs
6 ✔
715

716
    @classmethod
6 ✔
717
    def recipe_dirs(cls, ctx):
6 ✔
718
        recipe_dirs = []
6 ✔
719
        if ctx.local_recipes is not None:
6 ✔
720
            recipe_dirs.append(realpath(ctx.local_recipes))
6 ✔
721
        if ctx.storage_dir:
6 ✔
722
            recipe_dirs.append(join(ctx.storage_dir, 'recipes'))
6 ✔
723
        recipe_dirs.append(join(ctx.root_dir, "recipes"))
6 ✔
724
        return recipe_dirs
6 ✔
725

726
    @classmethod
6 ✔
727
    def list_recipes(cls, ctx):
6 ✔
728
        forbidden_dirs = ('__pycache__', )
6 ✔
729
        for recipes_dir in cls.recipe_dirs(ctx):
6 ✔
730
            if recipes_dir and exists(recipes_dir):
6 ✔
731
                for name in listdir(recipes_dir):
6 ✔
732
                    if name in forbidden_dirs:
6 ✔
733
                        continue
6 ✔
734
                    fn = join(recipes_dir, name)
6 ✔
735
                    if isdir(fn):
6 ✔
736
                        yield name
6 ✔
737

738
    @classmethod
6 ✔
739
    def get_recipe(cls, name, ctx):
6 ✔
740
        '''Returns the Recipe with the given name, if it exists.'''
741
        name = name.lower()
6 ✔
742
        if not hasattr(cls, "recipes"):
6 ✔
743
            cls.recipes = {}
6 ✔
744
        if name in cls.recipes:
6 ✔
745
            return cls.recipes[name]
6 ✔
746

747
        recipe_file = None
6 ✔
748
        for recipes_dir in cls.recipe_dirs(ctx):
6 ✔
749
            if not exists(recipes_dir):
6 ✔
750
                continue
6 ✔
751
            # Find matching folder (may differ in case):
752
            for subfolder in listdir(recipes_dir):
6 ✔
753
                if subfolder.lower() == name:
6 ✔
754
                    recipe_file = join(recipes_dir, subfolder, '__init__.py')
6 ✔
755
                    if exists(recipe_file):
6 !
756
                        name = subfolder  # adapt to actual spelling
6 ✔
757
                        break
6 ✔
758
                    recipe_file = None
×
759
            if recipe_file is not None:
6 ✔
760
                break
6 ✔
761

762
        else:
763
            raise ValueError('Recipe does not exist: {}'.format(name))
6 ✔
764

765
        mod = import_recipe('pythonforandroid.recipes.{}'.format(name), recipe_file)
6 ✔
766
        if len(logger.handlers) > 1:
6 !
767
            logger.removeHandler(logger.handlers[1])
×
768
        recipe = mod.recipe
6 ✔
769
        recipe.ctx = ctx
6 ✔
770
        cls.recipes[name.lower()] = recipe
6 ✔
771
        return recipe
6 ✔
772

773

774
class IncludedFilesBehaviour(object):
6 ✔
775
    '''Recipe mixin class that will automatically unpack files included in
776
    the recipe directory.'''
777
    src_filename = None
6 ✔
778

779
    def prepare_build_dir(self, arch):
6 ✔
780
        if self.src_filename is None:
×
781
            raise BuildInterruptingException(
×
782
                'IncludedFilesBehaviour failed: no src_filename specified')
783
        rmdir(self.get_build_dir(arch))
×
784
        shprint(sh.cp, '-a', join(self.get_recipe_dir(), self.src_filename),
×
785
                self.get_build_dir(arch))
786

787

788
class BootstrapNDKRecipe(Recipe):
6 ✔
789
    '''A recipe class for recipes built in an Android project jni dir with
790
    an Android.mk. These are not cached separately, but built in the
791
    bootstrap's own building directory.
792

793
    To build an NDK project which is not part of the bootstrap, see
794
    :class:`~pythonforandroid.recipe.NDKRecipe`.
795

796
    To link with python, call the method :meth:`get_recipe_env`
797
    with the kwarg *with_python=True*.
798
    '''
799

800
    dir_name = None  # The name of the recipe build folder in the jni dir
6 ✔
801

802
    def get_build_container_dir(self, arch):
6 ✔
803
        return self.get_jni_dir()
×
804

805
    def get_build_dir(self, arch):
6 ✔
806
        if self.dir_name is None:
×
807
            raise ValueError('{} recipe doesn\'t define a dir_name, but '
×
808
                             'this is necessary'.format(self.name))
809
        return join(self.get_build_container_dir(arch), self.dir_name)
×
810

811
    def get_jni_dir(self):
6 ✔
812
        return join(self.ctx.bootstrap.build_dir, 'jni')
6 ✔
813

814
    def get_recipe_env(self, arch=None, with_flags_in_cc=True, with_python=False):
6 ✔
815
        env = super().get_recipe_env(arch, with_flags_in_cc)
×
816
        if not with_python:
×
817
            return env
×
818

819
        env['PYTHON_INCLUDE_ROOT'] = self.ctx.python_recipe.include_root(arch.arch)
×
820
        env['PYTHON_LINK_ROOT'] = self.ctx.python_recipe.link_root(arch.arch)
×
821
        env['EXTRA_LDLIBS'] = ' -lpython{}'.format(
×
822
            self.ctx.python_recipe.link_version)
823
        return env
×
824

825

826
class NDKRecipe(Recipe):
6 ✔
827
    '''A recipe class for any NDK project not included in the bootstrap.'''
828

829
    generated_libraries = []
6 ✔
830

831
    def __init__(self, *args, **kwargs):
6 ✔
832
        super().__init__(*args, **kwargs)
6 ✔
833
        self.generated_libraries = list(self.generated_libraries)
6 ✔
834

835
    def should_build(self, arch):
6 ✔
836
        lib_dir = self.get_lib_dir(arch)
×
837

838
        for lib in self.generated_libraries:
×
839
            if not exists(join(lib_dir, lib)):
×
840
                return True
×
841

842
        return False
×
843

844
    def get_lib_dir(self, arch):
6 ✔
845
        return join(self.get_build_dir(arch.arch), 'obj', 'local', arch.arch)
×
846

847
    def get_jni_dir(self, arch):
6 ✔
848
        return join(self.get_build_dir(arch.arch), 'jni')
×
849

850
    def build_arch(self, arch, *extra_args):
6 ✔
851
        super().build_arch(arch)
×
852

853
        env = self.get_recipe_env(arch)
×
854
        with current_directory(self.get_build_dir(arch.arch)):
×
855
            shprint(
×
856
                sh.Command(join(self.ctx.ndk_dir, "ndk-build")),
857
                'V=1',
858
                "-j",
859
                str(cpu_count()),
860
                'NDK_DEBUG=' + ("1" if self.ctx.build_as_debuggable else "0"),
861
                'APP_PLATFORM=android-' + str(self.ctx.ndk_api),
862
                'APP_ABI=' + arch.arch,
863
                *extra_args, _env=env
864
            )
865

866

867
class PythonRecipe(Recipe):
6 ✔
868
    site_packages_name = None
6 ✔
869
    '''The name of the module's folder when installed in the Python
6 ✔
870
    site-packages (e.g. for pyjnius it is 'jnius')'''
871

872
    call_hostpython_via_targetpython = True
6 ✔
873
    '''If True, tries to install the module using the hostpython binary
6 ✔
874
    copied to the target (normally arm) python build dir. However, this
875
    will fail if the module tries to import e.g. _io.so. Set this to False
876
    to call hostpython from its own build dir, installing the module in
877
    the right place via arguments to setup.py. However, this may not set
878
    the environment correctly and so False is not the default.'''
879

880
    install_in_hostpython = False
6 ✔
881
    '''If True, additionally installs the module in the hostpython build
6 ✔
882
    dir. This will make it available to other recipes if
883
    call_hostpython_via_targetpython is False.
884
    '''
885

886
    install_in_targetpython = True
6 ✔
887
    '''If True, installs the module in the targetpython installation dir.
6 ✔
888
    This is almost always what you want to do.'''
889

890
    setup_extra_args = []
6 ✔
891
    '''List of extra arguments to pass to setup.py'''
6 ✔
892

893
    depends = ['python3']
6 ✔
894
    '''
6 ✔
895
    .. note:: it's important to keep this depends as a class attribute outside
896
              `__init__` because sometimes we only initialize the class, so the
897
              `__init__` call won't be called and the deps would be missing
898
              (which breaks the dependency graph computation)
899

900
    .. warning:: don't forget to call `super().__init__()` in any recipe's
901
                 `__init__`, or otherwise it may not be ensured that it depends
902
                 on python2 or python3 which can break the dependency graph
903
    '''
904

905
    hostpython_prerequisites = ['setuptools']
6 ✔
906
    '''List of hostpython packages required to build a recipe'''
6 ✔
907

908
    _host_recipe = None
6 ✔
909

910
    def __init__(self, *args, **kwargs):
6 ✔
911
        super().__init__(*args, **kwargs)
6 ✔
912
        self.setup_extra_args = list(self.setup_extra_args)
6 ✔
913
        self.hostpython_prerequisites = list(self.hostpython_prerequisites)
6 ✔
914
        if 'python3' not in self.depends:
6 ✔
915
            # We ensure here that the recipe depends on python even it overrode
916
            # `depends`. We only do this if it doesn't already depend on any
917
            # python, since some recipes intentionally don't depend on/work
918
            # with all python variants
919
            depends = list(self.depends)
6 ✔
920
            depends.append('python3')
6 ✔
921
            depends = list(set(depends))
6 ✔
922
            self.depends = depends
6 ✔
923

924
    def prebuild_arch(self, arch):
6 ✔
925
        self._host_recipe = Recipe.get_recipe("hostpython3", self.ctx)
6 ✔
926
        return super().prebuild_arch(arch)
6 ✔
927

928
    def clean_build(self, arch=None):
6 ✔
929
        super().clean_build(arch=arch)
×
930
        name = self.folder_name
×
931
        python_install_dirs = glob.glob(join(self.ctx.python_installs_dir, '*'))
×
932
        for python_install in python_install_dirs:
×
933
            site_packages_dir = glob.glob(join(python_install, 'lib', 'python*',
×
934
                                               'site-packages'))
935
            if site_packages_dir:
×
936
                build_dir = join(site_packages_dir[0], name)
×
937
                if exists(build_dir):
×
938
                    info('Deleted {}'.format(build_dir))
×
939
                    rmdir(build_dir)
×
940

941
    @property
6 ✔
942
    def real_hostpython_location(self):
6 ✔
943
        host_name = 'host{}'.format(self.ctx.python_recipe.name)
×
944
        if host_name == 'hostpython3':
×
945
            return self._host_recipe.python_exe
×
946
        else:
947
            return 'python{}'.format(self.ctx.python_recipe.version)
×
948

949
    @property
6 ✔
950
    def hostpython_location(self):
6 ✔
951
        if not self.call_hostpython_via_targetpython:
×
952
            return self.real_hostpython_location
×
953
        return self.ctx.hostpython
×
954

955
    @property
6 ✔
956
    def folder_name(self):
6 ✔
957
        '''The name of the build folders containing this recipe.'''
958
        name = self.site_packages_name
×
959
        if name is None:
×
960
            name = self.name
×
961
        return name
×
962

963
    def patch_shebang(self, _file, original_bin):
6 ✔
964
        _file_des = open(_file, "r")
×
965

966
        try:
×
967
            data = _file_des.readlines()
×
968
        except UnicodeDecodeError:
×
969
            return
×
970

971
        if "#!" in (line := data[0]):
×
972
            if line.split("#!")[-1].strip() == original_bin:
×
973
                return
×
974

975
            info(f"Fixing shebang for '{_file}'")
×
976
            data.pop(0)
×
977
            data.insert(0, "#!" + original_bin + "\n")
×
978
            _file_des.close()
×
979
            _file_des = open(_file, "w")
×
980
            _file_des.write("".join(data))
×
981
            _file_des.close()
×
982

983
    def patch_shebangs(self, path, original_bin):
6 ✔
984
        if not isdir(path):
×
985
            warning(f"Shebang patch skipped: '{path}' does not exist.")
×
986
            return
×
987
        # set correct shebang
988
        for file in listdir(path):
×
989
            _file = join(path, file)
×
990
            if isfile(_file):
×
991
                self.patch_shebang(_file, original_bin)
×
992

993
    def get_recipe_env(self, arch=None, with_flags_in_cc=True):
6 ✔
994
        if self._host_recipe is None:
6 !
995
            self._host_recipe = Recipe.get_recipe("hostpython3", self.ctx)
6 ✔
996

997
        env = super().get_recipe_env(arch, with_flags_in_cc)
6 ✔
998
        # Set the LANG, this isn't usually important but is a better default
999
        # as it occasionally matters how Python e.g. reads files
1000
        env['LANG'] = "en_GB.UTF-8"
6 ✔
1001
        env["PATH"] = self._host_recipe.local_bin + ":" + self._host_recipe.site_bin + ":" + env["PATH"]
6 ✔
1002
        host_env = self.get_hostrecipe_env(arch)
6 ✔
1003
        env['PYTHONPATH'] = host_env["PYTHONPATH"]
6 ✔
1004

1005
        if not self.call_hostpython_via_targetpython:
6 !
1006
            env['CFLAGS'] += ' -I{}'.format(
6 ✔
1007
                self.ctx.python_recipe.include_root(arch.arch)
1008
            )
1009
            env['LDFLAGS'] += ' -L{} -lpython{}'.format(
6 ✔
1010
                self.ctx.python_recipe.link_root(arch.arch),
1011
                self.ctx.python_recipe.link_version,
1012
            )
1013

1014
        return env
6 ✔
1015

1016
    def should_build(self, arch):
6 ✔
1017
        name = self.folder_name
×
1018
        if self.ctx.has_package(name, arch):
×
1019
            info('Python package already exists in site-packages')
×
1020
            return False
×
1021
        info('{} apparently isn\'t already in site-packages'.format(name))
×
1022
        return True
×
1023

1024
    def build_arch(self, arch):
6 ✔
1025
        '''Install the Python module by calling setup.py install with
1026
        the target Python dir.'''
1027
        self.install_hostpython_prerequisites()
×
1028
        super().build_arch(arch)
×
1029
        self.install_python_package(arch)
×
1030

1031
    def install_python_package(self, arch, name=None, env=None, is_dir=True):
6 ✔
1032
        '''Automate the installation of a Python package (or a cython
1033
        package where the cython components are pre-built).'''
1034
        # arch = self.filtered_archs[0]  # old kivy-ios way
1035
        if name is None:
×
1036
            name = self.name
×
1037
        if env is None:
×
1038
            env = self.get_recipe_env(arch)
×
1039

1040
        info('Installing {} into site-packages'.format(self.name))
×
1041

1042
        hpenv = env.copy()
×
1043
        with current_directory(self.get_build_dir(arch.arch)):
×
1044
            shprint(self._host_recipe.pip, 'install', '.',
×
1045
                    '--compile', '--target',
1046
                    self.ctx.get_python_install_dir(arch.arch),
1047
                    _env=hpenv, *self.setup_extra_args
1048
            )
1049

1050
    def get_hostrecipe_env(self, arch=None):
6 ✔
1051
        env = environ.copy()
6 ✔
1052
        env['PYTHONPATH'] = ''
6 ✔
1053
        env['HOME'] = '/tmp'
6 ✔
1054
        return env
6 ✔
1055

1056
    @property
6 ✔
1057
    def hostpython_site_dir(self):
6 ✔
1058
        return join(dirname(self.real_hostpython_location), 'Lib', 'site-packages')
×
1059

1060
    def install_hostpython_package(self, arch):
6 ✔
1061
        env = self.get_hostrecipe_env(arch)
×
1062
        shprint(self._host_recipe.pip, 'install', '.',
×
1063
                '--compile',
1064
                '--root={}'.format(self._host_recipe.site_root),
1065
                _env=env, *self.setup_extra_args)
1066

1067
    @property
6 ✔
1068
    def python_major_minor_version(self):
6 ✔
1069
        parsed_version = packaging.version.parse(self.ctx.python_recipe.version)
×
1070
        return f"{parsed_version.major}.{parsed_version.minor}"
×
1071

1072
    def install_hostpython_prerequisites(self, packages=None, force_upgrade=True):
6 ✔
1073
        if not packages:
×
1074
            packages = self.hostpython_prerequisites
×
1075

1076
        if len(packages) == 0:
×
1077
            return
×
1078

1079
        pip_options = [
×
1080
            "install",
1081
            *packages,
1082
            "-q",
1083
        ]
1084
        if force_upgrade:
×
1085
            pip_options.append("--upgrade")
×
1086
        pip_env = self.get_hostrecipe_env()
×
1087
        shprint(self._host_recipe.pip, *pip_options, _env=pip_env)
×
1088

1089
    def restore_hostpython_prerequisites(self, packages):
6 ✔
1090
        _packages = []
×
1091
        for package in packages:
×
1092
            original_version = Recipe.get_recipe(package, self.ctx).version
×
1093
            _packages.append(package + "==" + original_version)
×
1094
        self.install_hostpython_prerequisites(packages=_packages)
×
1095

1096

1097
class CompiledComponentsPythonRecipe(PythonRecipe):
6 ✔
1098
    pre_build_ext = False
6 ✔
1099

1100
    build_cmd = 'build_ext'
6 ✔
1101

1102
    def build_arch(self, arch):
6 ✔
1103
        '''Build any cython components, then install the Python module by
1104
        calling pip install with the target Python dir.
1105
        '''
1106
        Recipe.build_arch(self, arch)
×
1107
        self.install_hostpython_prerequisites()
×
1108
        self.build_compiled_components(arch)
×
1109
        self.install_python_package(arch)
×
1110

1111
    def build_compiled_components(self, arch):
6 ✔
1112
        info('Building compiled components in {}'.format(self.name))
×
1113

1114
        env = self.get_recipe_env(arch)
×
1115
        hostpython = sh.Command(self.hostpython_location)
×
1116
        with current_directory(self.get_build_dir(arch.arch)):
×
1117
            if self.install_in_hostpython:
×
1118
                shprint(hostpython, 'setup.py', 'clean', '--all', _env=env)
×
1119
            shprint(hostpython, 'setup.py', self.build_cmd, '-v',
×
1120
                    _env=env, *self.setup_extra_args)
1121
            build_dir = glob.glob('build/lib.*')[0]
×
1122
            shprint(sh.find, build_dir, '-name', '"*.o"', '-exec',
×
1123
                    env['STRIP'], '{}', ';', _env=env)
1124

1125
    def install_hostpython_package(self, arch):
6 ✔
1126
        env = self.get_hostrecipe_env(arch)
×
1127
        self.rebuild_compiled_components(arch, env)
×
1128
        super().install_hostpython_package(arch)
×
1129

1130
    def rebuild_compiled_components(self, arch, env):
6 ✔
1131
        info('Rebuilding compiled components in {}'.format(self.name))
×
1132

1133
        hostpython = sh.Command(self.real_hostpython_location)
×
1134
        shprint(hostpython, 'setup.py', 'clean', '--all', _env=env)
×
1135
        shprint(hostpython, 'setup.py', self.build_cmd, '-v', _env=env,
×
1136
                *self.setup_extra_args)
1137

1138

1139
class CppCompiledComponentsPythonRecipe(CompiledComponentsPythonRecipe):
6 ✔
1140
    """ Extensions that require the cxx-stl """
1141
    call_hostpython_via_targetpython = False
6 ✔
1142
    need_stl_shared = True
6 ✔
1143

1144

1145
class CythonRecipe(PythonRecipe):
6 ✔
1146
    pre_build_ext = False
6 ✔
1147
    cythonize = True
6 ✔
1148
    cython_args = []
6 ✔
1149
    call_hostpython_via_targetpython = False
6 ✔
1150

1151
    def __init__(self, *args, **kwargs):
6 ✔
1152
        super().__init__(*args, **kwargs)
6 ✔
1153
        self.cython_args = list(self.cython_args)
6 ✔
1154

1155
    def build_arch(self, arch):
6 ✔
1156
        '''Build any cython components, then install the Python module by
1157
        calling pip install with the target Python dir.
1158
        '''
1159
        self.install_hostpython_prerequisites()
×
1160
        Recipe.build_arch(self, arch)
×
1161
        self.build_cython_components(arch)
×
1162
        self.install_python_package(arch)
×
1163

1164
    def build_cython_components(self, arch):
6 ✔
1165
        info('Cythonizing anything necessary in {}'.format(self.name))
6 ✔
1166

1167
        env = self.get_recipe_env(arch)
6 ✔
1168

1169
        with current_directory(self.get_build_dir(arch.arch)):
6 ✔
1170
            hostpython = sh.Command(self.ctx.hostpython)
6 ✔
1171
            shprint(hostpython, '-c', 'import sys; print(sys.path)', _env=env)
6 ✔
1172
            debug('cwd is {}'.format(realpath(curdir)))
6 ✔
1173
            info('Trying first build of {} to get cython files: this is '
6 ✔
1174
                 'expected to fail'.format(self.name))
1175

1176
            manually_cythonise = False
6 ✔
1177
            try:
6 ✔
1178
                shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env,
6 ✔
1179
                        *self.setup_extra_args)
1180
            except sh.ErrorReturnCode_1:
×
1181
                print()
×
1182
                info('{} first build failed (as expected)'.format(self.name))
×
1183
                manually_cythonise = True
×
1184

1185
            if manually_cythonise:
6 !
1186
                self.cythonize_build(env=env)
×
1187
                shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env,
×
1188
                        _tail=20, _critical=True, *self.setup_extra_args)
1189
            else:
1190
                info('First build appeared to complete correctly, skipping manual'
6 ✔
1191
                     'cythonising.')
1192

1193
            if not self.ctx.with_debug_symbols:
6 ✔
1194
                self.strip_object_files(arch, env)
6 ✔
1195

1196
    def strip_object_files(self, arch, env, build_dir=None):
6 ✔
1197
        if build_dir is None:
6 ✔
1198
            build_dir = self.get_build_dir(arch.arch)
6 ✔
1199
        with current_directory(build_dir):
6 ✔
1200
            info('Stripping object files')
6 ✔
1201
            shprint(sh.find, '.', '-iname', '*.so', '-print', _env=env)
6 ✔
1202
            shprint(sh.find, '.', '-iname', '*.so', '-exec',
6 ✔
1203
                    env['STRIP'].split(' ')[0], '--strip-unneeded',
1204
                    # '/usr/bin/strip', '--strip-unneeded',
1205
                    '{}', ';', _env=env)
1206

1207
    def cythonize_file(self, env, build_dir, filename):
6 ✔
1208
        short_filename = filename
×
1209
        if filename.startswith(build_dir):
×
1210
            short_filename = filename[len(build_dir) + 1:]
×
1211
        info(u"Cythonize {}".format(short_filename))
×
1212
        cyenv = env.copy()
×
1213
        if 'CYTHONPATH' in cyenv:
×
1214
            cyenv['PYTHONPATH'] = cyenv['CYTHONPATH']
×
1215
        elif 'PYTHONPATH' in cyenv:
×
1216
            del cyenv['PYTHONPATH']
×
1217
        if 'PYTHONNOUSERSITE' in cyenv:
×
1218
            cyenv.pop('PYTHONNOUSERSITE')
×
1219
        python_command = sh.Command("python{}".format(
×
1220
            self.ctx.python_recipe.major_minor_version_string.split(".")[0]
1221
        ))
1222
        shprint(python_command, "-c"
×
1223
                "import sys; from Cython.Compiler.Main import setuptools_main; sys.exit(setuptools_main());",
1224
                filename, *self.cython_args, _env=cyenv)
1225

1226
    def cythonize_build(self, env, build_dir="."):
6 ✔
1227
        if not self.cythonize:
×
1228
            info('Running cython cancelled per recipe setting')
×
1229
            return
×
1230
        info('Running cython where appropriate')
×
1231
        for root, dirnames, filenames in walk("."):
×
1232
            for filename in fnmatch.filter(filenames, "*.pyx"):
×
1233
                self.cythonize_file(env, build_dir, join(root, filename))
×
1234

1235
    def get_recipe_env(self, arch, with_flags_in_cc=True):
6 ✔
1236
        env = super().get_recipe_env(arch, with_flags_in_cc)
×
1237
        env['LDFLAGS'] = env['LDFLAGS'] + ' -L{} '.format(
×
1238
            self.ctx.get_libs_dir(arch.arch) +
1239
            ' -L{} '.format(self.ctx.libs_dir) +
1240
            ' -L{}'.format(join(self.ctx.bootstrap.build_dir, 'obj', 'local',
1241
                                arch.arch)))
1242

1243
        env['LDSHARED'] = env['CC'] + ' -shared'
×
1244
        # shprint(sh.whereis, env['LDSHARED'], _env=env)
1245
        env['LIBLINK'] = 'NOTNONE'
×
1246
        if self.ctx.copy_libs:
×
1247
            env['COPYLIBS'] = '1'
×
1248

1249
        # Every recipe uses its own liblink path, object files are
1250
        # collected and biglinked later
1251
        liblink_path = join(self.get_build_container_dir(arch.arch),
×
1252
                            'objects_{}'.format(self.name))
1253
        env['LIBLINK_PATH'] = liblink_path
×
1254
        ensure_dir(liblink_path)
×
1255

1256
        return env
×
1257

1258

1259
def retag_wheel(path, platform_tag):
6 ✔
1260
    """Retag a built wheel using wheel's CLI, including WHEEL and RECORD."""
1261
    result = subprocess.run(
6 ✔
1262
        [executable, '-m', 'wheel', 'tags', '--platform-tag',
1263
         platform_tag, '--remove', path],
1264
        capture_output=True, text=True,
1265
    )
1266
    if result.returncode:
6 ✔
1267
        raise RuntimeError(
6 ✔
1268
            f'wheel tags failed (exit {result.returncode}): {result.stderr.strip()}'
1269
        )
1270
    wheel_tag = result.stdout.strip()
6 ✔
1271
    if not wheel_tag or basename(wheel_tag) != wheel_tag or not wheel_tag.endswith('.whl'):
6 !
1272
        raise ValueError(f'Unexpected wheel tags output: {wheel_tag!r}')
×
1273
    selected_wheel = join(dirname(path), wheel_tag)
6 ✔
1274
    if not isfile(selected_wheel):
6 !
1275
        raise FileNotFoundError(selected_wheel)
×
1276
    return selected_wheel
6 ✔
1277

1278

1279
class PyProjectRecipe(PythonRecipe):
6 ✔
1280
    """Recipe for projects which contain `pyproject.toml`"""
1281

1282
    # Extra args to pass to `python -m build ...`
1283
    extra_build_args = []
6 ✔
1284
    call_hostpython_via_targetpython = False
6 ✔
1285

1286
    def __init__(self, *args, **kwargs):
6 ✔
1287
        super().__init__(*args, **kwargs)
6 ✔
1288
        self.extra_build_args = list(self.extra_build_args)
6 ✔
1289

1290
    def get_pip_name(self):
6 ✔
1291
        name_str = self.name
×
1292
        if self.name not in self.ctx.use_prebuilt_version_for and self.version is not None:
×
1293
            # Like: v2.3.0 -> 2.3.0
1294
            cleaned_version = self.version.lstrip("v")
×
1295
            name_str += f"=={cleaned_version}"
×
1296
        return name_str
×
1297

1298
    def get_pip_install_args(self, arch):
6 ✔
1299
        python_recipe = Recipe.get_recipe("python3", self.ctx)
×
1300
        opts = [
×
1301
            "install",
1302
            self.get_pip_name(),
1303
            "--ignore-installed",
1304
            "--disable-pip-version-check",
1305
            "--python-version",
1306
            python_recipe.version,
1307
            "--only-binary=:all:",
1308
            "--no-deps",
1309
        ]
1310
        # add platform tags
1311
        tags = PyProjectRecipe.get_wheel_platform_tags(arch.arch, self.ctx)
×
1312
        for tag in tags:
×
1313
            opts.append(f"--platform={tag}")
×
1314

1315
        # add extra index urls
1316
        for index in self.ctx.extra_index_urls:
×
1317
            opts.extend(["--extra-index-url", index])
×
1318

1319
        return opts
×
1320

1321
    def lookup_prebuilt(self, arch):
6 ✔
1322
        pip_options = self.get_pip_install_args(arch)
×
1323
        # do not install
1324
        pip_options.extend(["--dry-run", "-q"])
×
1325
        pip_env = self.get_hostrecipe_env()
×
1326
        try:
×
1327
            shprint(self._host_recipe.pip, *pip_options, _env=pip_env, silent=True)
×
1328
        except Exception:
×
1329
            return False
×
1330
        return True
×
1331

1332
    def check_prebuilt(self, arch, msg=""):
6 ✔
1333
        if self.ctx.skip_prebuilt:
×
1334
            return False
×
1335

1336
        if self.lookup_prebuilt(arch):
×
1337
            if msg != "":
×
1338
                info(f"Prebuilt pip wheel found, {msg}")
×
1339
            return True
×
1340

1341
        return False
×
1342

1343
    def get_recipe_env(self, arch, **kwargs):
6 ✔
1344
        env = super().get_recipe_env(arch, **kwargs)
6 ✔
1345
        build_dir = self.get_build_dir(arch)
6 ✔
1346
        ensure_dir(build_dir)
6 ✔
1347
        build_opts = join(build_dir, "build-opts.cfg")
6 ✔
1348

1349
        with open(build_opts, "w") as file:
6 ✔
1350
            file.write("[bdist_wheel]\nplat_name={}".format(
6 ✔
1351
                self.get_wheel_platform_tag(arch.arch)
1352
            ))
1353
            file.close()
6 ✔
1354

1355
        env["DIST_EXTRA_CONFIG"] = build_opts
6 ✔
1356
        python_recipe = Recipe.get_recipe("python3", self.ctx)
6 ✔
1357
        env["INCLUDEPY"] = python_recipe.include_root(arch.arch)
6 ✔
1358
        return env
6 ✔
1359

1360
    @staticmethod
6 ✔
1361
    def get_wheel_platform_tags(arch, ctx):
6 ✔
1362
        # https://peps.python.org/pep-0738/#packaging
1363
        # official python only supports 64 bit:
1364
        # android_21_arm64_v8a
1365
        # android_21_x86_64
1366
        _suffix = {
6 ✔
1367
            "arm64-v8a": ["arm64_v8a", "aarch64"],
1368
            "x86_64": ["x86_64"],
1369
            "armeabi-v7a": ["arm"],
1370
            "x86": ["i686"],
1371
        }[arch]
1372
        return [f"android_{ctx.ndk_api}_" + _ for _ in _suffix]
6 ✔
1373

1374
    def get_wheel_platform_tag(self, arch):
6 ✔
1375
        return PyProjectRecipe.get_wheel_platform_tags(arch, self.ctx)[0]
6 ✔
1376

1377
    def install_prebuilt_wheel(self, arch):
6 ✔
1378
        info("Installing prebuilt wheel")
×
1379
        destination = self.ctx.get_python_install_dir(arch.arch)
×
1380
        pip_options = self.get_pip_install_args(arch)
×
1381
        pip_options.extend(["--target", destination])
×
1382
        pip_options.append("--upgrade")
×
1383
        pip_env = self.get_hostrecipe_env()
×
1384
        try:
×
1385
            shprint(self._host_recipe.pip, *pip_options, _env=pip_env)
×
1386
        except Exception:
×
1387
            return False
×
1388
        return True
×
1389

1390
    def install_wheel(self, arch, built_wheels):
6 ✔
1391
        with patch_wheel_setuptools_logging():
6 ✔
1392
            from wheel.wheelfile import WheelFile
6 ✔
1393
        # Fix wheel platform tag
1394
        selected_wheel = retag_wheel(
6 ✔
1395
            built_wheels[0], self.get_wheel_platform_tag(arch.arch)
1396
        )
1397
        wheel_tag = basename(selected_wheel)
6 ✔
1398
        _dev_wheel_dir = environ.get("P4A_WHEEL_DIR", False)
6 ✔
1399
        if _dev_wheel_dir:
6 !
1400
            ensure_dir(_dev_wheel_dir)
6 ✔
1401
            shprint(sh.cp, selected_wheel, _dev_wheel_dir)
6 ✔
1402

1403
        if exists(self.ctx.save_wheel_dir):
6 !
1404
            shprint(sh.cp, selected_wheel, self.ctx.save_wheel_dir)
6 ✔
1405

1406
        info(f"Installing built wheel: {wheel_tag}")
6 ✔
1407
        destination = self.ctx.get_python_install_dir(arch.arch)
6 ✔
1408
        with WheelFile(selected_wheel) as wf:
6 ✔
1409
            for zinfo in wf.filelist:
6 ✔
1410
                wf.extract(zinfo, destination)
6 ✔
1411

1412
    def build_arch(self, arch):
6 ✔
1413
        if self.check_prebuilt(arch, "skipping build_arch"):
×
1414
            result = self.install_prebuilt_wheel(arch)
×
1415
            if result:
×
1416
                return
×
1417
            warning("Failed to install prebuilt wheel, falling back to build_arch")
×
1418

1419
        build_dir = self.get_build_dir(arch.arch)
×
1420
        if not (isfile(join(build_dir, "pyproject.toml")) or isfile(join(build_dir, "setup.py"))):
×
1421
            warning("Skipping build because it does not appear to be a Python project.")
×
1422
            return
×
1423
        self.install_hostpython_prerequisites(
×
1424
            packages=["build[virtualenv]", "pip", "setuptools", "patchelf"] + self.hostpython_prerequisites
1425
        )
1426

1427
        env = self.get_recipe_env(arch, with_flags_in_cc=True)
×
1428
        # make build dir separately
1429
        sub_build_dir = join(build_dir, "p4a_android_build")
×
1430
        ensure_dir(sub_build_dir)
×
1431

1432
        build_args = [
×
1433
            "-m",
1434
            "build",
1435
            "--wheel",
1436
            "--config-setting",
1437
            "builddir={}".format(sub_build_dir),
1438
        ] + self.extra_build_args
1439

1440
        built_wheels = []
×
1441
        with current_directory(build_dir):
×
1442
            shprint(
×
1443
                sh.Command(self.real_hostpython_location), *build_args, _env=env
1444
            )
1445
            built_wheels = [realpath(whl) for whl in glob.glob("dist/*.whl")]
×
1446
        self.install_wheel(arch, built_wheels)
×
1447

1448

1449
class MesonRecipe(PyProjectRecipe):
6 ✔
1450
    '''Recipe for projects which uses meson as build system'''
1451

1452
    meson_version = "1.4.0"
6 ✔
1453
    pybind_version = "3.3.0"
6 ✔
1454

1455
    skip_python = False
6 ✔
1456
    '''If true, skips all Python build and installation steps.
6 ✔
1457
    Useful for Meson projects written purely in C/C++ without Python bindings.'''
1458

1459
    def sanitize_flags(self, *flag_strings):
6 ✔
1460
        return " ".join(flag_strings).strip().split(" ")
×
1461

1462
    def get_wrapper_dir(self, arch):
6 ✔
1463
        return join(self.get_build_dir(arch.arch), "p4a_wrappers")
×
1464

1465
    def write_wrapper(self, arch, name, content):
6 ✔
1466
        wrapper_dir = self.get_wrapper_dir(arch)
×
1467
        ensure_dir(wrapper_dir)
×
1468
        wrapper_path = join(wrapper_dir, name)
×
1469
        with open(wrapper_path, "w") as f:
×
1470
            f.write(content)
×
1471
        chmod(wrapper_path, 0o755)
×
1472
        return wrapper_path
×
1473

1474
    def get_python_wrapper(self, arch):
6 ✔
1475
        """
1476
        Meson Python introspection runs on the host interpreter, but the
1477
        target Python (Android) cannot be executed on the build machine.
1478

1479
        We therefore run host Python and override sysconfig data to emulate
1480
        the target Android Python environment during Meson introspection.
1481
        """
1482
        python_recipe = Recipe.get_recipe('python3', self.ctx)
×
1483
        target_prefix = python_recipe.get_python_root(arch)
×
1484
        python_file = join(self.ctx.root_dir, 'meson_python.py')
×
1485
        _arch = {
×
1486
            "arm64-v8a": ["aarch64"],
1487
            "x86_64": ["x86_64"],
1488
            "armeabi-v7a": ["arm"],
1489
            "x86": ["i686"],
1490
        }[arch.arch][0]
1491

1492
        # Real values pulled from android
1493
        # PYTHON_MAJOR_VERSION -> 3
1494
        # PYTHON_MINOR_VERSION -> 14
1495
        # PLATFORM_TAG eg -> 'android-24-arm64_v8a'
1496
        # PYTHON_SUFFIX eg -> '.cpython-314-aarch64-linux-android.so'
1497

1498
        _p_version = Version(python_recipe.version)
×
1499
        file_data = f"#!{self.real_hostpython_location}"
×
1500
        file_data += f"\nTARGET_PYTHON_PREFIX='{target_prefix}'"
×
1501
        file_data += f"\nPYTHON_MAJOR_VERSION='{_p_version.major}'"
×
1502
        file_data += f"\nPYTHON_MINOR_VERSION='{_p_version.minor}'"
×
1503
        file_data += f"\nPLATFORM_TAG='{self.get_wheel_platform_tags(arch.arch, self.ctx)[0]}'"
×
1504
        file_data += f"\nPYTHON_SUFFIX='.cpython-{_p_version.major}{_p_version.minor}-{_arch}-linux-android.so'"
×
1505

1506
        with open(python_file, "r") as f:
×
1507
            file_data += "\n" + f.read()
×
1508

1509
        return self.write_wrapper(arch, "python", file_data)
×
1510

1511
    def get_config_wrappers(self, arch, w_type: str):
6 ✔
1512
        wrapper_name = ""
×
1513
        version = ""
×
1514
        include_path = ""
×
1515

1516
        if w_type == "pybind11":
×
1517
            wrapper_name = "pybind11-config"
×
1518
            include_path = join(self._host_recipe.site_dir, "pybind11/include")
×
1519

1520
            version = None
×
1521
            try:
×
1522
                command = [self._host_recipe.real_hostpython_location, "-c", "import pybind11; print(pybind11.__version__)"]
×
1523
                version = subprocess.check_output(command).decode('utf-8').strip()
×
1524
            except Exception:
×
1525
                warning("Unable to get pybind11 version")
×
1526
            if version is None:
×
1527
                version = self.pybind_version
×
1528

1529
        elif w_type == "numpy":
×
1530
            wrapper_name = "numpy-config"
×
1531
            recipe = Recipe.get_recipe("numpy", self.ctx)
×
1532
            include_path = recipe.get_include(arch)
×
1533
            version = recipe.version
×
1534
        else:
1535
            raise ValueError(f"Unknown wrapper type: {w_type}")
×
1536

1537
        content = (
×
1538
            f"#!/bin/sh\n"
1539
            f"if [ \"$1\" = \"--version\" ]; then\n"
1540
            f"    echo '{version}'\n"
1541
            f"else\n"
1542
            f"    echo '-I{include_path}'\n"
1543
            f"fi\n"
1544
        )
1545
        return self.write_wrapper(arch, wrapper_name, content)
×
1546

1547
    def get_recipe_meson_options(self, arch):
6 ✔
1548
        env = self.get_recipe_env(arch, with_flags_in_cc=True)
×
1549
        return {
×
1550
            "binaries": {
1551
                "pybind11-config": self.get_config_wrappers(arch, "pybind11"),
1552
                "numpy-config": self.get_config_wrappers(arch, "numpy"),
1553
                "python": self.get_python_wrapper(arch),
1554
                "c": arch.get_clang_exe(with_target=True),
1555
                "cpp": arch.get_clang_exe(with_target=True, plus_plus=True),
1556
                "ar": self.ctx.ndk.llvm_ar,
1557
                "strip": self.ctx.ndk.llvm_strip,
1558
            },
1559
            "built-in options": {
1560
                "c_args": self.sanitize_flags(env["CFLAGS"], env["CPPFLAGS"]),
1561
                "cpp_args": self.sanitize_flags(env["CXXFLAGS"], env["CPPFLAGS"]),
1562
                "c_link_args": self.sanitize_flags(env["LDFLAGS"]),
1563
                "cpp_link_args": self.sanitize_flags(env["LDFLAGS"]),
1564
                "fortran_link_args": self.sanitize_flags(env["LDFLAGS"]),
1565
            },
1566
            "properties": {
1567
                "needs_exe_wrapper": True,
1568
                "sys_root": self.ctx.ndk.sysroot
1569
            },
1570
            "host_machine": {
1571
                "cpu_family": {
1572
                    "arm64-v8a": "aarch64",
1573
                    "armeabi-v7a": "arm",
1574
                    "x86_64": "x86_64",
1575
                    "x86": "x86"
1576
                }[arch.arch],
1577
                "cpu": {
1578
                    "arm64-v8a": "aarch64",
1579
                    "armeabi-v7a": "armv7",
1580
                    "x86_64": "x86_64",
1581
                    "x86": "i686"
1582
                }[arch.arch],
1583
                "endian": "little",
1584
                "system": "android",
1585
            }
1586
        }
1587

1588
    def write_build_options(self, arch):
6 ✔
1589
        """Writes python dict to meson config file"""
1590
        option_data = ""
×
1591
        build_options = self.get_recipe_meson_options(arch)
×
1592
        for key in build_options.keys():
×
1593
            data_chunk = "[{}]".format(key)
×
1594
            for subkey in build_options[key].keys():
×
1595
                value = build_options[key][subkey]
×
1596
                if isinstance(value, int):
×
1597
                    value = str(value)
×
1598
                elif isinstance(value, str):
×
1599
                    value = "'{}'".format(value)
×
1600
                elif isinstance(value, bool):
×
1601
                    value = "true" if value else "false"
×
1602
                elif isinstance(value, list):
×
1603
                    value = "['" + "', '".join(value) + "']"
×
1604
                data_chunk += "\n" + subkey + " = " + value
×
1605
            option_data += data_chunk + "\n\n"
×
1606
        return option_data
×
1607

1608
    def ensure_args(self, *args):
6 ✔
1609
        for arg in args:
6 ✔
1610
            if arg not in self.extra_build_args:
6 !
1611
                self.extra_build_args.append(arg)
6 ✔
1612

1613
    def get_recipe_env_command(self, command, env):
6 ✔
1614
        command_path = shutil.which(command, path=env["PATH"])
6 ✔
1615
        if command_path is None:
6 !
1616
            raise sh.CommandNotFound(command)
×
1617
        return sh.Command(command_path)
6 ✔
1618

1619
    def get_meson_command(self, env):
6 ✔
1620
        return self.get_recipe_env_command("meson", env)
6 ✔
1621

1622
    def get_ninja_command(self, env):
6 ✔
1623
        return self.get_recipe_env_command("ninja", env)
×
1624

1625
    def build_arch(self, arch):
6 ✔
1626
        cross_file = join("/tmp", "android.meson.cross")
×
1627
        info("Writing cross file at: {}".format(cross_file))
×
1628
        # write cross config file
1629
        with open(cross_file, "w") as file:
×
1630
            file.write(self.write_build_options(arch))
×
1631
            file.close()
×
1632
        # set cross file
1633
        self.ensure_args('-Csetup-args=--cross-file', '-Csetup-args={}'.format(cross_file))
×
1634
        # ensure ninja and meson
1635
        for dep in [
×
1636
            "ninja",
1637
            "meson=={}".format(self.meson_version),
1638
        ]:
1639
            if dep not in self.hostpython_prerequisites:
×
1640
                self.hostpython_prerequisites.append(dep)
×
1641

1642
        if not self.skip_python:
×
1643
            super().build_arch(arch)
×
1644
        else:
1645
            self.install_hostpython_prerequisites(
×
1646
                packages=["build[virtualenv]", "pip", "setuptools", "patchelf"] + self.hostpython_prerequisites
1647
            )
1648

1649

1650
class RustCompiledComponentsRecipe(PyProjectRecipe):
6 ✔
1651
    # Rust toolchain codes
1652
    # https://doc.rust-lang.org/nightly/rustc/platform-support.html
1653
    RUST_ARCH_CODES = {
6 ✔
1654
        "arm64-v8a": "aarch64-linux-android",
1655
        "armeabi-v7a": "armv7-linux-androideabi",
1656
        "x86_64": "x86_64-linux-android",
1657
        "x86": "i686-linux-android",
1658
    }
1659

1660
    def get_recipe_env(self, arch, **kwargs):
6 ✔
1661
        env = super().get_recipe_env(arch, **kwargs)
×
1662

1663
        # Set rust build target
1664
        build_target = self.RUST_ARCH_CODES[arch.arch]
×
1665
        cargo_linker_name = "CARGO_TARGET_{}_LINKER".format(
×
1666
            build_target.upper().replace("-", "_")
1667
        )
1668
        env["CARGO_BUILD_TARGET"] = build_target
×
1669
        env[cargo_linker_name] = join(
×
1670
            self.ctx.ndk.llvm_prebuilt_dir,
1671
            "bin",
1672
            "{}{}-clang".format(
1673
                # NDK's Clang format
1674
                build_target.replace("7", "7a")
1675
                if build_target.startswith("armv7")
1676
                else build_target,
1677
                self.ctx.ndk_api,
1678
            ),
1679
        )
1680
        realpython_dir = self.ctx.python_recipe.get_build_dir(arch.arch)
×
1681

1682
        # maturin (used by every Rust recipe here) refuses to build without the
1683
        # target Android API level: "Failed to determine Android API level."
1684
        env["ANDROID_API_LEVEL"] = str(self.ctx.ndk_api)
×
1685

1686
        env["RUSTFLAGS"] = "-Clink-args=-L{} -L{}".format(
×
1687
            self.ctx.get_libs_dir(arch.arch), join(realpython_dir, "android-build")
1688
        )
1689
        env["RUSTFLAGS"] += f" -Clink-arg=-lpython{self.ctx.python_recipe.link_version}"
×
1690

1691
        env["PYO3_CROSS_LIB_DIR"] = realpath(glob.glob(join(
×
1692
            realpython_dir, "android-build", "build",
1693
            "lib.*{}/".format(self.python_major_minor_version),
1694
        ))[0])
1695

1696
        info_main("Ensuring rust build toolchain")
×
1697
        shprint(sh.rustup, "target", "add", build_target)
×
1698

1699
        # Add host python to PATH
1700
        env["PATH"] = ("{hostpython_dir}:{old_path}").format(
×
1701
            hostpython_dir=Recipe.get_recipe(
1702
                "hostpython3", self.ctx
1703
            ).local_bin,
1704
            old_path=env["PATH"],
1705
        )
1706
        return env
×
1707

1708
    def check_host_deps(self):
6 ✔
1709
        if not hasattr(sh, "rustup"):
×
1710
            error(
×
1711
                "`rustup` was not found on host system."
1712
                "Please install it using :"
1713
                "\n`curl https://sh.rustup.rs -sSf | sh`\n"
1714
            )
1715
            exit(1)
×
1716

1717
    def build_arch(self, arch):
6 ✔
1718
        self.check_host_deps()
×
1719
        super().build_arch(arch)
×
1720

1721

1722
class TargetPythonRecipe(Recipe):
6 ✔
1723
    '''Class for target python recipes. Sets ctx.python_recipe to point to
1724
    itself, so as to know later what kind of Python was built or used.'''
1725

1726
    def __init__(self, *args, **kwargs):
6 ✔
1727
        self._ctx = None
6 ✔
1728
        super().__init__(*args, **kwargs)
6 ✔
1729

1730
    def prebuild_arch(self, arch):
6 ✔
1731
        super().prebuild_arch(arch)
×
1732
        self.ctx.python_recipe = self
×
1733

1734
    def include_root(self, arch):
6 ✔
1735
        '''The root directory from which to include headers.'''
1736
        raise NotImplementedError('Not implemented in TargetPythonRecipe')
1737

1738
    def link_root(self):
6 ✔
1739
        raise NotImplementedError('Not implemented in TargetPythonRecipe')
1740

1741
    @property
6 ✔
1742
    def major_minor_version_string(self):
6 ✔
1743
        parsed_version = packaging.version.parse(self.version)
6 ✔
1744
        return f"{parsed_version.major}.{parsed_version.minor}"
6 ✔
1745

1746
    def create_python_bundle(self, dirn, arch):
6 ✔
1747
        """
1748
        Create a packaged python bundle in the target directory, by
1749
        copying all the modules and standard library to the right
1750
        place.
1751
        """
1752
        raise NotImplementedError('{} does not implement create_python_bundle'.format(self))
1753

1754
    def reduce_object_file_names(self, dirn):
6 ✔
1755
        """Recursively renames all files named XXX.cpython-...-linux-gnu.so"
1756
        to "XXX.so", i.e. removing the erroneous architecture name
1757
        coming from the local system.
1758
        """
1759
        py_so_files = shprint(sh.find, dirn, '-iname', '*.so')
×
1760
        filens = py_so_files.stdout.decode('utf-8').split('\n')[:-1]
×
1761
        for filen in filens:
×
1762
            file_dirname, file_basename = split(filen)
×
1763
            parts = file_basename.split('.')
×
1764
            if len(parts) <= 2:
×
1765
                continue
×
1766
            # PySide6 libraries end with .abi3.so
1767
            if parts[1] == "abi3":
×
1768
                continue
×
1769
            move(filen, join(file_dirname, parts[0] + '.so'))
×
1770

1771

1772
def algsum(alg, filen):
6 ✔
1773
    '''Calculate the digest of a file.
1774
    '''
1775
    with open(filen, 'rb') as fileh:
×
1776
        digest = getattr(hashlib, alg)(fileh.read())
×
1777

1778
    return digest.hexdigest()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc