-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
mach_commands.py
2669 lines (2346 loc) · 81 KB
/
mach_commands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, # You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import, print_function, unicode_literals
import argparse
import itertools
import json
import logging
import operator
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import errno
import mozbuild.settings # noqa need @SettingsProvider hook to execute
import mozpack.path as mozpath
from pathlib import Path
from mach.decorators import (
CommandArgument,
CommandArgumentGroup,
Command,
SettingsProvider,
SubCommand,
)
from mozbuild.base import (
BinaryNotFoundException,
BuildEnvironmentNotFoundException,
MachCommandConditions as conditions,
MozbuildObject,
)
here = os.path.abspath(os.path.dirname(__file__))
EXCESSIVE_SWAP_MESSAGE = """
===================
PERFORMANCE WARNING
Your machine experienced a lot of swap activity during the build. This is
possibly a sign that your machine doesn't have enough physical memory or
not enough available memory to perform the build. It's also possible some
other system activity during the build is to blame.
If you feel this message is not appropriate for your machine configuration,
please file a Firefox Build System :: General bug at
https://bugzilla.mozilla.org/enter_bug.cgi?product=Firefox%20Build%20System&component=General
and tell us about your machine and build configuration so we can adjust the
warning heuristic.
===================
"""
class StoreDebugParamsAndWarnAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
sys.stderr.write(
"The --debugparams argument is deprecated. Please "
+ "use --debugger-args instead.\n\n"
)
setattr(namespace, self.dest, values)
@Command(
"watch",
category="post-build",
description="Watch and re-build (parts of) the tree.",
conditions=[conditions.is_firefox],
virtualenv_name="watch",
)
@CommandArgument(
"-v",
"--verbose",
action="store_true",
help="Verbose output for what commands the watcher is running.",
)
def watch(command_context, verbose=False):
"""Watch and re-build (parts of) the source tree."""
if not conditions.is_artifact_build(command_context):
print(
"WARNING: mach watch only rebuilds the `mach build faster` parts of the tree!"
)
if not command_context.substs.get("WATCHMAN", None):
print(
"mach watch requires watchman to be installed and found at configure time. See "
"https://developer.mozilla.org/docs/Mozilla/Developer_guide/Build_Instructions/Incremental_builds_with_filesystem_watching" # noqa
)
return 1
from mozbuild.faster_daemon import Daemon
daemon = Daemon(command_context.config_environment)
try:
return daemon.watch()
except KeyboardInterrupt:
# Suppress ugly stack trace when user hits Ctrl-C.
sys.exit(3)
@Command("cargo", category="build", description="Invoke cargo in useful ways.")
def cargo(command_context):
"""Invoke cargo in useful ways."""
command_context._sub_mach(["help", "cargo"])
return 1
@SubCommand(
"cargo",
"check",
description="Run `cargo check` on a given crate. Defaults to gkrust.",
)
@CommandArgument(
"--all-crates",
default=None,
action="store_true",
help="Check all of the crates in the tree.",
)
@CommandArgument("crates", default=None, nargs="*", help="The crate name(s) to check.")
@CommandArgument(
"--jobs",
"-j",
default="1",
nargs="?",
metavar="jobs",
type=int,
help="Run the tests in parallel using multiple processes.",
)
@CommandArgument("-v", "--verbose", action="store_true", help="Verbose output.")
@CommandArgument(
"--message-format-json",
action="store_true",
help="Emit error messages as JSON.",
)
def check(
command_context,
all_crates=None,
crates=None,
jobs=0,
verbose=False,
message_format_json=False,
):
# XXX duplication with `mach vendor rust`
crates_and_roots = {
"gkrust": "toolkit/library/rust",
"gkrust-gtest": "toolkit/library/gtest/rust",
"geckodriver": "testing/geckodriver",
}
if all_crates:
crates = crates_and_roots.keys()
elif crates is None or crates == []:
crates = ["gkrust"]
for crate in crates:
root = crates_and_roots.get(crate, None)
if not root:
print(
"Cannot locate crate %s. Please check your spelling or "
"add the crate information to the list." % crate
)
return 1
check_targets = [
"force-cargo-library-check",
"force-cargo-host-library-check",
"force-cargo-program-check",
"force-cargo-host-program-check",
]
append_env = {}
if message_format_json:
append_env["USE_CARGO_JSON_MESSAGE_FORMAT"] = "1"
ret = command_context._run_make(
srcdir=False,
directory=root,
ensure_exit_code=0,
silent=not verbose,
print_directory=False,
target=check_targets,
num_jobs=jobs,
append_env=append_env,
)
if ret != 0:
return ret
return 0
@SubCommand(
"cargo",
"vet",
description="Run `cargo vet`.",
)
@CommandArgument("arguments", nargs=argparse.REMAINDER)
def cargo_vet(command_context, arguments, stdout=None, env=os.environ):
from mozbuild.bootstrap import bootstrap_toolchain
# Logging of commands enables logging from `bootstrap_toolchain` that we
# don't want to expose. Disable them temporarily.
logger = logging.getLogger("gecko_taskgraph.generator")
level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
env = env.copy()
cargo_vet = bootstrap_toolchain("cargo-vet")
if cargo_vet:
env["PATH"] = os.pathsep.join([cargo_vet, env["PATH"]])
logger.setLevel(level)
try:
cargo = command_context.substs["CARGO"]
except (BuildEnvironmentNotFoundException, KeyError):
# Default if this tree isn't configured.
from mozfile import which
cargo = which("cargo", path=env["PATH"])
if not cargo:
raise OSError(
errno.ENOENT,
(
"Could not find 'cargo' on your $PATH. "
"Hint: have you run `mach build` or `mach configure`?"
),
)
locked = "--locked" in arguments
if locked:
# The use of --locked requires .cargo/config to exist, but other things,
# like cargo update, don't want it there, so remove it once we're done.
topsrcdir = Path(command_context.topsrcdir)
shutil.copyfile(
topsrcdir / ".cargo" / "config.in", topsrcdir / ".cargo" / "config"
)
try:
res = subprocess.run(
[cargo, "vet"] + arguments,
cwd=command_context.topsrcdir,
stdout=stdout,
env=env,
)
finally:
if locked:
(topsrcdir / ".cargo" / "config").unlink()
# When the function is invoked without stdout set (the default when running
# as a mach subcommand), exit with the returncode from cargo vet.
# When the function is invoked with stdout (direct function call), return
# the full result from subprocess.run.
return res if stdout else res.returncode
@Command(
"doctor",
category="devenv",
description="Diagnose and fix common development environment issues.",
)
@CommandArgument(
"--fix",
default=False,
action="store_true",
help="Attempt to fix found problems.",
)
@CommandArgument(
"--verbose",
default=False,
action="store_true",
help="Print verbose information found by checks.",
)
def doctor(command_context, fix=False, verbose=False):
"""Diagnose common build environment problems"""
from mozbuild.doctor import run_doctor
return run_doctor(
topsrcdir=command_context.topsrcdir,
topobjdir=command_context.topobjdir,
configure_args=command_context.mozconfig["configure_args"],
fix=fix,
verbose=verbose,
)
CLOBBER_CHOICES = {"objdir", "python", "gradle"}
@Command(
"clobber",
category="build",
description="Clobber the tree (delete the object directory).",
no_auto_log=True,
)
@CommandArgument(
"what",
default=["objdir", "python"],
nargs="*",
help="Target to clobber, must be one of {{{}}} (default "
"objdir and python).".format(", ".join(CLOBBER_CHOICES)),
)
@CommandArgument("--full", action="store_true", help="Perform a full clobber")
def clobber(command_context, what, full=False):
"""Clean up the source and object directories.
Performing builds and running various commands generate various files.
Sometimes it is necessary to clean up these files in order to make
things work again. This command can be used to perform that cleanup.
The `objdir` target removes most files in the current object directory
(where build output is stored). Some files (like Visual Studio project
files) are not removed by default. If you would like to remove the
object directory in its entirety, run with `--full`.
The `python` target will clean up Python's generated files (virtualenvs,
".pyc", "__pycache__", etc).
The `gradle` target will remove the "gradle" subdirectory of the object
directory.
By default, the command clobbers the `objdir` and `python` targets.
"""
what = set(what)
invalid = what - CLOBBER_CHOICES
if invalid:
print(
"Unknown clobber target(s): {}. Choose from {{{}}}".format(
", ".join(invalid), ", ".join(CLOBBER_CHOICES)
)
)
return 1
ret = 0
if "objdir" in what:
from mozbuild.controller.clobber import Clobberer
try:
substs = command_context.substs
except BuildEnvironmentNotFoundException:
substs = {}
try:
Clobberer(
command_context.topsrcdir, command_context.topobjdir, substs
).remove_objdir(full)
except OSError as e:
if sys.platform.startswith("win"):
if isinstance(e, WindowsError) and e.winerror in (5, 32):
command_context.log(
logging.ERROR,
"file_access_error",
{"error": e},
"Could not clobber because a file was in use. If the "
"application is running, try closing it. {error}",
)
return 1
raise
if "python" in what:
if conditions.is_hg(command_context):
cmd = [
"hg",
"--config",
"extensions.purge=",
"purge",
"--all",
"-I",
"glob:**.py[cdo]",
"-I",
"glob:**/__pycache__",
]
elif conditions.is_git(command_context):
cmd = ["git", "clean", "-d", "-f", "-x", "*.py[cdo]", "*/__pycache__/*"]
else:
cmd = ["find", ".", "-type", "f", "-name", "*.py[cdo]", "-delete"]
subprocess.call(cmd, cwd=command_context.topsrcdir)
cmd = [
"find",
".",
"-type",
"d",
"-name",
"__pycache__",
"-empty",
"-delete",
]
ret = subprocess.call(cmd, cwd=command_context.topsrcdir)
shutil.rmtree(
mozpath.join(command_context.topobjdir, "_virtualenvs"),
ignore_errors=True,
)
if "gradle" in what:
shutil.rmtree(
mozpath.join(command_context.topobjdir, "gradle"), ignore_errors=True
)
return ret
@Command(
"show-log", category="post-build", description="Display mach logs", no_auto_log=True
)
@CommandArgument(
"log_file",
nargs="?",
type=argparse.FileType("rb"),
help="Filename to read log data from. Defaults to the log of the last "
"mach command.",
)
def show_log(command_context, log_file=None):
"""Show mach logs
If we're in a terminal context, the log is piped to 'less'
for more convenient viewing.
(https://man7.org/linux/man-pages/man1/less.1.html)
"""
if not log_file:
path = command_context._get_state_filename("last_log.json")
log_file = open(path, "rb")
if os.isatty(sys.stdout.fileno()):
env = dict(os.environ)
if "LESS" not in env:
# Sensible default flags if none have been set in the user environment.
env["LESS"] = "FRX"
less = subprocess.Popen(
["less"], stdin=subprocess.PIPE, env=env, encoding="UTF-8"
)
try:
# Create a new logger handler with the stream being the stdin of our 'less'
# process so that we can pipe the logger output into 'less'
less_handler = logging.StreamHandler(stream=less.stdin)
less_handler.setFormatter(
command_context.log_manager.terminal_handler.formatter
)
less_handler.setLevel(command_context.log_manager.terminal_handler.level)
# replace the existing terminal handler with the new one for 'less' while
# still keeping the original one to set back later
original_handler = command_context.log_manager.replace_terminal_handler(
less_handler
)
# Save this value so we can set it back to the original value later
original_logging_raise_exceptions = logging.raiseExceptions
# We need to explicitly disable raising exceptions inside logging so
# that we can catch them here ourselves to ignore the ones we want
logging.raiseExceptions = False
# Parses the log file line by line and streams
# (to less.stdin) the relevant records we want
handle_log_file(command_context, log_file)
# At this point we've piped the entire log file to
# 'less', so we can close the input stream
less.stdin.close()
# Wait for the user to manually terminate `less`
less.wait()
except OSError as os_error:
# (POSIX) errno.EPIPE: BrokenPipeError: [Errno 32] Broken pipe
# (Windows) errno.EINVAL: OSError: [Errno 22] Invalid argument
if os_error.errno == errno.EPIPE or os_error.errno == errno.EINVAL:
# If the user manually terminates 'less' before the entire log file
# is piped (without scrolling close enough to the bottom) we will get
# one of these errors (depends on the OS) because the logger will still
# attempt to stream to the now invalid less.stdin. To prevent a bunch
# of errors being shown after a user terminates 'less', we just catch
# the first of those exceptions here, and stop parsing the log file.
pass
else:
raise
except Exception:
raise
finally:
# Ensure these values are changed back to the originals, regardless of outcome
command_context.log_manager.replace_terminal_handler(original_handler)
logging.raiseExceptions = original_logging_raise_exceptions
else:
# Not in a terminal context, so just handle the log file with the
# default stream without piping it to a pager (less)
handle_log_file(command_context, log_file)
def handle_log_file(command_context, log_file):
start_time = 0
for line in log_file:
created, action, params = json.loads(line)
if not start_time:
start_time = created
command_context.log_manager.terminal_handler.formatter.start_time = created
if "line" in params:
record = logging.makeLogRecord(
{
"created": created,
"name": command_context._logger.name,
"levelno": logging.INFO,
"msg": "{line}",
"params": params,
"action": action,
}
)
command_context._logger.handle(record)
# Provide commands for inspecting warnings.
def database_path(command_context):
return command_context._get_state_filename("warnings.json")
def get_warnings_database(command_context):
from mozbuild.compilation.warnings import WarningsDatabase
path = database_path(command_context)
database = WarningsDatabase()
if os.path.exists(path):
database.load_from_file(path)
return database
@Command(
"warnings-summary",
category="post-build",
description="Show a summary of compiler warnings.",
)
@CommandArgument(
"-C",
"--directory",
default=None,
help="Change to a subdirectory of the build directory first.",
)
@CommandArgument(
"report",
default=None,
nargs="?",
help="Warnings report to display. If not defined, show the most recent report.",
)
def summary(command_context, directory=None, report=None):
database = get_warnings_database(command_context)
if directory:
dirpath = join_ensure_dir(command_context.topsrcdir, directory)
if not dirpath:
return 1
else:
dirpath = None
type_counts = database.type_counts(dirpath)
sorted_counts = sorted(type_counts.items(), key=operator.itemgetter(1))
total = 0
for k, v in sorted_counts:
print("%d\t%s" % (v, k))
total += v
print("%d\tTotal" % total)
@Command(
"warnings-list",
category="post-build",
description="Show a list of compiler warnings.",
)
@CommandArgument(
"-C",
"--directory",
default=None,
help="Change to a subdirectory of the build directory first.",
)
@CommandArgument(
"--flags", default=None, nargs="+", help="Which warnings flags to match."
)
@CommandArgument(
"report",
default=None,
nargs="?",
help="Warnings report to display. If not defined, show the most recent report.",
)
def list_warnings(command_context, directory=None, flags=None, report=None):
database = get_warnings_database(command_context)
by_name = sorted(database.warnings)
topsrcdir = mozpath.normpath(command_context.topsrcdir)
if directory:
directory = mozpath.normsep(directory)
dirpath = join_ensure_dir(topsrcdir, directory)
if not dirpath:
return 1
if flags:
# Flatten lists of flags.
flags = set(itertools.chain(*[flaglist.split(",") for flaglist in flags]))
for warning in by_name:
filename = mozpath.normsep(warning["filename"])
if filename.startswith(topsrcdir):
filename = filename[len(topsrcdir) + 1 :]
if directory and not filename.startswith(directory):
continue
if flags and warning["flag"] not in flags:
continue
if warning["column"] is not None:
print(
"%s:%d:%d [%s] %s"
% (
filename,
warning["line"],
warning["column"],
warning["flag"],
warning["message"],
)
)
else:
print(
"%s:%d [%s] %s"
% (filename, warning["line"], warning["flag"], warning["message"])
)
def join_ensure_dir(dir1, dir2):
dir1 = mozpath.normpath(dir1)
dir2 = mozpath.normsep(dir2)
joined_path = mozpath.join(dir1, dir2)
if os.path.isdir(joined_path):
return joined_path
print("Specified directory not found.")
return None
@Command("gtest", category="testing", description="Run GTest unit tests (C++ tests).")
@CommandArgument(
"gtest_filter",
default="*",
nargs="?",
metavar="gtest_filter",
help="test_filter is a ':'-separated list of wildcard patterns "
"(called the positive patterns), optionally followed by a '-' "
"and another ':'-separated pattern list (called the negative patterns)."
"Test names are of the format SUITE.NAME. Use --list-tests to see all.",
)
@CommandArgument("--list-tests", action="store_true", help="list all available tests")
@CommandArgument(
"--jobs",
"-j",
default="1",
nargs="?",
metavar="jobs",
type=int,
help="Run the tests in parallel using multiple processes.",
)
@CommandArgument(
"--tbpl-parser",
"-t",
action="store_true",
help="Output test results in a format that can be parsed by TBPL.",
)
@CommandArgument(
"--shuffle",
"-s",
action="store_true",
help="Randomize the execution order of tests.",
)
@CommandArgument(
"--enable-webrender",
action="store_true",
default=False,
dest="enable_webrender",
help="Enable the WebRender compositor in Gecko.",
)
@CommandArgumentGroup("Android")
@CommandArgument(
"--package",
default="org.mozilla.geckoview.test_runner",
group="Android",
help="Package name of test app.",
)
@CommandArgument(
"--adbpath", dest="adb_path", group="Android", help="Path to adb binary."
)
@CommandArgument(
"--deviceSerial",
dest="device_serial",
group="Android",
help="adb serial number of remote device. "
"Required when more than one device is connected to the host. "
"Use 'adb devices' to see connected devices.",
)
@CommandArgument(
"--remoteTestRoot",
dest="remote_test_root",
group="Android",
help="Remote directory to use as test root (eg. /data/local/tmp/test_root).",
)
@CommandArgument(
"--libxul", dest="libxul_path", group="Android", help="Path to gtest libxul.so."
)
@CommandArgument(
"--no-install",
action="store_true",
default=False,
group="Android",
help="Skip the installation of the APK.",
)
@CommandArgumentGroup("debugging")
@CommandArgument(
"--debug",
action="store_true",
group="debugging",
help="Enable the debugger. Not specifying a --debugger option will result in "
"the default debugger being used.",
)
@CommandArgument(
"--debugger",
default=None,
type=str,
group="debugging",
help="Name of debugger to use.",
)
@CommandArgument(
"--debugger-args",
default=None,
metavar="params",
type=str,
group="debugging",
help="Command-line arguments to pass to the debugger itself; "
"split as the Bourne shell would.",
)
def gtest(
command_context,
shuffle,
jobs,
gtest_filter,
list_tests,
tbpl_parser,
enable_webrender,
package,
adb_path,
device_serial,
remote_test_root,
libxul_path,
no_install,
debug,
debugger,
debugger_args,
):
# We lazy build gtest because it's slow to link
try:
command_context.config_environment
except Exception:
print("Please run |./mach build| before |./mach gtest|.")
return 1
res = command_context._mach_context.commands.dispatch(
"build", command_context._mach_context, what=["recurse_gtest"]
)
if res:
print("Could not build xul-gtest")
return res
if command_context.substs.get("MOZ_WIDGET_TOOLKIT") == "cocoa":
command_context._run_make(
directory="browser/app", target="repackage", ensure_exit_code=True
)
cwd = os.path.join(command_context.topobjdir, "_tests", "gtest")
if not os.path.isdir(cwd):
os.makedirs(cwd)
if conditions.is_android(command_context):
if jobs != 1:
print("--jobs is not supported on Android and will be ignored")
if debug or debugger or debugger_args:
print("--debug options are not supported on Android and will be ignored")
from mozrunner.devices.android_device import InstallIntent
return android_gtest(
command_context,
cwd,
shuffle,
gtest_filter,
package,
adb_path,
device_serial,
remote_test_root,
libxul_path,
InstallIntent.NO if no_install else InstallIntent.YES,
)
if (
package
or adb_path
or device_serial
or remote_test_root
or libxul_path
or no_install
):
print("One or more Android-only options will be ignored")
app_path = command_context.get_binary_path("app")
args = [app_path, "-unittest", "--gtest_death_test_style=threadsafe"]
if (
sys.platform.startswith("win")
and "MOZ_LAUNCHER_PROCESS" in command_context.defines
):
args.append("--wait-for-browser")
if list_tests:
args.append("--gtest_list_tests")
if debug or debugger or debugger_args:
args = _prepend_debugger_args(args, debugger, debugger_args)
if not args:
return 1
# Use GTest environment variable to control test execution
# For details see:
# https://google.github.io/googletest/advanced.html#running-test-programs-advanced-options
gtest_env = {"GTEST_FILTER": gtest_filter}
# Note: we must normalize the path here so that gtest on Windows sees
# a MOZ_GMP_PATH which has only Windows dir seperators, because
# nsIFile cannot open the paths with non-Windows dir seperators.
xre_path = os.path.join(os.path.normpath(command_context.topobjdir), "dist", "bin")
gtest_env["MOZ_XRE_DIR"] = xre_path
gtest_env["MOZ_GMP_PATH"] = os.pathsep.join(
os.path.join(xre_path, p, "1.0") for p in ("gmp-fake", "gmp-fakeopenh264")
)
gtest_env["MOZ_RUN_GTEST"] = "True"
if shuffle:
gtest_env["GTEST_SHUFFLE"] = "True"
if tbpl_parser:
gtest_env["MOZ_TBPL_PARSER"] = "True"
if enable_webrender:
gtest_env["MOZ_WEBRENDER"] = "1"
gtest_env["MOZ_ACCELERATED"] = "1"
else:
gtest_env["MOZ_WEBRENDER"] = "0"
if jobs == 1:
return command_context.run_process(
args=args,
append_env=gtest_env,
cwd=cwd,
ensure_exit_code=False,
pass_thru=True,
)
from mozprocess import ProcessHandlerMixin
import functools
def handle_line(job_id, line):
# Prepend the jobId
line = "[%d] %s" % (job_id + 1, line.strip())
command_context.log(logging.INFO, "GTest", {"line": line}, "{line}")
gtest_env["GTEST_TOTAL_SHARDS"] = str(jobs)
processes = {}
for i in range(0, jobs):
gtest_env["GTEST_SHARD_INDEX"] = str(i)
processes[i] = ProcessHandlerMixin(
[app_path, "-unittest"],
cwd=cwd,
env=gtest_env,
processOutputLine=[functools.partial(handle_line, i)],
universal_newlines=True,
)
processes[i].run()
exit_code = 0
for process in processes.values():
status = process.wait()
if status:
exit_code = status
# Clamp error code to 255 to prevent overflowing multiple of
# 256 into 0
if exit_code > 255:
exit_code = 255
return exit_code
def android_gtest(
command_context,
test_dir,
shuffle,
gtest_filter,
package,
adb_path,
device_serial,
remote_test_root,
libxul_path,
install,
):
# setup logging for mozrunner
from mozlog.commandline import setup_logging
format_args = {"level": command_context._mach_context.settings["test"]["level"]}
default_format = command_context._mach_context.settings["test"]["format"]
setup_logging("mach-gtest", {}, {default_format: sys.stdout}, format_args)
# ensure that a device is available and test app is installed
from mozrunner.devices.android_device import verify_android_device, get_adb_path
verify_android_device(
command_context, install=install, app=package, device_serial=device_serial
)
if not adb_path:
adb_path = get_adb_path(command_context)
if not libxul_path:
libxul_path = os.path.join(
command_context.topobjdir, "dist", "bin", "gtest", "libxul.so"
)
# run gtest via remotegtests.py
exit_code = 0
import imp
path = os.path.join("testing", "gtest", "remotegtests.py")
with open(path, "r") as fh:
imp.load_module("remotegtests", fh, path, (".py", "r", imp.PY_SOURCE))
import remotegtests
tester = remotegtests.RemoteGTests()
if not tester.run_gtest(
test_dir,
shuffle,
gtest_filter,
package,
adb_path,
device_serial,
remote_test_root,
libxul_path,
None,
):
exit_code = 1
tester.cleanup()
return exit_code
@Command(
"package",
category="post-build",
description="Package the built product for distribution as an APK, DMG, etc.",
)
@CommandArgument(
"-v",
"--verbose",
action="store_true",
help="Verbose output for what commands the packaging process is running.",
)
def package(command_context, verbose=False):
"""Package the built product for distribution."""
ret = command_context._run_make(
directory=".", target="package", silent=not verbose, ensure_exit_code=False
)
if ret == 0:
command_context.notify("Packaging complete")
return ret
def _get_android_install_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--app",
default="org.mozilla.geckoview_example",
help="Android package to install (default: org.mozilla.geckoview_example)",
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",