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

kivy / python-for-android / 46133526156

28 Nov 2026 10:05AM UTC coverage: 62.868% (-0.8%) from 63.674%
46133526156

Pull #3420

github

web-flow
Merge fdb345bff into da1e1b20f
Pull Request #3420: recipes: new mpv recipe

1913 of 3286 branches covered (58.22%)

Branch coverage included in aggregate %.

70 of 235 new or added lines in 7 files covered. (29.79%)

366 existing lines in 4 files now uncovered.

5562 of 8604 relevant lines covered (64.64%)

3.88 hits per line

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

49.74
/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:
×
UNCOV
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:
×
UNCOV
232
                    progression = '{0} bytes'.format(index * blksize)
×
233
                else:
UNCOV
234
                    progression = '{0:.2f}%'.format(
×
235
                        index * blksize * 100. / float(size))
UNCOV
236
                if "CI" not in environ:
×
UNCOV
237
                    stdout.write('- Download {}\r'.format(progression))
×
UNCOV
238
                    stdout.flush()
×
239

240
            if exists(target):
6 !
UNCOV
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 !
UNCOV
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 ✔
UNCOV
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)
×
UNCOV
278
            with current_directory(target):
×
UNCOV
279
                if self.version:
×
UNCOV
280
                    shprint(sh.git, 'fetch', '--tags', '--depth', '1')
×
UNCOV
281
                    shprint(sh.git, 'checkout', self.version)
×
UNCOV
282
                branch = sh.git('branch', '--show-current')
×
UNCOV
283
                if branch:
×
UNCOV
284
                    shprint(sh.git, 'pull')
×
UNCOV
285
                    shprint(sh.git, 'pull', '--recurse-submodules')
×
UNCOV
286
                shprint(sh.git, 'submodule', 'update', '--recursive', '--init', '--depth', '1')
×
UNCOV
287
            return target
×
288

289
    def apply_patch(self, filename, arch, build_dir=None):
6 ✔
290
        """
291
        Apply a patch from the current recipe directory into the current
292
        build directory.
293

294
        .. versionchanged:: 0.6.0
295
            Add ability to apply patch from any dir via kwarg `build_dir`'''
296
        """
297
        info("Applying patch {}".format(filename))
6 ✔
298
        build_dir = build_dir if build_dir else self.get_build_dir(arch)
6 ✔
299
        filename = join(self.get_recipe_dir(), filename)
6 ✔
300
        shprint(sh.patch, "-t", "-d", build_dir, "-p1",
6 ✔
301
                "-i", filename, _tail=10)
302

303
    def copy_file(self, filename, dest):
6 ✔
304
        info("Copy {} to {}".format(filename, dest))
×
305
        filename = join(self.get_recipe_dir(), filename)
×
306
        dest = join(self.build_dir, dest)
×
UNCOV
307
        shutil.copy(filename, dest)
×
308

309
    def append_file(self, filename, dest):
6 ✔
UNCOV
310
        info("Append {} to {}".format(filename, dest))
×
UNCOV
311
        filename = join(self.get_recipe_dir(), filename)
×
UNCOV
312
        dest = join(self.build_dir, dest)
×
UNCOV
313
        with open(filename, "rb") as fd:
×
UNCOV
314
            data = fd.read()
×
UNCOV
315
        with open(dest, "ab") as fd:
×
UNCOV
316
            fd.write(data)
×
317

318
    @property
6 ✔
319
    def name(self):
6 ✔
320
        '''The name of the recipe, the same as the folder containing it.'''
321
        modname = self.__class__.__module__
6 ✔
322
        return modname.split(".", 2)[-1]
6 ✔
323

324
    @property
6 ✔
325
    def filtered_archs(self):
6 ✔
326
        '''Return archs of self.ctx that are valid build archs
327
        for the Recipe.'''
UNCOV
328
        result = []
×
UNCOV
329
        for arch in self.ctx.archs:
×
UNCOV
330
            if not self.archs or (arch.arch in self.archs):
×
UNCOV
331
                result.append(arch)
×
332
        return result
×
333

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

351
    def get_opt_depends_in_list(self, recipes):
6 ✔
352
        '''Given a list of recipe names, returns those that are also in
353
        self.opt_depends.
354
        '''
355
        return [recipe for recipe in recipes if recipe in self.opt_depends]
6 ✔
356

357
    def get_build_container_dir(self, arch):
6 ✔
358
        '''Given the arch name, returns the directory where it will be
359
        built.
360

361
        This returns a different directory depending on what
362
        alternative or optional dependencies are being built.
363
        '''
364
        dir_name = self.get_dir_name()
6 ✔
365
        return join(self.ctx.build_dir, 'other_builds',
6 ✔
366
                    dir_name, '{}__ndk_target_{}'.format(arch, self.ctx.ndk_api))
367

368
    def get_dir_name(self):
6 ✔
369
        choices = self.check_recipe_choices()
6 ✔
370
        dir_name = '-'.join([self.name] + choices)
6 ✔
371
        return dir_name
6 ✔
372

373
    def get_build_dir(self, arch):
6 ✔
374
        '''Given the arch name, returns the directory where the
375
        downloaded/copied package will be built.'''
376

377
        return join(self.get_build_container_dir(arch), self.name)
6 ✔
378

379
    def get_recipe_dir(self):
6 ✔
380
        """
381
        Returns the local recipe directory or defaults to the core recipe
382
        directory.
383
        """
384
        if self.ctx.local_recipes is not None:
6 !
385
            local_recipe_dir = join(self.ctx.local_recipes, self.name)
×
UNCOV
386
            if exists(local_recipe_dir):
×
UNCOV
387
                return local_recipe_dir
×
388
        return join(self.ctx.root_dir, 'recipes', self.name)
6 ✔
389

390
    # Public Recipe API to be subclassed if needed
391

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

404
    def download(self):
6 ✔
405
        if self.url is None:
6 ✔
406
            info('Skipping {} download as no URL is set'.format(self.name))
6 ✔
407
            return
6 ✔
408

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

424
        ensure_dir(join(self.ctx.packages_path, self.name))
6 ✔
425

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

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

447
            # If we got this far, we will download
448
            if do_download:
6 !
449
                debug('Downloading {} from {}'.format(self.name, url))
6 ✔
450

451
                shprint(sh.rm, '-f', marker_filename)
6 ✔
452
                self.download_file(self.versioned_url, filename)
6 ✔
453
                touch(marker_filename)
6 ✔
454

455
                if exists(filename) and isfile(filename):
6 !
UNCOV
456
                    for alg, expected_digest in expected_digests.items():
×
457
                        current_digest = algsum(alg, filename)
×
UNCOV
458
                        if current_digest != expected_digest:
×
UNCOV
459
                            debug('* Generated {}sum: {}'.format(alg,
×
460
                                                                 current_digest))
UNCOV
461
                            debug('* Expected {}sum: {}'.format(alg,
×
462
                                                                expected_digest))
UNCOV
463
                            raise ValueError(
×
464
                                ('Generated {0}sum does not match expected {0}sum '
465
                                 'for {1} recipe').format(alg, self.name))
466
            else:
UNCOV
467
                info('{} download already cached, skipping'.format(self.name))
×
468

469
    def unpack(self, arch):
6 ✔
470
        info_main('Unpacking {} for {}'.format(self.name, arch))
×
471

472
        build_dir = self.get_build_container_dir(arch)
×
473

UNCOV
474
        user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower()))
×
475
        if user_dir is not None:
×
476
            info('P4A_{}_DIR exists, symlinking instead'.format(
×
477
                self.name.lower()))
UNCOV
478
            if exists(self.get_build_dir(arch)):
×
479
                return
×
UNCOV
480
            rmdir(build_dir)
×
481
            ensure_dir(build_dir)
×
482
            shprint(sh.cp, '-a', user_dir, self.get_build_dir(arch))
×
483
            return
×
484

485
        if self.url is None:
×
486
            info('Skipping {} unpack as no URL is set'.format(self.name))
×
UNCOV
487
            return
×
488

489
        filename = shprint(
×
490
            sh.basename, self.versioned_url).stdout[:-1].decode('utf-8')
491
        ma = match(u'^(.+)#[a-z0-9_]{3,}=([0-9a-f]{32,})$', filename)
×
492
        if ma:                  # fragmented URL?
×
493
            filename = ma.group(1)
×
494

495
        with current_directory(build_dir):
×
UNCOV
496
            directory_name = self.get_build_dir(arch)
×
497

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

538
            else:
539
                info('{} is already unpacked, skipping'.format(self.name))
×
540

541
    def get_recipe_env(self, arch=None, with_flags_in_cc=True):
6 ✔
542
        """Return the env specialized for the recipe
543
        """
544
        arch = arch or self.filtered_archs[0]
6 ✔
545
        env = arch.get_env(with_flags_in_cc=with_flags_in_cc)
6 ✔
546

547
        for proxy_key in ('HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy'):
6 ✔
548
            if proxy_key in environ:
6 !
549
                env[proxy_key] = environ[proxy_key]
×
550

551
        return env
6 ✔
552

553
    def prebuild_arch(self, arch):
6 ✔
554
        '''Run any pre-build tasks for the Recipe. By default, this checks if
555
        any prebuild_archname methods exist for the archname of the current
556
        architecture, and runs them if so.'''
557
        prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
6 ✔
558
        if hasattr(self, prebuild):
6 !
UNCOV
559
            getattr(self, prebuild)()
×
560
        else:
561
            info('{} has no {}, skipping'.format(self.name, prebuild))
6 ✔
562

563
    def is_patched(self, arch):
6 ✔
UNCOV
564
        build_dir = self.get_build_dir(arch.arch)
×
UNCOV
565
        return exists(join(build_dir, '.patched'))
×
566

567
    def apply_patches(self, arch, build_dir=None):
6 ✔
568
        '''Apply any patches for the Recipe.
569

570
        .. versionchanged:: 0.6.0
571
            Add ability to apply patches from any dir via kwarg `build_dir`'''
572
        if self.patches:
×
573
            info_main('Applying patches for {}[{}]'
×
574
                      .format(self.name, arch.arch))
575

UNCOV
576
            if self.is_patched(arch):
×
577
                info_main('{} already patched, skipping'.format(self.name))
×
UNCOV
578
                return
×
579

UNCOV
580
            build_dir = build_dir if build_dir else self.get_build_dir(arch.arch)
×
581
            for patch in self.patches:
×
UNCOV
582
                if isinstance(patch, (tuple, list)):
×
UNCOV
583
                    patch, patch_check = patch
×
UNCOV
584
                    if not patch_check(arch=arch, recipe=self):
×
UNCOV
585
                        continue
×
586

UNCOV
587
                self.apply_patch(
×
588
                        patch.format(version=self.version, arch=arch.arch),
589
                        arch.arch, build_dir=build_dir)
590

UNCOV
591
            touch(join(build_dir, '.patched'))
×
592

593
    def should_build(self, arch):
6 ✔
594
        '''Should perform any necessary test and return True only if it needs
595
        building again. Per default we implement a library test, in case that
596
        we detect so.
597
        '''
598
        if self.built_libraries:
6 !
599
            return not all(
6 ✔
600
                exists(lib) for lib in self.get_libraries(arch.arch)
601
            )
UNCOV
602
        return True
×
603

604
    def build_arch(self, arch):
6 ✔
605
        '''Run any build tasks for the Recipe. By default, this checks if
606
        any build_archname methods exist for the archname of the current
607
        architecture, and runs them if so.'''
UNCOV
608
        build = "build_{}".format(arch.arch)
×
609
        if hasattr(self, build):
×
UNCOV
610
            getattr(self, build)()
×
611

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

625
    def postbuild_arch(self, arch):
6 ✔
626
        '''Run any post-build tasks for the Recipe. By default, this checks if
627
        any postbuild_archname methods exist for the archname of the
628
        current architecture, and runs them if so.
629
        '''
630
        postbuild = "postbuild_{}".format(arch.arch)
6 ✔
631
        if hasattr(self, postbuild):
6 !
UNCOV
632
            getattr(self, postbuild)()
×
633

634
        if self.need_stl_shared:
6 !
635
            self.install_stl_lib(arch)
6 ✔
636

637
    def prepare_build_dir(self, arch):
6 ✔
638
        '''Copies the recipe data into a build dir for the given arch. By
639
        default, this unpacks a downloaded recipe. You should override
640
        it (or use a Recipe subclass with different behaviour) if you
641
        want to do something else.
642
        '''
UNCOV
643
        self.unpack(arch)
×
644

645
    def clean_build(self, arch=None):
6 ✔
646
        '''Deletes all the build information of the recipe.
647

648
        If arch is not None, only this arch dir is deleted. Otherwise
649
        (the default) all builds for all archs are deleted.
650

651
        By default, this just deletes the main build dir. If the
652
        recipe has e.g. object files biglinked, or .so files stored
653
        elsewhere, you should override this method.
654

655
        This method is intended for testing purposes, it may have
656
        strange results. Rebuild everything if this seems to happen.
657

658
        '''
UNCOV
659
        if arch is None:
×
660
            base_dir = join(self.ctx.build_dir, 'other_builds', self.name)
×
661
        else:
UNCOV
662
            base_dir = self.get_build_container_dir(arch)
×
UNCOV
663
        dirs = glob.glob(base_dir + '-*')
×
UNCOV
664
        if exists(base_dir):
×
665
            dirs.append(base_dir)
×
UNCOV
666
        if not dirs:
×
UNCOV
667
            warning('Attempted to clean build for {} but found no existing '
×
668
                    'build dirs'.format(self.name))
669

670
        for directory in dirs:
×
671
            rmdir(directory)
×
672

673
        # Delete any Python distributions to ensure the recipe build
674
        # doesn't persist in site-packages
UNCOV
675
        rmdir(self.ctx.python_installs_dir)
×
676

677
    def install_libs(self, arch, *libs):
6 ✔
678
        libs_dir = self.ctx.get_libs_dir(arch.arch)
6 ✔
679
        if not libs:
6 !
UNCOV
680
            warning('install_libs called with no libraries to install!')
×
UNCOV
681
            return
×
682
        args = libs + (libs_dir,)
6 ✔
683
        shprint(sh.cp, *args)
6 ✔
684

685
    def has_libs(self, arch, *libs):
6 ✔
UNCOV
686
        return all(map(lambda lib: self.ctx.has_lib(arch.arch, lib), libs))
×
687

688
    def get_libraries(self, arch_name, in_context=False):
6 ✔
689
        """Return the full path of the library depending on the architecture.
690
        Per default, the build library path it will be returned, unless
691
        `get_libraries` has been called with kwarg `in_context` set to
692
        True.
693

694
        .. note:: this method should be used for library recipes only
695
        """
696
        recipe_libs = set()
6 ✔
697
        if not self.built_libraries:
6 !
UNCOV
698
            return recipe_libs
×
699
        for lib, rel_path in self.built_libraries.items():
6 ✔
700
            if not in_context:
6 !
701
                abs_path = join(self.get_build_dir(arch_name), rel_path, lib)
6 ✔
702
                if rel_path in {".", "", None}:
6 ✔
703
                    abs_path = join(self.get_build_dir(arch_name), lib)
6 ✔
704
            else:
UNCOV
705
                abs_path = join(self.ctx.get_libs_dir(arch_name), lib)
×
706
            recipe_libs.add(abs_path)
6 ✔
707
        return recipe_libs
6 ✔
708

709
    @classmethod
6 ✔
710
    def recipe_dirs(cls, ctx):
6 ✔
711
        recipe_dirs = []
6 ✔
712
        if ctx.local_recipes is not None:
6 ✔
713
            recipe_dirs.append(realpath(ctx.local_recipes))
6 ✔
714
        if ctx.storage_dir:
6 ✔
715
            recipe_dirs.append(join(ctx.storage_dir, 'recipes'))
6 ✔
716
        recipe_dirs.append(join(ctx.root_dir, "recipes"))
6 ✔
717
        return recipe_dirs
6 ✔
718

719
    @classmethod
6 ✔
720
    def list_recipes(cls, ctx):
6 ✔
721
        forbidden_dirs = ('__pycache__', )
6 ✔
722
        for recipes_dir in cls.recipe_dirs(ctx):
6 ✔
723
            if recipes_dir and exists(recipes_dir):
6 ✔
724
                for name in listdir(recipes_dir):
6 ✔
725
                    if name in forbidden_dirs:
6 ✔
726
                        continue
6 ✔
727
                    fn = join(recipes_dir, name)
6 ✔
728
                    if isdir(fn):
6 ✔
729
                        yield name
6 ✔
730

731
    @classmethod
6 ✔
732
    def get_recipe(cls, name, ctx):
6 ✔
733
        '''Returns the Recipe with the given name, if it exists.'''
734
        name = name.lower()
6 ✔
735
        if not hasattr(cls, "recipes"):
6 ✔
736
            cls.recipes = {}
6 ✔
737
        if name in cls.recipes:
6 ✔
738
            return cls.recipes[name]
6 ✔
739

740
        recipe_file = None
6 ✔
741
        for recipes_dir in cls.recipe_dirs(ctx):
6 ✔
742
            if not exists(recipes_dir):
6 ✔
743
                continue
6 ✔
744
            # Find matching folder (may differ in case):
745
            for subfolder in listdir(recipes_dir):
6 ✔
746
                if subfolder.lower() == name:
6 ✔
747
                    recipe_file = join(recipes_dir, subfolder, '__init__.py')
6 ✔
748
                    if exists(recipe_file):
6 !
749
                        name = subfolder  # adapt to actual spelling
6 ✔
750
                        break
6 ✔
UNCOV
751
                    recipe_file = None
×
752
            if recipe_file is not None:
6 ✔
753
                break
6 ✔
754

755
        else:
756
            raise ValueError('Recipe does not exist: {}'.format(name))
6 ✔
757

758
        mod = import_recipe('pythonforandroid.recipes.{}'.format(name), recipe_file)
6 ✔
759
        if len(logger.handlers) > 1:
6 !
UNCOV
760
            logger.removeHandler(logger.handlers[1])
×
761
        recipe = mod.recipe
6 ✔
762
        recipe.ctx = ctx
6 ✔
763
        cls.recipes[name.lower()] = recipe
6 ✔
764
        return recipe
6 ✔
765

766

767
class IncludedFilesBehaviour(object):
6 ✔
768
    '''Recipe mixin class that will automatically unpack files included in
769
    the recipe directory.'''
770
    src_filename = None
6 ✔
771

772
    def prepare_build_dir(self, arch):
6 ✔
UNCOV
773
        if self.src_filename is None:
×
UNCOV
774
            raise BuildInterruptingException(
×
775
                'IncludedFilesBehaviour failed: no src_filename specified')
UNCOV
776
        rmdir(self.get_build_dir(arch))
×
UNCOV
777
        shprint(sh.cp, '-a', join(self.get_recipe_dir(), self.src_filename),
×
778
                self.get_build_dir(arch))
779

780

781
class BootstrapNDKRecipe(Recipe):
6 ✔
782
    '''A recipe class for recipes built in an Android project jni dir with
783
    an Android.mk. These are not cached separately, but built in the
784
    bootstrap's own building directory.
785

786
    To build an NDK project which is not part of the bootstrap, see
787
    :class:`~pythonforandroid.recipe.NDKRecipe`.
788

789
    To link with python, call the method :meth:`get_recipe_env`
790
    with the kwarg *with_python=True*.
791
    '''
792

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

795
    def get_build_container_dir(self, arch):
6 ✔
UNCOV
796
        return self.get_jni_dir()
×
797

798
    def get_build_dir(self, arch):
6 ✔
799
        if self.dir_name is None:
×
800
            raise ValueError('{} recipe doesn\'t define a dir_name, but '
×
801
                             'this is necessary'.format(self.name))
802
        return join(self.get_build_container_dir(arch), self.dir_name)
×
803

804
    def get_jni_dir(self):
6 ✔
805
        return join(self.ctx.bootstrap.build_dir, 'jni')
6 ✔
806

807
    def get_recipe_env(self, arch=None, with_flags_in_cc=True, with_python=False):
6 ✔
UNCOV
808
        env = super().get_recipe_env(arch, with_flags_in_cc)
×
UNCOV
809
        if not with_python:
×
UNCOV
810
            return env
×
811

UNCOV
812
        env['PYTHON_INCLUDE_ROOT'] = self.ctx.python_recipe.include_root(arch.arch)
×
UNCOV
813
        env['PYTHON_LINK_ROOT'] = self.ctx.python_recipe.link_root(arch.arch)
×
UNCOV
814
        env['EXTRA_LDLIBS'] = ' -lpython{}'.format(
×
815
            self.ctx.python_recipe.link_version)
UNCOV
816
        return env
×
817

818

819
class NDKRecipe(Recipe):
6 ✔
820
    '''A recipe class for any NDK project not included in the bootstrap.'''
821

822
    generated_libraries = []
6 ✔
823

824
    def __init__(self, *args, **kwargs):
6 ✔
825
        super().__init__(*args, **kwargs)
6 ✔
826
        self.generated_libraries = list(self.generated_libraries)
6 ✔
827

828
    def should_build(self, arch):
6 ✔
UNCOV
829
        lib_dir = self.get_lib_dir(arch)
×
830

UNCOV
831
        for lib in self.generated_libraries:
×
832
            if not exists(join(lib_dir, lib)):
×
833
                return True
×
834

UNCOV
835
        return False
×
836

837
    def get_lib_dir(self, arch):
6 ✔
UNCOV
838
        return join(self.get_build_dir(arch.arch), 'obj', 'local', arch.arch)
×
839

840
    def get_jni_dir(self, arch):
6 ✔
UNCOV
841
        return join(self.get_build_dir(arch.arch), 'jni')
×
842

843
    def build_arch(self, arch, *extra_args):
6 ✔
UNCOV
844
        super().build_arch(arch)
×
845

UNCOV
846
        env = self.get_recipe_env(arch)
×
UNCOV
847
        with current_directory(self.get_build_dir(arch.arch)):
×
UNCOV
848
            shprint(
×
849
                sh.Command(join(self.ctx.ndk_dir, "ndk-build")),
850
                'V=1',
851
                "-j",
852
                str(cpu_count()),
853
                'NDK_DEBUG=' + ("1" if self.ctx.build_as_debuggable else "0"),
854
                'APP_PLATFORM=android-' + str(self.ctx.ndk_api),
855
                'APP_ABI=' + arch.arch,
856
                *extra_args, _env=env
857
            )
858

859

860
class PythonRecipe(Recipe):
6 ✔
861
    site_packages_name = None
6 ✔
862
    '''The name of the module's folder when installed in the Python
6 ✔
863
    site-packages (e.g. for pyjnius it is 'jnius')'''
864

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

873
    install_in_hostpython = False
6 ✔
874
    '''If True, additionally installs the module in the hostpython build
6 ✔
875
    dir. This will make it available to other recipes if
876
    call_hostpython_via_targetpython is False.
877
    '''
878

879
    install_in_targetpython = True
6 ✔
880
    '''If True, installs the module in the targetpython installation dir.
6 ✔
881
    This is almost always what you want to do.'''
882

883
    setup_extra_args = []
6 ✔
884
    '''List of extra arguments to pass to setup.py'''
6 ✔
885

886
    depends = ['python3']
6 ✔
887
    '''
6 ✔
888
    .. note:: it's important to keep this depends as a class attribute outside
889
              `__init__` because sometimes we only initialize the class, so the
890
              `__init__` call won't be called and the deps would be missing
891
              (which breaks the dependency graph computation)
892

893
    .. warning:: don't forget to call `super().__init__()` in any recipe's
894
                 `__init__`, or otherwise it may not be ensured that it depends
895
                 on python2 or python3 which can break the dependency graph
896
    '''
897

898
    hostpython_prerequisites = ['setuptools']
6 ✔
899
    '''List of hostpython packages required to build a recipe'''
6 ✔
900

901
    _host_recipe = None
6 ✔
902

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

917
    def prebuild_arch(self, arch):
6 ✔
918
        self._host_recipe = Recipe.get_recipe("hostpython3", self.ctx)
6 ✔
919
        return super().prebuild_arch(arch)
6 ✔
920

921
    def clean_build(self, arch=None):
6 ✔
922
        super().clean_build(arch=arch)
×
UNCOV
923
        name = self.folder_name
×
924
        python_install_dirs = glob.glob(join(self.ctx.python_installs_dir, '*'))
×
UNCOV
925
        for python_install in python_install_dirs:
×
UNCOV
926
            site_packages_dir = glob.glob(join(python_install, 'lib', 'python*',
×
927
                                               'site-packages'))
928
            if site_packages_dir:
×
929
                build_dir = join(site_packages_dir[0], name)
×
930
                if exists(build_dir):
×
UNCOV
931
                    info('Deleted {}'.format(build_dir))
×
UNCOV
932
                    rmdir(build_dir)
×
933

934
    @property
6 ✔
935
    def real_hostpython_location(self):
6 ✔
936
        host_name = 'host{}'.format(self.ctx.python_recipe.name)
×
937
        if host_name == 'hostpython3':
×
938
            return self._host_recipe.python_exe
×
939
        else:
UNCOV
940
            return 'python{}'.format(self.ctx.python_recipe.version)
×
941

942
    @property
6 ✔
943
    def hostpython_location(self):
6 ✔
944
        if not self.call_hostpython_via_targetpython:
×
945
            return self.real_hostpython_location
×
946
        return self.ctx.hostpython
×
947

948
    @property
6 ✔
949
    def folder_name(self):
6 ✔
950
        '''The name of the build folders containing this recipe.'''
UNCOV
951
        name = self.site_packages_name
×
952
        if name is None:
×
953
            name = self.name
×
954
        return name
×
955

956
    def patch_shebang(self, _file, original_bin):
6 ✔
957
        _file_des = open(_file, "r")
×
958

UNCOV
959
        try:
×
UNCOV
960
            data = _file_des.readlines()
×
961
        except UnicodeDecodeError:
×
962
            return
×
963

UNCOV
964
        if "#!" in (line := data[0]):
×
965
            if line.split("#!")[-1].strip() == original_bin:
×
966
                return
×
967

968
            info(f"Fixing shebang for '{_file}'")
×
UNCOV
969
            data.pop(0)
×
UNCOV
970
            data.insert(0, "#!" + original_bin + "\n")
×
UNCOV
971
            _file_des.close()
×
UNCOV
972
            _file_des = open(_file, "w")
×
UNCOV
973
            _file_des.write("".join(data))
×
UNCOV
974
            _file_des.close()
×
975

976
    def patch_shebangs(self, path, original_bin):
6 ✔
UNCOV
977
        if not isdir(path):
×
UNCOV
978
            warning(f"Shebang patch skipped: '{path}' does not exist.")
×
UNCOV
979
            return
×
980
        # set correct shebang
UNCOV
981
        for file in listdir(path):
×
UNCOV
982
            _file = join(path, file)
×
UNCOV
983
            if isfile(_file):
×
UNCOV
984
                self.patch_shebang(_file, original_bin)
×
985

986
    def get_recipe_env(self, arch=None, with_flags_in_cc=True):
6 ✔
987
        if self._host_recipe is None:
6 !
988
            self._host_recipe = Recipe.get_recipe("hostpython3", self.ctx)
6 ✔
989

990
        env = super().get_recipe_env(arch, with_flags_in_cc)
6 ✔
991
        # Set the LANG, this isn't usually important but is a better default
992
        # as it occasionally matters how Python e.g. reads files
993
        env['LANG'] = "en_GB.UTF-8"
6 ✔
994
        env["PATH"] = self._host_recipe.local_bin + ":" + self._host_recipe.site_bin + ":" + env["PATH"]
6 ✔
995
        host_env = self.get_hostrecipe_env(arch)
6 ✔
996
        env['PYTHONPATH'] = host_env["PYTHONPATH"]
6 ✔
997

998
        if not self.call_hostpython_via_targetpython:
6 !
999
            env['CFLAGS'] += ' -I{}'.format(
6 ✔
1000
                self.ctx.python_recipe.include_root(arch.arch)
1001
            )
1002
            env['LDFLAGS'] += ' -L{} -lpython{}'.format(
6 ✔
1003
                self.ctx.python_recipe.link_root(arch.arch),
1004
                self.ctx.python_recipe.link_version,
1005
            )
1006

1007
        return env
6 ✔
1008

1009
    def should_build(self, arch):
6 ✔
UNCOV
1010
        name = self.folder_name
×
UNCOV
1011
        if self.ctx.has_package(name, arch):
×
1012
            info('Python package already exists in site-packages')
×
1013
            return False
×
1014
        info('{} apparently isn\'t already in site-packages'.format(name))
×
1015
        return True
×
1016

1017
    def build_arch(self, arch):
6 ✔
1018
        '''Install the Python module by calling setup.py install with
1019
        the target Python dir.'''
1020
        self.install_hostpython_prerequisites()
×
1021
        super().build_arch(arch)
×
UNCOV
1022
        self.install_python_package(arch)
×
1023

1024
    def install_python_package(self, arch, name=None, env=None, is_dir=True):
6 ✔
1025
        '''Automate the installation of a Python package (or a cython
1026
        package where the cython components are pre-built).'''
1027
        # arch = self.filtered_archs[0]  # old kivy-ios way
UNCOV
1028
        if name is None:
×
UNCOV
1029
            name = self.name
×
UNCOV
1030
        if env is None:
×
UNCOV
1031
            env = self.get_recipe_env(arch)
×
1032

UNCOV
1033
        info('Installing {} into site-packages'.format(self.name))
×
1034

1035
        hpenv = env.copy()
×
UNCOV
1036
        with current_directory(self.get_build_dir(arch.arch)):
×
UNCOV
1037
            shprint(self._host_recipe.pip, 'install', '.',
×
1038
                    '--compile', '--target',
1039
                    self.ctx.get_python_install_dir(arch.arch),
1040
                    _env=hpenv, *self.setup_extra_args
1041
            )
1042

1043
    def get_hostrecipe_env(self, arch=None):
6 ✔
1044
        env = environ.copy()
6 ✔
1045
        env['PYTHONPATH'] = ''
6 ✔
1046
        env['HOME'] = '/tmp'
6 ✔
1047
        return env
6 ✔
1048

1049
    @property
6 ✔
1050
    def hostpython_site_dir(self):
6 ✔
1051
        return join(dirname(self.real_hostpython_location), 'Lib', 'site-packages')
×
1052

1053
    def install_hostpython_package(self, arch):
6 ✔
1054
        env = self.get_hostrecipe_env(arch)
×
UNCOV
1055
        shprint(self._host_recipe.pip, 'install', '.',
×
1056
                '--compile',
1057
                '--root={}'.format(self._host_recipe.site_root),
1058
                _env=env, *self.setup_extra_args)
1059

1060
    @property
6 ✔
1061
    def python_major_minor_version(self):
6 ✔
1062
        parsed_version = packaging.version.parse(self.ctx.python_recipe.version)
×
1063
        return f"{parsed_version.major}.{parsed_version.minor}"
×
1064

1065
    def install_hostpython_prerequisites(self, packages=None, force_upgrade=True):
6 ✔
UNCOV
1066
        if not packages:
×
1067
            packages = self.hostpython_prerequisites
×
1068

1069
        if len(packages) == 0:
×
1070
            return
×
1071

UNCOV
1072
        pip_options = [
×
1073
            "install",
1074
            *packages,
1075
            "-q",
1076
        ]
UNCOV
1077
        if force_upgrade:
×
UNCOV
1078
            pip_options.append("--upgrade")
×
UNCOV
1079
        pip_env = self.get_hostrecipe_env()
×
UNCOV
1080
        shprint(self._host_recipe.pip, *pip_options, _env=pip_env)
×
1081

1082
    def restore_hostpython_prerequisites(self, packages):
6 ✔
1083
        _packages = []
×
1084
        for package in packages:
×
1085
            original_version = Recipe.get_recipe(package, self.ctx).version
×
1086
            _packages.append(package + "==" + original_version)
×
UNCOV
1087
        self.install_hostpython_prerequisites(packages=_packages)
×
1088

1089

1090
class CompiledComponentsPythonRecipe(PythonRecipe):
6 ✔
1091
    pre_build_ext = False
6 ✔
1092

1093
    build_cmd = 'build_ext'
6 ✔
1094

1095
    def build_arch(self, arch):
6 ✔
1096
        '''Build any cython components, then install the Python module by
1097
        calling pip install with the target Python dir.
1098
        '''
1099
        Recipe.build_arch(self, arch)
×
UNCOV
1100
        self.install_hostpython_prerequisites()
×
UNCOV
1101
        self.build_compiled_components(arch)
×
UNCOV
1102
        self.install_python_package(arch)
×
1103

1104
    def build_compiled_components(self, arch):
6 ✔
1105
        info('Building compiled components in {}'.format(self.name))
×
1106

UNCOV
1107
        env = self.get_recipe_env(arch)
×
1108
        hostpython = sh.Command(self.hostpython_location)
×
UNCOV
1109
        with current_directory(self.get_build_dir(arch.arch)):
×
1110
            if self.install_in_hostpython:
×
1111
                shprint(hostpython, 'setup.py', 'clean', '--all', _env=env)
×
1112
            shprint(hostpython, 'setup.py', self.build_cmd, '-v',
×
1113
                    _env=env, *self.setup_extra_args)
UNCOV
1114
            build_dir = glob.glob('build/lib.*')[0]
×
UNCOV
1115
            shprint(sh.find, build_dir, '-name', '"*.o"', '-exec',
×
1116
                    env['STRIP'], '{}', ';', _env=env)
1117

1118
    def install_hostpython_package(self, arch):
6 ✔
UNCOV
1119
        env = self.get_hostrecipe_env(arch)
×
UNCOV
1120
        self.rebuild_compiled_components(arch, env)
×
UNCOV
1121
        super().install_hostpython_package(arch)
×
1122

1123
    def rebuild_compiled_components(self, arch, env):
6 ✔
UNCOV
1124
        info('Rebuilding compiled components in {}'.format(self.name))
×
1125

UNCOV
1126
        hostpython = sh.Command(self.real_hostpython_location)
×
UNCOV
1127
        shprint(hostpython, 'setup.py', 'clean', '--all', _env=env)
×
UNCOV
1128
        shprint(hostpython, 'setup.py', self.build_cmd, '-v', _env=env,
×
1129
                *self.setup_extra_args)
1130

1131

1132
class CppCompiledComponentsPythonRecipe(CompiledComponentsPythonRecipe):
6 ✔
1133
    """ Extensions that require the cxx-stl """
1134
    call_hostpython_via_targetpython = False
6 ✔
1135
    need_stl_shared = True
6 ✔
1136

1137

1138
class CythonRecipe(PythonRecipe):
6 ✔
1139
    pre_build_ext = False
6 ✔
1140
    cythonize = True
6 ✔
1141
    cython_args = []
6 ✔
1142
    call_hostpython_via_targetpython = False
6 ✔
1143

1144
    def __init__(self, *args, **kwargs):
6 ✔
1145
        super().__init__(*args, **kwargs)
6 ✔
1146
        self.cython_args = list(self.cython_args)
6 ✔
1147

1148
    def build_arch(self, arch):
6 ✔
1149
        '''Build any cython components, then install the Python module by
1150
        calling pip install with the target Python dir.
1151
        '''
UNCOV
1152
        self.install_hostpython_prerequisites()
×
1153
        Recipe.build_arch(self, arch)
×
1154
        self.build_cython_components(arch)
×
1155
        self.install_python_package(arch)
×
1156

1157
    def build_cython_components(self, arch):
6 ✔
1158
        info('Cythonizing anything necessary in {}'.format(self.name))
6 ✔
1159

1160
        env = self.get_recipe_env(arch)
6 ✔
1161

1162
        with current_directory(self.get_build_dir(arch.arch)):
6 ✔
1163
            hostpython = sh.Command(self.ctx.hostpython)
6 ✔
1164
            shprint(hostpython, '-c', 'import sys; print(sys.path)', _env=env)
6 ✔
1165
            debug('cwd is {}'.format(realpath(curdir)))
6 ✔
1166
            info('Trying first build of {} to get cython files: this is '
6 ✔
1167
                 'expected to fail'.format(self.name))
1168

1169
            manually_cythonise = False
6 ✔
1170
            try:
6 ✔
1171
                shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env,
6 ✔
1172
                        *self.setup_extra_args)
UNCOV
1173
            except sh.ErrorReturnCode_1:
×
UNCOV
1174
                print()
×
UNCOV
1175
                info('{} first build failed (as expected)'.format(self.name))
×
UNCOV
1176
                manually_cythonise = True
×
1177

1178
            if manually_cythonise:
6 !
UNCOV
1179
                self.cythonize_build(env=env)
×
UNCOV
1180
                shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env,
×
1181
                        _tail=20, _critical=True, *self.setup_extra_args)
1182
            else:
1183
                info('First build appeared to complete correctly, skipping manual'
6 ✔
1184
                     'cythonising.')
1185

1186
            if not self.ctx.with_debug_symbols:
6 ✔
1187
                self.strip_object_files(arch, env)
6 ✔
1188

1189
    def strip_object_files(self, arch, env, build_dir=None):
6 ✔
1190
        if build_dir is None:
6 ✔
1191
            build_dir = self.get_build_dir(arch.arch)
6 ✔
1192
        with current_directory(build_dir):
6 ✔
1193
            info('Stripping object files')
6 ✔
1194
            shprint(sh.find, '.', '-iname', '*.so', '-print', _env=env)
6 ✔
1195
            shprint(sh.find, '.', '-iname', '*.so', '-exec',
6 ✔
1196
                    env['STRIP'].split(' ')[0], '--strip-unneeded',
1197
                    # '/usr/bin/strip', '--strip-unneeded',
1198
                    '{}', ';', _env=env)
1199

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

1219
    def cythonize_build(self, env, build_dir="."):
6 ✔
1220
        if not self.cythonize:
×
UNCOV
1221
            info('Running cython cancelled per recipe setting')
×
UNCOV
1222
            return
×
UNCOV
1223
        info('Running cython where appropriate')
×
1224
        for root, dirnames, filenames in walk("."):
×
UNCOV
1225
            for filename in fnmatch.filter(filenames, "*.pyx"):
×
1226
                self.cythonize_file(env, build_dir, join(root, filename))
×
1227

1228
    def get_recipe_env(self, arch, with_flags_in_cc=True):
6 ✔
1229
        env = super().get_recipe_env(arch, with_flags_in_cc)
×
UNCOV
1230
        env['LDFLAGS'] = env['LDFLAGS'] + ' -L{} '.format(
×
1231
            self.ctx.get_libs_dir(arch.arch) +
1232
            ' -L{} '.format(self.ctx.libs_dir) +
1233
            ' -L{}'.format(join(self.ctx.bootstrap.build_dir, 'obj', 'local',
1234
                                arch.arch)))
1235

UNCOV
1236
        env['LDSHARED'] = env['CC'] + ' -shared'
×
1237
        # shprint(sh.whereis, env['LDSHARED'], _env=env)
UNCOV
1238
        env['LIBLINK'] = 'NOTNONE'
×
UNCOV
1239
        if self.ctx.copy_libs:
×
UNCOV
1240
            env['COPYLIBS'] = '1'
×
1241

1242
        # Every recipe uses its own liblink path, object files are
1243
        # collected and biglinked later
UNCOV
1244
        liblink_path = join(self.get_build_container_dir(arch.arch),
×
1245
                            'objects_{}'.format(self.name))
UNCOV
1246
        env['LIBLINK_PATH'] = liblink_path
×
UNCOV
1247
        ensure_dir(liblink_path)
×
1248

UNCOV
1249
        return env
×
1250

1251

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

1271

1272
class PyProjectRecipe(PythonRecipe):
6 ✔
1273
    """Recipe for projects which contain `pyproject.toml`"""
1274

1275
    # Extra args to pass to `python -m build ...`
1276
    extra_build_args = []
6 ✔
1277
    call_hostpython_via_targetpython = False
6 ✔
1278

1279
    def __init__(self, *args, **kwargs):
6 ✔
1280
        super().__init__(*args, **kwargs)
6 ✔
1281
        self.extra_build_args = list(self.extra_build_args)
6 ✔
1282

1283
    def get_pip_name(self):
6 ✔
UNCOV
1284
        name_str = self.name
×
1285
        if self.name not in self.ctx.use_prebuilt_version_for and self.version is not None:
×
1286
            # Like: v2.3.0 -> 2.3.0
UNCOV
1287
            cleaned_version = self.version.lstrip("v")
×
1288
            name_str += f"=={cleaned_version}"
×
UNCOV
1289
        return name_str
×
1290

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

1308
        # add extra index urls
UNCOV
1309
        for index in self.ctx.extra_index_urls:
×
1310
            opts.extend(["--extra-index-url", index])
×
1311

UNCOV
1312
        return opts
×
1313

1314
    def lookup_prebuilt(self, arch):
6 ✔
UNCOV
1315
        pip_options = self.get_pip_install_args(arch)
×
1316
        # do not install
UNCOV
1317
        pip_options.extend(["--dry-run", "-q"])
×
UNCOV
1318
        pip_env = self.get_hostrecipe_env()
×
UNCOV
1319
        try:
×
UNCOV
1320
            shprint(self._host_recipe.pip, *pip_options, _env=pip_env, silent=True)
×
UNCOV
1321
        except Exception:
×
UNCOV
1322
            return False
×
UNCOV
1323
        return True
×
1324

1325
    def check_prebuilt(self, arch, msg=""):
6 ✔
UNCOV
1326
        if self.ctx.skip_prebuilt:
×
UNCOV
1327
            return False
×
1328

UNCOV
1329
        if self.lookup_prebuilt(arch):
×
UNCOV
1330
            if msg != "":
×
UNCOV
1331
                info(f"Prebuilt pip wheel found, {msg}")
×
UNCOV
1332
            return True
×
1333

UNCOV
1334
        return False
×
1335

1336
    def get_recipe_env(self, arch, **kwargs):
6 ✔
1337
        env = super().get_recipe_env(arch, **kwargs)
6 ✔
1338
        build_dir = self.get_build_dir(arch)
6 ✔
1339
        ensure_dir(build_dir)
6 ✔
1340
        build_opts = join(build_dir, "build-opts.cfg")
6 ✔
1341

1342
        with open(build_opts, "w") as file:
6 ✔
1343
            file.write("[bdist_wheel]\nplat_name={}".format(
6 ✔
1344
                self.get_wheel_platform_tag(arch.arch)
1345
            ))
1346
            file.close()
6 ✔
1347

1348
        env["DIST_EXTRA_CONFIG"] = build_opts
6 ✔
1349
        python_recipe = Recipe.get_recipe("python3", self.ctx)
6 ✔
1350
        env["INCLUDEPY"] = python_recipe.include_root(arch.arch)
6 ✔
1351
        return env
6 ✔
1352

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

1367
    def get_wheel_platform_tag(self, arch):
6 ✔
1368
        return PyProjectRecipe.get_wheel_platform_tags(arch, self.ctx)[0]
6 ✔
1369

1370
    def install_prebuilt_wheel(self, arch):
6 ✔
UNCOV
1371
        info("Installing prebuilt wheel")
×
UNCOV
1372
        destination = self.ctx.get_python_install_dir(arch.arch)
×
UNCOV
1373
        pip_options = self.get_pip_install_args(arch)
×
UNCOV
1374
        pip_options.extend(["--target", destination])
×
UNCOV
1375
        pip_options.append("--upgrade")
×
UNCOV
1376
        pip_env = self.get_hostrecipe_env()
×
UNCOV
1377
        try:
×
UNCOV
1378
            shprint(self._host_recipe.pip, *pip_options, _env=pip_env)
×
UNCOV
1379
        except Exception:
×
UNCOV
1380
            return False
×
UNCOV
1381
        return True
×
1382

1383
    def install_wheel(self, arch, built_wheels):
6 ✔
1384
        with patch_wheel_setuptools_logging():
6 ✔
1385
            from wheel.wheelfile import WheelFile
6 ✔
1386
        # Fix wheel platform tag
1387
        selected_wheel = retag_wheel(
6 ✔
1388
            built_wheels[0], self.get_wheel_platform_tag(arch.arch)
1389
        )
1390
        wheel_tag = basename(selected_wheel)
6 ✔
1391
        _dev_wheel_dir = environ.get("P4A_WHEEL_DIR", False)
6 ✔
1392
        if _dev_wheel_dir:
6 !
1393
            ensure_dir(_dev_wheel_dir)
6 ✔
1394
            shprint(sh.cp, selected_wheel, _dev_wheel_dir)
6 ✔
1395

1396
        if exists(self.ctx.save_wheel_dir):
6 !
1397
            shprint(sh.cp, selected_wheel, self.ctx.save_wheel_dir)
6 ✔
1398

1399
        info(f"Installing built wheel: {wheel_tag}")
6 ✔
1400
        destination = self.ctx.get_python_install_dir(arch.arch)
6 ✔
1401
        with WheelFile(selected_wheel) as wf:
6 ✔
1402
            for zinfo in wf.filelist:
6 ✔
1403
                wf.extract(zinfo, destination)
6 ✔
1404

1405
    def build_arch(self, arch):
6 ✔
UNCOV
1406
        if self.check_prebuilt(arch, "skipping build_arch"):
×
UNCOV
1407
            result = self.install_prebuilt_wheel(arch)
×
UNCOV
1408
            if result:
×
1409
                return
×
1410
            warning("Failed to install prebuilt wheel, falling back to build_arch")
×
1411

UNCOV
1412
        build_dir = self.get_build_dir(arch.arch)
×
UNCOV
1413
        if not (isfile(join(build_dir, "pyproject.toml")) or isfile(join(build_dir, "setup.py"))):
×
1414
            warning("Skipping build because it does not appear to be a Python project.")
×
1415
            return
×
UNCOV
1416
        self.install_hostpython_prerequisites(
×
1417
            packages=["build[virtualenv]", "pip", "setuptools", "patchelf"] + self.hostpython_prerequisites
1418
        )
1419

UNCOV
1420
        env = self.get_recipe_env(arch, with_flags_in_cc=True)
×
1421
        # make build dir separately
UNCOV
1422
        sub_build_dir = join(build_dir, "p4a_android_build")
×
UNCOV
1423
        ensure_dir(sub_build_dir)
×
1424

UNCOV
1425
        build_args = [
×
1426
            "-m",
1427
            "build",
1428
            "--wheel",
1429
            "--config-setting",
1430
            "builddir={}".format(sub_build_dir),
1431
        ] + self.extra_build_args
1432

UNCOV
1433
        built_wheels = []
×
UNCOV
1434
        with current_directory(build_dir):
×
1435
            shprint(
×
1436
                sh.Command(self.real_hostpython_location), *build_args, _env=env
1437
            )
1438
            built_wheels = [realpath(whl) for whl in glob.glob("dist/*.whl")]
×
1439
        self.install_wheel(arch, built_wheels)
×
1440

1441

1442
class MesonRecipe(PyProjectRecipe):
6 ✔
1443
    '''Recipe for projects which uses meson as build system'''
1444

1445
    meson_version = "1.4.0"
6 ✔
1446
    pybind_version = "3.3.0"
6 ✔
1447

1448
    skip_python = False
6 ✔
1449
    '''If true, skips all Python build and installation steps.
6 ✔
1450
    Useful for Meson projects written purely in C/C++ without Python bindings.'''
1451

1452
    def sanitize_flags(self, *flag_strings):
6 ✔
1453
        return " ".join(flag_strings).strip().split(" ")
×
1454

1455
    def get_wrapper_dir(self, arch):
6 ✔
UNCOV
1456
        return join(self.get_build_dir(arch.arch), "p4a_wrappers")
×
1457

1458
    def write_wrapper(self, arch, name, content):
6 ✔
UNCOV
1459
        wrapper_dir = self.get_wrapper_dir(arch)
×
UNCOV
1460
        ensure_dir(wrapper_dir)
×
UNCOV
1461
        wrapper_path = join(wrapper_dir, name)
×
UNCOV
1462
        with open(wrapper_path, "w") as f:
×
UNCOV
1463
            f.write(content)
×
UNCOV
1464
        chmod(wrapper_path, 0o755)
×
UNCOV
1465
        return wrapper_path
×
1466

1467
    def get_python_wrapper(self, arch):
6 ✔
1468
        """
1469
        Meson Python introspection runs on the host interpreter, but the
1470
        target Python (Android) cannot be executed on the build machine.
1471

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

1485
        # Real values pulled from android
1486
        # PYTHON_MAJOR_VERSION -> 3
1487
        # PYTHON_MINOR_VERSION -> 14
1488
        # PLATFORM_TAG eg -> 'android-24-arm64_v8a'
1489
        # PYTHON_SUFFIX eg -> '.cpython-314-aarch64-linux-android.so'
1490

1491
        _p_version = Version(python_recipe.version)
×
1492
        file_data = f"#!{self.real_hostpython_location}"
×
1493
        file_data += f"\nTARGET_PYTHON_PREFIX='{target_prefix}'"
×
1494
        file_data += f"\nPYTHON_MAJOR_VERSION='{_p_version.major}'"
×
1495
        file_data += f"\nPYTHON_MINOR_VERSION='{_p_version.minor}'"
×
1496
        file_data += f"\nPLATFORM_TAG='{self.get_wheel_platform_tags(arch.arch, self.ctx)[0]}'"
×
UNCOV
1497
        file_data += f"\nPYTHON_SUFFIX='.cpython-{_p_version.major}{_p_version.minor}-{_arch}-linux-android.so'"
×
1498

1499
        with open(python_file, "r") as f:
×
1500
            file_data += "\n" + f.read()
×
1501

1502
        return self.write_wrapper(arch, "python", file_data)
×
1503

1504
    def get_config_wrappers(self, arch, w_type: str):
6 ✔
UNCOV
1505
        wrapper_name = ""
×
1506
        version = ""
×
UNCOV
1507
        include_path = ""
×
1508

UNCOV
1509
        if w_type == "pybind11":
×
UNCOV
1510
            wrapper_name = "pybind11-config"
×
UNCOV
1511
            include_path = join(self._host_recipe.site_dir, "pybind11/include")
×
1512

UNCOV
1513
            version = None
×
1514
            try:
×
UNCOV
1515
                command = [self._host_recipe.real_hostpython_location, "-c", "import pybind11; print(pybind11.__version__)"]
×
UNCOV
1516
                version = subprocess.check_output(command).decode('utf-8').strip()
×
1517
            except Exception:
×
1518
                warning("Unable to get pybind11 version")
×
UNCOV
1519
            if version is None:
×
UNCOV
1520
                version = self.pybind_version
×
1521

UNCOV
1522
        elif w_type == "numpy":
×
UNCOV
1523
            wrapper_name = "numpy-config"
×
UNCOV
1524
            recipe = Recipe.get_recipe("numpy", self.ctx)
×
UNCOV
1525
            include_path = recipe.get_include(arch)
×
UNCOV
1526
            version = recipe.version
×
1527
        else:
UNCOV
1528
            raise ValueError(f"Unknown wrapper type: {w_type}")
×
1529

UNCOV
1530
        content = (
×
1531
            f"#!/bin/sh\n"
1532
            f"if [ \"$1\" = \"--version\" ]; then\n"
1533
            f"    echo '{version}'\n"
1534
            f"else\n"
1535
            f"    echo '-I{include_path}'\n"
1536
            f"fi\n"
1537
        )
UNCOV
1538
        return self.write_wrapper(arch, wrapper_name, content)
×
1539

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

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

1601
    def ensure_args(self, *args):
6 ✔
1602
        for arg in args:
6 ✔
1603
            if arg not in self.extra_build_args:
6 !
1604
                self.extra_build_args.append(arg)
6 ✔
1605

1606
    def get_recipe_env_command(self, command, env):
6 ✔
1607
        command_path = shutil.which(command, path=env["PATH"])
6 ✔
1608
        if command_path is None:
6 !
1609
            raise sh.CommandNotFound(command)
×
1610
        return sh.Command(command_path)
6 ✔
1611

1612
    def get_meson_command(self, env):
6 ✔
1613
        return self.get_recipe_env_command("meson", env)
6 ✔
1614

1615
    def get_ninja_command(self, env):
6 ✔
UNCOV
1616
        return self.get_recipe_env_command("ninja", env)
×
1617

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

UNCOV
1635
        if not self.skip_python:
×
UNCOV
1636
            super().build_arch(arch)
×
1637
        else:
1638
            self.install_hostpython_prerequisites(
×
1639
                packages=["build[virtualenv]", "pip", "setuptools", "patchelf"] + self.hostpython_prerequisites
1640
            )
1641

1642

1643
class RustCompiledComponentsRecipe(PyProjectRecipe):
6 ✔
1644
    # Rust toolchain codes
1645
    # https://doc.rust-lang.org/nightly/rustc/platform-support.html
1646
    RUST_ARCH_CODES = {
6 ✔
1647
        "arm64-v8a": "aarch64-linux-android",
1648
        "armeabi-v7a": "armv7-linux-androideabi",
1649
        "x86_64": "x86_64-linux-android",
1650
        "x86": "i686-linux-android",
1651
    }
1652

1653
    def get_recipe_env(self, arch, **kwargs):
6 ✔
UNCOV
1654
        env = super().get_recipe_env(arch, **kwargs)
×
1655

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

1675
        # maturin (used by every Rust recipe here) refuses to build without the
1676
        # target Android API level: "Failed to determine Android API level."
UNCOV
1677
        env["ANDROID_API_LEVEL"] = str(self.ctx.ndk_api)
×
1678

1679
        env["RUSTFLAGS"] = "-Clink-args=-L{} -L{}".format(
×
1680
            self.ctx.get_libs_dir(arch.arch), join(realpython_dir, "android-build")
1681
        )
UNCOV
1682
        env["RUSTFLAGS"] += f" -Clink-arg=-lpython{self.ctx.python_recipe.link_version}"
×
1683

1684
        env["PYO3_CROSS_LIB_DIR"] = realpath(glob.glob(join(
×
1685
            realpython_dir, "android-build", "build",
1686
            "lib.*{}/".format(self.python_major_minor_version),
1687
        ))[0])
1688

UNCOV
1689
        info_main("Ensuring rust build toolchain")
×
UNCOV
1690
        shprint(sh.rustup, "target", "add", build_target)
×
1691

1692
        # Add host python to PATH
UNCOV
1693
        env["PATH"] = ("{hostpython_dir}:{old_path}").format(
×
1694
            hostpython_dir=Recipe.get_recipe(
1695
                "hostpython3", self.ctx
1696
            ).local_bin,
1697
            old_path=env["PATH"],
1698
        )
UNCOV
1699
        return env
×
1700

1701
    def check_host_deps(self):
6 ✔
UNCOV
1702
        if not hasattr(sh, "rustup"):
×
UNCOV
1703
            error(
×
1704
                "`rustup` was not found on host system."
1705
                "Please install it using :"
1706
                "\n`curl https://sh.rustup.rs -sSf | sh`\n"
1707
            )
UNCOV
1708
            exit(1)
×
1709

1710
    def build_arch(self, arch):
6 ✔
UNCOV
1711
        self.check_host_deps()
×
UNCOV
1712
        super().build_arch(arch)
×
1713

1714

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

1719
    def __init__(self, *args, **kwargs):
6 ✔
1720
        self._ctx = None
6 ✔
1721
        super().__init__(*args, **kwargs)
6 ✔
1722

1723
    def prebuild_arch(self, arch):
6 ✔
UNCOV
1724
        super().prebuild_arch(arch)
×
UNCOV
1725
        self.ctx.python_recipe = self
×
1726

1727
    def include_root(self, arch):
6 ✔
1728
        '''The root directory from which to include headers.'''
1729
        raise NotImplementedError('Not implemented in TargetPythonRecipe')
1730

1731
    def link_root(self):
6 ✔
1732
        raise NotImplementedError('Not implemented in TargetPythonRecipe')
1733

1734
    @property
6 ✔
1735
    def major_minor_version_string(self):
6 ✔
1736
        parsed_version = packaging.version.parse(self.version)
6 ✔
1737
        return f"{parsed_version.major}.{parsed_version.minor}"
6 ✔
1738

1739
    def create_python_bundle(self, dirn, arch):
6 ✔
1740
        """
1741
        Create a packaged python bundle in the target directory, by
1742
        copying all the modules and standard library to the right
1743
        place.
1744
        """
1745
        raise NotImplementedError('{} does not implement create_python_bundle'.format(self))
1746

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

1764

1765
def algsum(alg, filen):
6 ✔
1766
    '''Calculate the digest of a file.
1767
    '''
UNCOV
1768
    with open(filen, 'rb') as fileh:
×
UNCOV
1769
        digest = getattr(hashlib, alg)(fileh.read())
×
1770

UNCOV
1771
    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