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

kivy / python-for-android / 46363471995

30 Nov 2026 06:01AM UTC coverage: 62.914%. First build
46363471995

push

github

web-flow
Handle un-downloadable pinned dependencies in dependency resolution (#3418)

1925 of 3301 branches covered (58.32%)

Branch coverage included in aggregate %.

19 of 25 new or added lines in 2 files covered. (76.0%)

5580 of 8628 relevant lines covered (64.67%)

3.88 hits per line

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

48.98
/pythonforandroid/toolchain.py
1
#!/usr/bin/env python
2
"""
6 ✔
3
Tool for packaging Python apps for Android
4
==========================================
5

6
This module defines the entry point for command line and programmatic use.
7
"""
8

9
from appdirs import user_data_dir
6 ✔
10
import argparse
6 ✔
11
from functools import wraps
6 ✔
12
import glob
6 ✔
13
import logging
6 ✔
14
import os
6 ✔
15
from os import environ
6 ✔
16
from os.path import (join, dirname, realpath, exists, expanduser, basename)
6 ✔
17
import re
6 ✔
18
import shlex
6 ✔
19
import sys
6 ✔
20
from sys import platform
6 ✔
21

22
# This must be imported and run before other third-party or p4a
23
# packages.
24
from pythonforandroid.checkdependencies import check
6 ✔
25
check()
6 ✔
26

27
from packaging.version import Version
6 ✔
28
import sh
6 ✔
29

30
from pythonforandroid import __version__
6 ✔
31
from pythonforandroid.bootstrap import Bootstrap
6 ✔
32
from pythonforandroid.build import Context, build_recipes, project_has_setup_py
6 ✔
33
from pythonforandroid.distribution import Distribution, pretty_log_dists
6 ✔
34
from pythonforandroid.entrypoints import main
6 ✔
35
from pythonforandroid.graph import get_recipe_order_and_bootstrap
6 ✔
36
from pythonforandroid.logger import (logger, info, warning, setup_color,
6 ✔
37
                                     Out_Style, Out_Fore,
38
                                     info_notify, info_main, shprint)
39
from pythonforandroid.pythonpackage import get_dep_names_of_package
6 ✔
40
from pythonforandroid.recipe import Recipe
6 ✔
41
from pythonforandroid.recommendations import (
6 ✔
42
    RECOMMENDED_NDK_API, RECOMMENDED_TARGET_API, print_recommendations)
43
from pythonforandroid.util import (
6 ✔
44
    current_directory,
45
    BuildInterruptingException,
46
    load_source,
47
    rmdir,
48
    max_build_tool_version,
49
)
50

51
user_dir = dirname(realpath(os.path.curdir))
6 ✔
52
toolchain_dir = dirname(__file__)
6 ✔
53
sys.path.insert(0, join(toolchain_dir, "tools", "external"))
6 ✔
54

55

56
def add_boolean_option(parser, names, no_names=None,
6 ✔
57
                       default=True, dest=None, description=None):
58
    group = parser.add_argument_group(description=description)
6 ✔
59
    if not isinstance(names, (list, tuple)):
6 !
60
        names = [names]
×
61
    if dest is None:
6 !
62
        dest = names[0].strip("-").replace("-", "_")
6 ✔
63

64
    def add_dashes(x):
6 ✔
65
        return x if x.startswith("-") else "--"+x
6 ✔
66

67
    opts = [add_dashes(x) for x in names]
6 ✔
68
    group.add_argument(
6 ✔
69
        *opts, help=("(this is the default)" if default else None),
70
        dest=dest, action='store_true')
71
    if no_names is None:
6 !
72
        def add_no(x):
6 ✔
73
            x = x.lstrip("-")
6 ✔
74
            return ("no_"+x) if "_" in x else ("no-"+x)
6 ✔
75
        no_names = [add_no(x) for x in names]
6 ✔
76
    opts = [add_dashes(x) for x in no_names]
6 ✔
77
    group.add_argument(
6 ✔
78
        *opts, help=(None if default else "(this is the default)"),
79
        dest=dest, action='store_false')
80
    parser.set_defaults(**{dest: default})
6 ✔
81

82

83
def require_prebuilt_dist(func):
6 ✔
84
    """Decorator for ToolchainCL methods. If present, the method will
85
    automatically make sure a dist has been built before continuing
86
    or, if no dists are present or can be obtained, will raise an
87
    error.
88
    """
89

90
    @wraps(func)
6 ✔
91
    def wrapper_func(self, args, **kw):
6 ✔
92
        ctx = self.ctx
6 ✔
93
        ctx.set_archs(self._archs)
6 ✔
94
        ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir,
6 ✔
95
                                      user_ndk_dir=self.ndk_dir,
96
                                      user_android_api=self.android_api,
97
                                      user_ndk_api=self.ndk_api)
98
        dist = self._dist
6 ✔
99
        if dist.needs_build:
6 !
100
            if dist.folder_exists():  # possible if the dist is being replaced
6 !
101
                dist.delete()
×
102
            info_notify('No dist exists that meets your requirements, '
6 ✔
103
                        'so one will be built.')
104
            build_dist_from_args(ctx, dist, args)
6 ✔
105
        func(self, args, **kw)
6 ✔
106
    return wrapper_func
6 ✔
107

108

109
def dist_from_args(ctx, args):
6 ✔
110
    """Parses out any distribution-related arguments, and uses them to
111
    obtain a Distribution class instance for the build.
112
    """
113
    return Distribution.get_distribution(
6 ✔
114
        ctx,
115
        name=args.dist_name,
116
        recipes=split_argument_list(args.requirements),
117
        archs=args.arch,
118
        ndk_api=args.ndk_api,
119
        force_build=args.force_build,
120
        require_perfect_match=args.require_perfect_match,
121
        allow_replace_dist=args.allow_replace_dist)
122

123

124
def build_dist_from_args(ctx, dist, args):
6 ✔
125
    """Parses out any bootstrap related arguments, and uses them to build
126
    a dist."""
127
    bs = Bootstrap.get_bootstrap(args.bootstrap, ctx)
6 ✔
128
    blacklist = getattr(args, "blacklist_requirements", "").split(",")
6 ✔
129
    if len(blacklist) == 1 and blacklist[0] == "":
6 !
130
        blacklist = []
6 ✔
131
    build_order, python_modules, bs = (
6 ✔
132
        get_recipe_order_and_bootstrap(
133
            ctx, dist.recipes, bs,
134
            blacklist=blacklist
135
        ))
136
    assert set(build_order).intersection(set(python_modules)) == set()
6 ✔
137
    ctx.recipe_build_order = build_order
6 ✔
138
    ctx.python_modules = python_modules
6 ✔
139

140
    info('The selected bootstrap is {}'.format(bs.name))
6 ✔
141
    info_main('# Creating dist with {} bootstrap'.format(bs.name))
6 ✔
142
    bs.distribution = dist
6 ✔
143
    info_notify('Dist will have name {} and requirements ({})'.format(
6 ✔
144
        dist.name, ', '.join(dist.recipes)))
145
    info('Dist contains the following requirements as recipes: {}'.format(
6 ✔
146
        ctx.recipe_build_order))
147
    info('Dist will also contain modules ({}) installed from pip'.format(
6 ✔
148
        ', '.join(ctx.python_modules)))
149
    info(
6 ✔
150
        'Dist will be build in mode {build_mode}{with_debug_symbols}'.format(
151
            build_mode='debug' if ctx.build_as_debuggable else 'release',
152
            with_debug_symbols=' (with debug symbols)'
153
            if ctx.with_debug_symbols
154
            else '',
155
        )
156
    )
157

158
    ctx.distribution = dist
6 ✔
159
    ctx.prepare_bootstrap(bs)
6 ✔
160
    if dist.needs_build:
6 !
161
        ctx.prepare_dist()
6 ✔
162

163
    build_recipes(build_order, python_modules, ctx,
6 ✔
164
                  getattr(args, "private", None),
165
                  ignore_project_setup_py=getattr(
166
                      args, "ignore_setup_py", False
167
                  ),
168
                 )
169

170
    ctx.bootstrap.assemble_distribution()
6 ✔
171

172
    info_main('# Your distribution was created successfully, exiting.')
6 ✔
173
    info('Dist can be found at (for now) {}'
6 ✔
174
         .format(join(ctx.dist_dir, ctx.distribution.dist_dir)))
175

176

177
def split_argument_list(arg_list):
6 ✔
178
    if not len(arg_list):
6 ✔
179
        return []
6 ✔
180
    return re.split(r'[ ,]+', arg_list)
6 ✔
181

182

183
class NoAbbrevParser(argparse.ArgumentParser):
6 ✔
184
    """We want to disable argument abbreviation so as not to interfere
185
    with passing through arguments to build.py, but in python2 argparse
186
    doesn't have this option.
187

188
    This subclass alternative is follows the suggestion at
189
    https://bugs.python.org/issue14910.
190
    """
191

192
    def _get_option_tuples(self, option_string):
6 ✔
193
        return []
6 ✔
194

195

196
class ToolchainCL:
6 ✔
197

198
    def __init__(self):
6 ✔
199

200
        argv = sys.argv
6 ✔
201
        self.warn_on_carriage_return_args(argv)
6 ✔
202
        # Buildozer used to pass these arguments in a now-invalid order
203
        # If that happens, apply this fix
204
        # This fix will be removed once a fixed buildozer is released
205
        if (len(argv) > 2
6 !
206
                and argv[1].startswith('--color')
207
                and argv[2].startswith('--storage-dir')):
208
            argv.append(argv.pop(1))  # the --color arg
×
209
            argv.append(argv.pop(1))  # the --storage-dir arg
×
210

211
        parser = NoAbbrevParser(
6 ✔
212
            description='A packaging tool for turning Python scripts and apps '
213
                        'into Android APKs')
214

215
        generic_parser = argparse.ArgumentParser(
6 ✔
216
            add_help=False,
217
            description='Generic arguments applied to all commands')
218
        argparse.ArgumentParser(
6 ✔
219
            add_help=False, description='Arguments for dist building')
220

221
        generic_parser.add_argument(
6 ✔
222
            '--debug', dest='debug', action='store_true', default=False,
223
            help='Display debug output and all build info')
224
        generic_parser.add_argument(
6 ✔
225
            '--color', dest='color', choices=['always', 'never', 'auto'],
226
            help='Enable or disable color output (default enabled on tty)')
227
        generic_parser.add_argument(
6 ✔
228
            '--sdk-dir', '--sdk_dir', dest='sdk_dir', default='',
229
            help='The filepath where the Android SDK is installed')
230
        generic_parser.add_argument(
6 ✔
231
            '--ndk-dir', '--ndk_dir', dest='ndk_dir', default='',
232
            help='The filepath where the Android NDK is installed')
233
        generic_parser.add_argument(
6 ✔
234
            '--android-api',
235
            '--android_api',
236
            dest='android_api',
237
            default=0,
238
            type=int,
239
            help=('The Android API level to build against defaults to {} if '
240
                  'not specified.').format(RECOMMENDED_TARGET_API))
241
        generic_parser.add_argument(
6 ✔
242
            '--ndk-version', '--ndk_version', dest='ndk_version', default=None,
243
            help=('DEPRECATED: the NDK version is now found automatically or '
244
                  'not at all.'))
245
        generic_parser.add_argument(
6 ✔
246
            '--ndk-api', type=int, default=None,
247
            help=('The Android API level to compile against. This should be your '
248
                  '*minimal supported* API, not normally the same as your --android-api. '
249
                  'Defaults to min(ANDROID_API, {}) if not specified.').format(RECOMMENDED_NDK_API))
250
        generic_parser.add_argument(
6 ✔
251
            '--symlink-bootstrap-files', '--ssymlink_bootstrap_files',
252
            action='store_true',
253
            dest='symlink_bootstrap_files',
254
            default=False,
255
            help=('If True, symlinks the bootstrap files '
256
                  'creation. This is useful for development only, it could also'
257
                  ' cause weird problems.'))
258

259
        default_storage_dir = user_data_dir('python-for-android')
6 ✔
260
        if ' ' in default_storage_dir:
6 !
261
            default_storage_dir = '~/.python-for-android'
×
262
        generic_parser.add_argument(
6 ✔
263
            '--storage-dir', dest='storage_dir', default=default_storage_dir,
264
            help=('Primary storage directory for downloads and builds '
265
                  '(default: {})'.format(default_storage_dir)))
266

267
        generic_parser.add_argument(
6 ✔
268
            '--arch', help='The archs to build for.',
269
            action='append', default=[])
270

271
        generic_parser.add_argument(
6 ✔
272
            '--extra-index-url',
273
            help=(
274
                'Extra package indexes to look for prebuilt Android wheels. '
275
                'Can be used multiple times.'
276
            ),
277
            action='append',
278
            default=[],
279
            dest="extra_index_urls",
280
        )
281

282
        generic_parser.add_argument(
6 ✔
283
            '--skip-prebuilt',
284
            help='Always build from source; do not use prebuilt wheels.',
285
            action='store_true',
286
            default=False,
287
            dest="skip_prebuilt",
288
        )
289

290
        generic_parser.add_argument(
6 ✔
291
            '--use-prebuilt-version-for',
292
            help=(
293
                'For these packages, ignore pinned versions and use the latest '
294
                'prebuilt version from the extra index if available. '
295
                'Only applies to packages with a recipe.'
296
            ),
297
            action='append',
298
            default=[],
299
            dest="use_prebuilt_version_for",
300
        )
301

302
        generic_parser.add_argument(
6 ✔
303
            '--save-wheel-dir',
304
            dest='save_wheel_dir',
305
            default='',
306
            help='Directory to store wheels built by PyProjectRecipe.',
307
        )
308

309
        # Options for specifying the Distribution
310
        generic_parser.add_argument(
6 ✔
311
            '--dist-name', '--dist_name',
312
            help='The name of the distribution to use or create', default='')
313

314
        generic_parser.add_argument(
6 ✔
315
            '--requirements',
316
            help=('Dependencies of your app, should be recipe names or '
317
                  'Python modules. NOT NECESSARY if you are using '
318
                  'Python 3 with --use-setup-py'),
319
            default='')
320

321
        generic_parser.add_argument(
6 ✔
322
            '--recipe-blacklist',
323
            help=('Blacklist an internal recipe from use. Allows '
324
                  'disabling Python 3 core modules to save size'),
325
            dest="recipe_blacklist",
326
            default='')
327

328
        generic_parser.add_argument(
6 ✔
329
            '--blacklist-requirements',
330
            help=('Blacklist an internal recipe from use. Allows '
331
                  'disabling Python 3 core modules to save size'),
332
            dest="blacklist_requirements",
333
            default='')
334

335
        generic_parser.add_argument(
6 ✔
336
            '--use-setup-py', dest="use_setup_py",
337
            action='store_true', default=False,
338
            help="Process the setup.py of a project if present. " +
339
                 "(Experimental!")
340
        generic_parser.add_argument(
6 ✔
341
            '--ignore-setup-py', dest="ignore_setup_py",
342
            action='store_true', default=False,
343
            help="Don't run the setup.py of a project if present. " +
344
                 "This may be required if the setup.py is not " +
345
                 "designed to work inside p4a (e.g. by installing " +
346
                 "dependencies that won't work or aren't desired " +
347
                 "on Android")
348

349
        generic_parser.add_argument(
6 ✔
350
            '--bootstrap',
351
            help='The bootstrap to build with. Leave unset to choose '
352
                 'automatically.',
353
            default=None)
354

355
        generic_parser.add_argument(
6 ✔
356
            '--hook',
357
            help='Filename to a module that contains python-for-android hooks',
358
            default=None)
359

360
        add_boolean_option(
6 ✔
361
            generic_parser, ["force-build"],
362
            default=False,
363
            description='Whether to force compilation of a new distribution')
364

365
        add_boolean_option(
6 ✔
366
            generic_parser, ["require-perfect-match"],
367
            default=False,
368
            description=('Whether the dist recipes must perfectly match '
369
                         'those requested'))
370

371
        add_boolean_option(
6 ✔
372
            generic_parser, ["allow-replace-dist"],
373
            default=True,
374
            description='Whether existing dist names can be automatically replaced'
375
            )
376

377
        generic_parser.add_argument(
6 ✔
378
            '--local-recipes', '--local_recipes',
379
            dest='local_recipes', default='./p4a-recipes',
380
            help='Directory to look for local recipes')
381

382
        generic_parser.add_argument(
6 ✔
383
            '--activity-class-name',
384
            dest='activity_class_name', default='org.kivy.android.PythonActivity',
385
            help='The full java class name of the main activity')
386

387
        generic_parser.add_argument(
6 ✔
388
            '--service-class-name',
389
            dest='service_class_name', default='org.kivy.android.PythonService',
390
            help='Full java package name of the PythonService class')
391

392
        generic_parser.add_argument(
6 ✔
393
            '--java-build-tool',
394
            dest='java_build_tool', default='auto',
395
            choices=['auto', 'ant', 'gradle'],
396
            help=('The java build tool to use when packaging the APK, defaults '
397
                  'to automatically selecting an appropriate tool.'))
398

399
        # Also an argument of the bootstrap build.py
400
        generic_parser.add_argument(
6 ✔
401
            '--no-optimize-python', dest='optimize_python',
402
            action='store_false', default=True,
403
            help=('Whether to compile to optimised .pyc files, using -OO '
404
                  '(strips docstrings and asserts)'))
405

406
        add_boolean_option(
6 ✔
407
            generic_parser, ['copy-libs'],
408
            default=False,
409
            description='Copy libraries instead of using biglink (Android 4.3+)'
410
        )
411

412
        self._read_configuration()
6 ✔
413

414
        subparsers = parser.add_subparsers(dest='subparser_name',
6 ✔
415
                                           help='The command to run')
416

417
        subparsers.add_parser(
6 ✔
418
            'recommendations',
419
            parents=[generic_parser],
420
            help='List recommended p4a dependencies')
421
        parser_recipes = subparsers.add_parser(
6 ✔
422
            'recipes',
423
            parents=[generic_parser],
424
            help='List the available recipes')
425
        parser_recipes.add_argument(
6 ✔
426
            "--compact",
427
            action="store_true", default=False,
428
            help="Produce a compact list suitable for scripting")
429
        subparsers.add_parser(
6 ✔
430
            'bootstraps',
431
            help='List the available bootstraps',
432
            parents=[generic_parser])
433
        subparsers.add_parser(
6 ✔
434
            'clean_all',
435
            aliases=['clean-all'],
436
            help='Delete all builds, dists and caches',
437
            parents=[generic_parser])
438
        subparsers.add_parser(
6 ✔
439
            'clean_dists',
440
            aliases=['clean-dists'],
441
            help='Delete all dists',
442
            parents=[generic_parser])
443
        subparsers.add_parser(
6 ✔
444
            'clean_bootstrap_builds',
445
            aliases=['clean-bootstrap-builds'],
446
            help='Delete all bootstrap builds',
447
            parents=[generic_parser])
448
        subparsers.add_parser(
6 ✔
449
            'clean_builds',
450
            aliases=['clean-builds'],
451
            help='Delete all builds',
452
            parents=[generic_parser])
453

454
        parser_clean = subparsers.add_parser(
6 ✔
455
            'clean',
456
            help='Delete build components.',
457
            parents=[generic_parser])
458
        parser_clean.add_argument(
6 ✔
459
            'component', nargs='+',
460
            help=('The build component(s) to delete. You can pass any '
461
                  'number of arguments from "all", "builds", "dists", '
462
                  '"distributions", "bootstrap_builds", "downloads".'))
463

464
        parser_clean_recipe_build = subparsers.add_parser(
6 ✔
465
            'clean_recipe_build', aliases=['clean-recipe-build'],
466
            help=('Delete the build components of the given recipe. '
467
                  'By default this will also delete built dists'),
468
            parents=[generic_parser])
469
        parser_clean_recipe_build.add_argument(
6 ✔
470
            'recipe', help='The recipe name')
471
        parser_clean_recipe_build.add_argument(
6 ✔
472
            '--no-clean-dists', default=False,
473
            dest='no_clean_dists',
474
            action='store_true',
475
            help='If passed, do not delete existing dists')
476

477
        parser_clean_download_cache = subparsers.add_parser(
6 ✔
478
            'clean_download_cache', aliases=['clean-download-cache'],
479
            help='Delete cached downloads for requirement builds',
480
            parents=[generic_parser])
481
        parser_clean_download_cache.add_argument(
6 ✔
482
            'recipes',
483
            nargs='*',
484
            help='The recipes to clean (space-separated). If no recipe name is'
485
                  ' provided, the entire cache is cleared.')
486

487
        parser_export_dist = subparsers.add_parser(
6 ✔
488
            'export_dist', aliases=['export-dist'],
489
            help='Copy the named dist to the given path',
490
            parents=[generic_parser])
491
        parser_export_dist.add_argument('output_dir',
6 ✔
492
                                        help='The output dir to copy to')
493
        parser_export_dist.add_argument(
6 ✔
494
            '--symlink',
495
            action='store_true',
496
            help='Symlink the dist instead of copying')
497

498
        parser_packaging = argparse.ArgumentParser(
6 ✔
499
            parents=[generic_parser],
500
            add_help=False,
501
            description='common options for packaging (apk, aar)')
502

503
        # This is actually an internal argument of the build.py
504
        # (see pythonforandroid/bootstraps/common/build/build.py).
505
        # However, it is also needed before the distribution is finally
506
        # assembled for locating the setup.py / other build systems, which
507
        # is why we also add it here:
508
        parser_packaging.add_argument(
6 ✔
509
            '--add-asset', dest='assets',
510
            action="append", default=[],
511
            help='Put this in the assets folder in the apk.')
512
        parser_packaging.add_argument(
6 ✔
513
            '--add-resource', dest='resources',
514
            action="append", default=[],
515
            help='Put this in the res folder in the apk.')
516
        parser_packaging.add_argument(
6 ✔
517
            '--private', dest='private',
518
            help='the directory with the app source code files' +
519
                 ' (containing your main.py entrypoint)',
520
            required=False, default=None)
521

522
        parser_packaging.add_argument(
6 ✔
523
            '--release', dest='build_mode', action='store_const',
524
            const='release', default='debug',
525
            help='Build your app as a non-debug release build. '
526
                 '(Disables gdb debugging among other things)')
527
        parser_packaging.add_argument(
6 ✔
528
            '--with-debug-symbols', dest='with_debug_symbols',
529
            action='store_const', const=True, default=False,
530
            help='Will keep debug symbols from `.so` files.')
531
        parser_packaging.add_argument(
6 ✔
532
            '--keystore', dest='keystore', action='store', default=None,
533
            help=('Keystore for JAR signing key, will use jarsigner '
534
                  'default if not specified (release build only)'))
535
        parser_packaging.add_argument(
6 ✔
536
            '--signkey', dest='signkey', action='store', default=None,
537
            help='Key alias to sign PARSER_APK. with (release build only)')
538
        parser_packaging.add_argument(
6 ✔
539
            '--keystorepw', dest='keystorepw', action='store', default=None,
540
            help='Password for keystore')
541
        parser_packaging.add_argument(
6 ✔
542
            '--signkeypw', dest='signkeypw', action='store', default=None,
543
            help='Password for key alias')
544

545
        subparsers.add_parser(
6 ✔
546
            'aar', help='Build an AAR',
547
            parents=[parser_packaging])
548

549
        subparsers.add_parser(
6 ✔
550
            'apk', help='Build an APK',
551
            parents=[parser_packaging])
552

553
        subparsers.add_parser(
6 ✔
554
            'aab', help='Build an AAB',
555
            parents=[parser_packaging])
556

557
        subparsers.add_parser(
6 ✔
558
            'create', help='Compile a set of requirements into a dist',
559
            parents=[generic_parser])
560
        subparsers.add_parser(
6 ✔
561
            'archs', help='List the available target architectures',
562
            parents=[generic_parser])
563
        subparsers.add_parser(
6 ✔
564
            'distributions', aliases=['dists'],
565
            help='List the currently available (compiled) dists',
566
            parents=[generic_parser])
567
        subparsers.add_parser(
6 ✔
568
            'delete_dist', aliases=['delete-dist'], help='Delete a compiled dist',
569
            parents=[generic_parser])
570

571
        parser_sdk_tools = subparsers.add_parser(
6 ✔
572
            'sdk_tools', aliases=['sdk-tools'],
573
            help='Run the given binary from the SDK tools dis',
574
            parents=[generic_parser])
575
        parser_sdk_tools.add_argument(
6 ✔
576
            'tool', help='The binary tool name to run')
577

578
        subparsers.add_parser(
6 ✔
579
            'adb', help='Run adb from the given SDK',
580
            parents=[generic_parser])
581
        subparsers.add_parser(
6 ✔
582
            'logcat', help='Run logcat from the given SDK',
583
            parents=[generic_parser])
584
        subparsers.add_parser(
6 ✔
585
            'build_status', aliases=['build-status'],
586
            help='Print some debug information about current built components',
587
            parents=[generic_parser])
588

589
        parser.add_argument('-v', '--version', action='version',
6 ✔
590
                            version=__version__)
591

592
        args, unknown = parser.parse_known_args(sys.argv[1:])
6 ✔
593
        args.unknown_args = unknown
6 ✔
594

595
        if getattr(args, "private", None) is not None:
6 !
596
            # Pass this value on to the internal bootstrap build.py:
597
            args.unknown_args += ["--private", args.private]
×
598
        if getattr(args, "build_mode", None) == "release":
6 !
599
            args.unknown_args += ["--release"]
×
600
        if getattr(args, "with_debug_symbols", False):
6 !
601
            args.unknown_args += ["--with-debug-symbols"]
×
602
        if not getattr(args, "optimize_python", True):
6 !
603
            args.unknown_args += ["--no-optimize-python"]
×
604
        if getattr(args, "ignore_setup_py", False):
6 !
605
            args.use_setup_py = False
×
606
        if getattr(args, "activity_class_name", "org.kivy.android.PythonActivity") != 'org.kivy.android.PythonActivity':
6 ✔
607
            args.unknown_args += ["--activity-class-name", args.activity_class_name]
6 ✔
608
        if getattr(args, "service_class_name", "org.kivy.android.PythonService") != 'org.kivy.android.PythonService':
6 ✔
609
            args.unknown_args += ["--service-class-name", args.service_class_name]
6 ✔
610

611
        self.args = args
6 ✔
612

613
        if args.subparser_name is None:
6 ✔
614
            parser.print_help()
6 ✔
615
            exit(1)
6 ✔
616

617
        setup_color(args.color)
6 ✔
618

619
        if args.debug:
6 !
620
            logger.setLevel(logging.DEBUG)
×
621

622
        self.ctx = Context()
6 ✔
623
        self.ctx.use_setup_py = getattr(args, "use_setup_py", True)
6 ✔
624
        self.ctx.build_as_debuggable = getattr(
6 ✔
625
            args, "build_mode", "debug"
626
        ) == "debug"
627
        self.ctx.with_debug_symbols = getattr(
6 ✔
628
            args, "with_debug_symbols", False
629
        )
630
        self.ctx.optimize_python = getattr(args, "optimize_python", True)
6 ✔
631

632
        # Process requirements and put version in environ
633
        if hasattr(args, 'requirements'):
6 !
634
            requirements = []
6 ✔
635

636
            # Add dependencies from setup.py, but only if they are recipes
637
            # (because otherwise, setup.py itself will install them later)
638
            if (project_has_setup_py(getattr(args, "private", None)) and
6 !
639
                    getattr(args, "use_setup_py", False)):
640
                try:
×
641
                    info("Analyzing package dependencies. MAY TAKE A WHILE.")
×
642
                    # Get all the dependencies corresponding to a recipe:
643
                    dependencies = [
×
644
                        dep.lower() for dep in
645
                        get_dep_names_of_package(
646
                            args.private,
647
                            keep_version_pins=True,
648
                            recursive=True,
649
                            verbose=True,
650
                        )
651
                    ]
652
                    info("Dependencies obtained: " + str(dependencies))
×
653
                    all_recipes = [
×
654
                        recipe.lower() for recipe in
655
                        set(Recipe.list_recipes(self.ctx))
656
                    ]
657
                    dependencies = set(dependencies).intersection(
×
658
                        set(all_recipes)
659
                    )
NEW
660
                    existing_reqs = {
×
661
                        req.split("==", 1)[0].strip().lower()
662
                        for req in split_argument_list(args.requirements)
663
                        if req.strip()
664
                    }
NEW
665
                    dependencies = {
×
666
                        dep for dep in dependencies
667
                        if dep.split("==", 1)[0] not in existing_reqs
668
                    }
669
                    # Add dependencies to argument list:
670
                    if len(dependencies) > 0:
×
671
                        if len(args.requirements) > 0:
×
672
                            args.requirements += u","
×
673
                        args.requirements += u",".join(dependencies)
×
674
                except ValueError:
×
675
                    # Not a python package, apparently.
676
                    warning(
×
677
                        "Processing failed, is this project a valid "
678
                        "package? Will continue WITHOUT setup.py deps."
679
                    )
680

681
            # Parse --requirements argument list:
682
            for requirement in split_argument_list(args.requirements):
6 ✔
683
                if "==" in requirement:
6 !
684
                    requirement, version = requirement.split(u"==", 1)
×
685
                    os.environ["VERSION_{}".format(requirement)] = version
×
686
                    info('Recipe {}: version "{}" requested'.format(
×
687
                        requirement, version))
688
                requirements.append(requirement)
6 ✔
689
            args.requirements = u",".join(requirements)
6 ✔
690

691
        self.warn_on_deprecated_args(args)
6 ✔
692

693
        self.storage_dir = args.storage_dir
6 ✔
694
        self.ctx.setup_dirs(self.storage_dir)
6 ✔
695
        self.sdk_dir = args.sdk_dir
6 ✔
696
        self.ndk_dir = args.ndk_dir
6 ✔
697
        self.android_api = args.android_api
6 ✔
698
        self.ndk_api = args.ndk_api
6 ✔
699
        self.ctx.symlink_bootstrap_files = args.symlink_bootstrap_files
6 ✔
700
        self.ctx.java_build_tool = args.java_build_tool
6 ✔
701

702
        self._archs = args.arch
6 ✔
703

704
        self.ctx.local_recipes = realpath(args.local_recipes)
6 ✔
705
        self.ctx.copy_libs = args.copy_libs
6 ✔
706

707
        self.ctx.activity_class_name = args.activity_class_name
6 ✔
708
        self.ctx.service_class_name = args.service_class_name
6 ✔
709

710
        self.ctx.extra_index_urls = args.extra_index_urls
6 ✔
711
        self.ctx.skip_prebuilt = args.skip_prebuilt
6 ✔
712
        self.ctx.use_prebuilt_version_for = args.use_prebuilt_version_for
6 ✔
713
        self.ctx.save_wheel_dir = args.save_wheel_dir
6 ✔
714

715
        # Each subparser corresponds to a method
716
        command = args.subparser_name.replace('-', '_')
6 ✔
717
        getattr(self, command)(args)
6 ✔
718

719
    @staticmethod
6 ✔
720
    def warn_on_carriage_return_args(args):
6 ✔
721
        for check_arg in args:
6 ✔
722
            if '\r' in check_arg:
6 !
723
                warning("Argument '{}' contains a carriage return (\\r).".format(str(check_arg.replace('\r', ''))))
×
724
                warning("Invoking this program via scripts which use CRLF instead of LF line endings will have undefined behaviour.")
×
725

726
    def warn_on_deprecated_args(self, args):
6 ✔
727
        """
728
        Print warning messages for any deprecated arguments that were passed.
729
        """
730

731
        # Output warning if setup.py is present and neither --ignore-setup-py
732
        # nor --use-setup-py was specified.
733
        if project_has_setup_py(getattr(args, "private", None)):
6 !
734
            if not getattr(args, "use_setup_py", False) and \
×
735
                    not getattr(args, "ignore_setup_py", False):
736
                warning("  **** FUTURE BEHAVIOR CHANGE WARNING ****")
×
737
                warning("Your project appears to contain a setup.py file.")
×
738
                warning("Currently, these are ignored by default.")
×
739
                warning("This will CHANGE in an upcoming version!")
×
740
                warning("")
×
741
                warning("To ensure your setup.py is ignored, please specify:")
×
742
                warning("    --ignore-setup-py")
×
743
                warning("")
×
744
                warning("To enable what will some day be the default, specify:")
×
745
                warning("    --use-setup-py")
×
746

747
        # NDK version is now determined automatically
748
        if args.ndk_version is not None:
6 !
749
            warning('--ndk-version is deprecated and no longer necessary, '
×
750
                    'the value you passed is ignored')
751
        if 'ANDROIDNDKVER' in environ:
6 !
752
            warning('$ANDROIDNDKVER is deprecated and no longer necessary, '
×
753
                    'the value you set is ignored')
754

755
    def hook(self, name):
6 ✔
756
        if not self.args.hook:
×
757
            return
×
758
        if not hasattr(self, "hook_module"):
×
759
            # first time, try to load the hook module
760
            self.hook_module = load_source(
×
761
                "pythonforandroid.hook", self.args.hook)
762
        if hasattr(self.hook_module, name):
×
763
            info("Hook: execute {}".format(name))
×
764
            getattr(self.hook_module, name)(self)
×
765
        else:
766
            info("Hook: ignore {}".format(name))
×
767

768
    @property
6 ✔
769
    def default_storage_dir(self):
6 ✔
770
        udd = user_data_dir('python-for-android')
×
771
        if ' ' in udd:
×
772
            udd = '~/.python-for-android'
×
773
        return udd
×
774

775
    @staticmethod
6 ✔
776
    def _read_configuration():
6 ✔
777
        # search for a .p4a configuration file in the current directory
778
        if not exists(".p4a"):
6 !
779
            return
6 ✔
780
        info("Reading .p4a configuration")
×
781
        with open(".p4a") as fd:
×
782
            lines = fd.readlines()
×
783
        lines = [shlex.split(line)
×
784
                 for line in lines if not line.startswith("#")]
785
        for line in lines:
×
786
            for arg in line:
×
787
                sys.argv.append(arg)
×
788

789
    def recipes(self, args):
6 ✔
790
        """
791
        Prints recipes basic info, e.g.
792
        .. code-block:: bash
793

794
            python3      3.7.1
795
                depends: ['hostpython3', 'sqlite3', 'openssl', 'libffi']
796
                conflicts: []
797
                optional depends: ['sqlite3', 'libffi', 'openssl']
798
        """
799
        ctx = self.ctx
6 ✔
800
        if args.compact:
6 !
801
            print(" ".join(set(Recipe.list_recipes(ctx))))
×
802
        else:
803
            for name in sorted(Recipe.list_recipes(ctx)):
6 ✔
804
                try:
6 ✔
805
                    recipe = Recipe.get_recipe(name, ctx)
6 ✔
806
                except (IOError, ValueError):
×
807
                    warning('Recipe "{}" could not be loaded'.format(name))
×
808
                except SyntaxError:
×
809
                    import traceback
×
810
                    traceback.print_exc()
×
811
                    warning(('Recipe "{}" could not be loaded due to a '
×
812
                             'syntax error').format(name))
813
                version = str(recipe.version)
6 ✔
814
                print('{Fore.BLUE}{Style.BRIGHT}{recipe.name:<12} '
6 ✔
815
                      '{Style.RESET_ALL}{Fore.LIGHTBLUE_EX}'
816
                      '{version:<8}{Style.RESET_ALL}'.format(
817
                            recipe=recipe, Fore=Out_Fore, Style=Out_Style,
818
                            version=version))
819
                print('    {Fore.GREEN}depends: {recipe.depends}'
6 ✔
820
                      '{Fore.RESET}'.format(recipe=recipe, Fore=Out_Fore))
821
                if recipe.conflicts:
6 ✔
822
                    print('    {Fore.RED}conflicts: {recipe.conflicts}'
6 ✔
823
                          '{Fore.RESET}'
824
                          .format(recipe=recipe, Fore=Out_Fore))
825
                if recipe.opt_depends:
6 ✔
826
                    print('    {Fore.YELLOW}optional depends: '
6 ✔
827
                          '{recipe.opt_depends}{Fore.RESET}'
828
                          .format(recipe=recipe, Fore=Out_Fore))
829

830
    def bootstraps(self, _args):
6 ✔
831
        """List all the bootstraps available to build with."""
832
        for bs in Bootstrap.all_bootstraps():
×
833
            bs = Bootstrap.get_bootstrap(bs, self.ctx)
×
834
            print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}'
×
835
                  .format(bs=bs, Fore=Out_Fore, Style=Out_Style))
836
            print('    {Fore.GREEN}depends: {bs.recipe_depends}{Fore.RESET}'
×
837
                  .format(bs=bs, Fore=Out_Fore))
838

839
    def clean(self, args):
6 ✔
840
        components = args.component
×
841

842
        component_clean_methods = {
×
843
            'all': self.clean_all,
844
            'dists': self.clean_dists,
845
            'distributions': self.clean_dists,
846
            'builds': self.clean_builds,
847
            'bootstrap_builds': self.clean_bootstrap_builds,
848
            'downloads': self.clean_download_cache}
849

850
        for component in components:
×
851
            if component not in component_clean_methods:
×
852
                raise BuildInterruptingException((
×
853
                    'Asked to clean "{}" but this argument is not '
854
                    'recognised'.format(component)))
855
            component_clean_methods[component](args)
×
856

857
    def clean_all(self, args):
6 ✔
858
        """Delete all build components; the package cache, package builds,
859
        bootstrap builds and distributions."""
860
        self.clean_dists(args)
×
861
        self.clean_builds(args)
×
862
        self.clean_download_cache(args)
×
863

864
    def clean_dists(self, _args):
6 ✔
865
        """Delete all compiled distributions in the internal distribution
866
        directory."""
867
        ctx = self.ctx
×
868
        rmdir(ctx.dist_dir)
×
869

870
    def clean_bootstrap_builds(self, _args):
6 ✔
871
        """Delete all the bootstrap builds."""
872
        rmdir(join(self.ctx.build_dir, 'bootstrap_builds'))
×
873
        # for bs in Bootstrap.all_bootstraps():
874
        #     bs = Bootstrap.get_bootstrap(bs, self.ctx)
875
        #     if bs.build_dir and exists(bs.build_dir):
876
        #         info('Cleaning build for {} bootstrap.'.format(bs.name))
877
        #         rmdir(bs.build_dir)
878

879
    def clean_builds(self, _args):
6 ✔
880
        """Delete all build caches for each recipe, python-install, java code
881
        and compiled libs collection.
882

883
        This does *not* delete the package download cache or the final
884
        distributions.  You can also use clean_recipe_build to delete the build
885
        of a specific recipe.
886
        """
887
        ctx = self.ctx
×
888
        rmdir(ctx.build_dir)
×
889
        rmdir(ctx.python_installs_dir)
×
890
        libs_dir = join(self.ctx.build_dir, 'libs_collections')
×
891
        rmdir(libs_dir)
×
892

893
    def clean_recipe_build(self, args):
6 ✔
894
        """Deletes the build files of the given recipe.
895

896
        This is intended for debug purposes. You may experience
897
        strange behaviour or problems with some recipes if their
898
        build has made unexpected state changes. If this happens, run
899
        clean_builds, or attempt to clean other recipes until things
900
        work again.
901
        """
902
        recipe = Recipe.get_recipe(args.recipe, self.ctx)
×
903
        info('Cleaning build for {} recipe.'.format(recipe.name))
×
904
        recipe.clean_build()
×
905
        if not args.no_clean_dists:
×
906
            self.clean_dists(args)
×
907

908
    def clean_download_cache(self, args):
6 ✔
909
        """ Deletes a download cache for recipes passed as arguments. If no
910
        argument is passed, it'll delete *all* downloaded caches. ::
911

912
            p4a clean_download_cache kivy,pyjnius
913

914
        This does *not* delete the build caches or final distributions.
915
        """
916
        ctx = self.ctx
×
917
        if hasattr(args, 'recipes') and args.recipes:
×
918
            for package in args.recipes:
×
919
                remove_path = join(ctx.packages_path, package)
×
920
                if exists(remove_path):
×
921
                    rmdir(remove_path)
×
922
                    info('Download cache removed for: "{}"'.format(package))
×
923
                else:
924
                    warning('No download cache found for "{}", skipping'.format(
×
925
                        package))
926
        else:
927
            if exists(ctx.packages_path):
×
928
                rmdir(ctx.packages_path)
×
929
                info('Download cache removed.')
×
930
            else:
931
                print('No cache found at "{}"'.format(ctx.packages_path))
×
932

933
    @require_prebuilt_dist
6 ✔
934
    def export_dist(self, args):
6 ✔
935
        """Copies a created dist to an output dir.
936

937
        This makes it easy to navigate to the dist to investigate it
938
        or call build.py, though you do not in general need to do this
939
        and can use the apk command instead.
940
        """
941
        ctx = self.ctx
×
942
        dist = dist_from_args(ctx, args)
×
943
        if dist.needs_build:
×
944
            raise BuildInterruptingException(
×
945
                'You asked to export a dist, but there is no dist '
946
                'with suitable recipes available. For now, you must '
947
                ' create one first with the create argument.')
948
        if args.symlink:
×
949
            shprint(sh.ln, '-s', dist.dist_dir, args.output_dir)
×
950
        else:
951
            shprint(sh.cp, '-r', dist.dist_dir, args.output_dir)
×
952

953
    @property
6 ✔
954
    def _dist(self):
6 ✔
955
        ctx = self.ctx
6 ✔
956
        dist = dist_from_args(ctx, self.args)
6 ✔
957
        ctx.distribution = dist
6 ✔
958
        return dist
6 ✔
959

960
    @staticmethod
6 ✔
961
    def _fix_args(args):
6 ✔
962
        """
963
        Manually fixing these arguments at the string stage is
964
        unsatisfactory and should probably be changed somehow, but
965
        we can't leave it until later as the build.py scripts assume
966
        they are in the current directory.
967
        works in-place
968
        :param args: parser args
969
        """
970

971
        fix_args = ('--dir', '--private', '--add-jar', '--add-source',
×
972
                    '--whitelist', '--blacklist', '--presplash', '--icon',
973
                    '--icon-bg', '--icon-fg')
974
        unknown_args = args.unknown_args
×
975

976
        for asset in args.assets:
×
977
            if ":" in asset:
×
978
                asset_src, asset_dest = asset.split(":")
×
979
            else:
980
                asset_src = asset_dest = asset
×
981
            # take abspath now, because build.py will be run in bootstrap dir
982
            unknown_args += ["--asset", os.path.abspath(asset_src)+":"+asset_dest]
×
983
        for resource in args.resources:
×
984
            if ":" in resource:
×
985
                resource_src, resource_dest = resource.split(":")
×
986
            else:
987
                resource_src = resource
×
988
                resource_dest = ""
×
989
            # take abspath now, because build.py will be run in bootstrap dir
990
            unknown_args += ["--resource", os.path.abspath(resource_src)+":"+resource_dest]
×
991
        for i, arg in enumerate(unknown_args):
×
992
            argx = arg.split('=')
×
993
            if argx[0] in fix_args:
×
994
                if len(argx) > 1:
×
995
                    unknown_args[i] = '='.join(
×
996
                        (argx[0], realpath(expanduser(argx[1]))))
997
                elif i + 1 < len(unknown_args):
×
998
                    unknown_args[i+1] = realpath(expanduser(unknown_args[i+1]))
×
999

1000
    @staticmethod
6 ✔
1001
    def _prepare_release_env(args):
6 ✔
1002
        """
1003
        prepares envitonment dict with the necessary flags for signing an apk
1004
        :param args: parser args
1005
        """
1006
        env = os.environ.copy()
×
1007
        if args.build_mode == 'release':
×
1008
            if args.keystore:
×
1009
                env['P4A_RELEASE_KEYSTORE'] = realpath(expanduser(args.keystore))
×
1010
            if args.signkey:
×
1011
                env['P4A_RELEASE_KEYALIAS'] = args.signkey
×
1012
            if args.keystorepw:
×
1013
                env['P4A_RELEASE_KEYSTORE_PASSWD'] = args.keystorepw
×
1014
            if args.signkeypw:
×
1015
                env['P4A_RELEASE_KEYALIAS_PASSWD'] = args.signkeypw
×
1016
            elif args.keystorepw and 'P4A_RELEASE_KEYALIAS_PASSWD' not in env:
×
1017
                env['P4A_RELEASE_KEYALIAS_PASSWD'] = args.keystorepw
×
1018

1019
        return env
×
1020

1021
    def _build_package(self, args, package_type):
6 ✔
1022
        """
1023
        Creates an android package using gradle
1024
        :param args: parser args
1025
        :param package_type: one of 'apk', 'aar', 'aab'
1026
        :return (gradle output, build_args)
1027
        """
1028
        ctx = self.ctx
×
1029
        dist = self._dist
×
1030
        bs = Bootstrap.get_bootstrap(args.bootstrap, ctx)
×
1031
        ctx.prepare_bootstrap(bs)
×
1032
        self._fix_args(args)
×
1033
        env = self._prepare_release_env(args)
×
1034

1035
        with current_directory(dist.dist_dir):
×
1036
            self.hook("before_apk_build")
×
1037
            os.environ["ANDROID_API"] = str(self.ctx.android_api)
×
1038
            build = load_source('build', join(dist.dist_dir, 'build.py'))
×
1039
            build_args = build.parse_args_and_make_package(
×
1040
                args.unknown_args
1041
            )
1042

1043
            self.hook("after_apk_build")
×
1044
            self.hook("before_apk_assemble")
×
1045
            build_tools_versions = os.listdir(join(ctx.sdk_dir,
×
1046
                                                   'build-tools'))
1047
            build_tools_version = max_build_tool_version(build_tools_versions)
×
1048
            info(('Detected highest available build tools '
×
1049
                  'version to be {}').format(build_tools_version))
1050

1051
            if Version(build_tools_version.replace(" ", "")) < Version('25.0'):
×
1052
                raise BuildInterruptingException(
×
1053
                    'build_tools >= 25 is required, but %s is installed' % build_tools_version)
1054
            if not exists("gradlew"):
×
1055
                raise BuildInterruptingException("gradlew file is missing")
×
1056

1057
            env["ANDROID_NDK_HOME"] = self.ctx.ndk_dir
×
1058
            env["ANDROID_HOME"] = self.ctx.sdk_dir
×
1059

1060
            gradlew = sh.Command('./gradlew')
×
1061

1062
            if exists('/usr/bin/dos2unix'):
×
1063
                # .../dists/bdisttest_python3/gradlew
1064
                # .../build/bootstrap_builds/sdl2-python3/gradlew
1065
                # if docker on windows, gradle contains CRLF
1066
                output = shprint(
×
1067
                    sh.Command('dos2unix'), gradlew._path,
1068
                    _tail=20, _critical=True, _env=env
1069
                )
1070
            if args.build_mode == "debug":
×
1071
                if package_type == "aab":
×
1072
                    raise BuildInterruptingException(
×
1073
                        "aab is meant only for distribution and is not available in debug mode. "
1074
                        "Instead, you can use apk while building for debugging purposes."
1075
                    )
1076
                gradle_task = "assembleDebug"
×
1077
            elif args.build_mode == "release":
×
1078
                if package_type in ["apk", "aar"]:
×
1079
                    gradle_task = "assembleRelease"
×
1080
                elif package_type == "aab":
×
1081
                    gradle_task = "bundleRelease"
×
1082
            else:
1083
                raise BuildInterruptingException(
×
1084
                    "Unknown build mode {} for apk()".format(args.build_mode))
1085

1086
            # WARNING: We should make sure to clean the build directory before building.
1087
            # See PR: kivy/python-for-android#2705
1088
            output = shprint(gradlew, "clean", gradle_task, _tail=20,
×
1089
                             _critical=True, _env=env)
1090
        return output, build_args
×
1091

1092
    def _finish_package(self, args, output, build_args, package_type, output_dir):
6 ✔
1093
        """
1094
        Finishes the package after the gradle script run
1095
        :param args: the parser args
1096
        :param output: RunningCommand output
1097
        :param build_args: build args as returned by build.parse_args
1098
        :param package_type: one of 'apk', 'aar', 'aab'
1099
        :param output_dir: where to put the package file
1100
        """
1101

1102
        package_glob = "*-{}.%s" % package_type
×
1103
        package_add_version = True
×
1104

1105
        self.hook("after_apk_assemble")
×
1106

1107
        info_main('# Copying android package to current directory')
×
1108

1109
        package_re = re.compile(r'.*Package: (.*\.apk)$')
×
1110
        package_file = None
×
1111
        for line in reversed(output.splitlines()):
×
1112
            m = package_re.match(line)
×
1113
            if m:
×
1114
                package_file = m.groups()[0]
×
1115
                break
×
1116
        if not package_file:
×
1117
            info_main('# Android package filename not found in build output. Guessing...')
×
1118
            if args.build_mode == "release":
×
1119
                suffixes = ("release", "release-unsigned")
×
1120
            else:
1121
                suffixes = ("debug", )
×
1122
            for suffix in suffixes:
×
1123

1124
                package_files = glob.glob(join(output_dir, package_glob.format(suffix)))
×
1125
                if package_files:
×
1126
                    if len(package_files) > 1:
×
1127
                        info('More than one built APK found... guessing you '
×
1128
                             'just built {}'.format(package_files[-1]))
1129
                    package_file = package_files[-1]
×
1130
                    break
×
1131
            else:
1132
                raise BuildInterruptingException('Couldn\'t find the built APK')
×
1133

1134
        info_main('# Found android package file: {}'.format(package_file))
×
1135
        package_extension = f".{package_type}"
×
1136
        if package_add_version:
×
1137
            info('# Add version number to android package')
×
1138
            package_name = basename(package_file)[:-len(package_extension)]
×
1139
            package_file_dest = "{}-{}{}".format(
×
1140
                package_name, build_args.version, package_extension)
1141
            info('# Android package renamed to {}'.format(package_file_dest))
×
1142
            shprint(sh.cp, package_file, package_file_dest)
×
1143
        else:
1144
            shprint(sh.cp, package_file, './')
×
1145

1146
    @require_prebuilt_dist
6 ✔
1147
    def apk(self, args):
6 ✔
1148
        output, build_args = self._build_package(args, package_type='apk')
×
1149
        output_dir = join(self._dist.dist_dir, "build", "outputs", 'apk', args.build_mode)
×
1150
        self._finish_package(args, output, build_args, 'apk', output_dir)
×
1151

1152
    @require_prebuilt_dist
6 ✔
1153
    def aar(self, args):
6 ✔
1154
        output, build_args = self._build_package(args, package_type='aar')
×
1155
        output_dir = join(self._dist.dist_dir, "build", "outputs", 'aar')
×
1156
        self._finish_package(args, output, build_args, 'aar', output_dir)
×
1157

1158
    @require_prebuilt_dist
6 ✔
1159
    def aab(self, args):
6 ✔
1160
        output, build_args = self._build_package(args, package_type='aab')
×
1161
        output_dir = join(self._dist.dist_dir, "build", "outputs", 'bundle', args.build_mode)
×
1162
        self._finish_package(args, output, build_args, 'aab', output_dir)
×
1163

1164
    @require_prebuilt_dist
6 ✔
1165
    def create(self, args):
6 ✔
1166
        """Create a distribution directory if it doesn't already exist, run
1167
        any recipes if necessary, and build the apk.
1168
        """
1169
        pass  # The decorator does everything
6 ✔
1170

1171
    def archs(self, _args):
6 ✔
1172
        """List the target architectures available to be built for."""
1173
        print('{Style.BRIGHT}Available target architectures are:'
×
1174
              '{Style.RESET_ALL}'.format(Style=Out_Style))
1175
        for arch in self.ctx.archs:
×
1176
            print('    {}'.format(arch.arch))
×
1177

1178
    def dists(self, args):
6 ✔
1179
        """The same as :meth:`distributions`."""
1180
        self.distributions(args)
×
1181

1182
    def distributions(self, _args):
6 ✔
1183
        """Lists all distributions currently available (i.e. that have already
1184
        been built)."""
1185
        ctx = self.ctx
×
1186
        dists = Distribution.get_distributions(ctx)
×
1187

1188
        if dists:
×
1189
            print('{Style.BRIGHT}Distributions currently installed are:'
×
1190
                  '{Style.RESET_ALL}'.format(Style=Out_Style))
1191
            pretty_log_dists(dists, print)
×
1192
        else:
1193
            print('{Style.BRIGHT}There are no dists currently built.'
×
1194
                  '{Style.RESET_ALL}'.format(Style=Out_Style))
1195

1196
    def delete_dist(self, _args):
6 ✔
1197
        dist = self._dist
×
1198
        if not dist.folder_exists():
×
1199
            info('No dist exists that matches your specifications, '
×
1200
                 'exiting without deleting.')
1201
            return
×
1202
        dist.delete()
×
1203

1204
    def sdk_tools(self, args):
6 ✔
1205
        """Runs the android binary from the detected SDK directory, passing
1206
        all arguments straight to it. This binary is used to install
1207
        e.g. platform-tools for different API level targets. This is
1208
        intended as a convenience function if android is not in your
1209
        $PATH.
1210
        """
1211
        ctx = self.ctx
×
1212
        ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir,
×
1213
                                      user_ndk_dir=self.ndk_dir,
1214
                                      user_android_api=self.android_api,
1215
                                      user_ndk_api=self.ndk_api)
1216
        android = sh.Command(join(ctx.sdk_dir, 'tools', args.tool))
×
1217
        output = android(
×
1218
            *args.unknown_args, _iter=True, _out_bufsize=1, _err_to_out=True)
1219
        for line in output:
×
1220
            sys.stdout.write(line)
×
1221
            sys.stdout.flush()
×
1222

1223
    def adb(self, args):
6 ✔
1224
        """Runs the adb binary from the detected SDK directory, passing all
1225
        arguments straight to it. This is intended as a convenience
1226
        function if adb is not in your $PATH.
1227
        """
1228
        self._adb(args.unknown_args)
×
1229

1230
    def logcat(self, args):
6 ✔
1231
        """Runs ``adb logcat`` using the adb binary from the detected SDK
1232
        directory. All extra args are passed as arguments to logcat."""
1233
        self._adb(['logcat'] + args.unknown_args)
×
1234

1235
    def _adb(self, commands):
6 ✔
1236
        """Call the adb executable from the SDK, passing the given commands as
1237
        arguments."""
1238
        ctx = self.ctx
×
1239
        ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir,
×
1240
                                      user_ndk_dir=self.ndk_dir,
1241
                                      user_android_api=self.android_api,
1242
                                      user_ndk_api=self.ndk_api)
1243
        if platform in ('win32', 'cygwin'):
×
1244
            adb = sh.Command(join(ctx.sdk_dir, 'platform-tools', 'adb.exe'))
×
1245
        else:
1246
            adb = sh.Command(join(ctx.sdk_dir, 'platform-tools', 'adb'))
×
1247
        info_notify('Starting adb...')
×
1248
        output = adb(*commands, _iter=True, _out_bufsize=1, _err_to_out=True)
×
1249
        for line in output:
×
1250
            sys.stdout.write(line)
×
1251
            sys.stdout.flush()
×
1252

1253
    def recommendations(self, args):
6 ✔
1254
        print_recommendations()
6 ✔
1255

1256
    def build_status(self, _args):
6 ✔
1257
        """Print the status of the specified build. """
1258
        print('{Style.BRIGHT}Bootstraps whose core components are probably '
×
1259
              'already built:{Style.RESET_ALL}'.format(Style=Out_Style))
1260

1261
        bootstrap_dir = join(self.ctx.build_dir, 'bootstrap_builds')
×
1262
        if exists(bootstrap_dir):
×
1263
            for filen in os.listdir(bootstrap_dir):
×
1264
                print('    {Fore.GREEN}{Style.BRIGHT}{filen}{Style.RESET_ALL}'
×
1265
                      .format(filen=filen, Fore=Out_Fore, Style=Out_Style))
1266

1267
        print('{Style.BRIGHT}Recipes that are probably already built:'
×
1268
              '{Style.RESET_ALL}'.format(Style=Out_Style))
1269
        other_builds_dir = join(self.ctx.build_dir, 'other_builds')
×
1270
        if exists(other_builds_dir):
×
1271
            for filen in sorted(os.listdir(other_builds_dir)):
×
1272
                name = filen.split('-')[0]
×
1273
                dependencies = filen.split('-')[1:]
×
1274
                recipe_str = ('    {Style.BRIGHT}{Fore.GREEN}{name}'
×
1275
                              '{Style.RESET_ALL}'.format(
1276
                                  Style=Out_Style, name=name, Fore=Out_Fore))
1277
                if dependencies:
×
1278
                    recipe_str += (
×
1279
                        ' ({Fore.BLUE}with ' + ', '.join(dependencies) +
1280
                        '{Fore.RESET})').format(Fore=Out_Fore)
1281
                recipe_str += '{Style.RESET_ALL}'.format(Style=Out_Style)
×
1282
                print(recipe_str)
×
1283

1284

1285
if __name__ == "__main__":
1286
    main()
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