Source code

Revision control

Other Tools

1
# This Source Code Form is subject to the terms of the Mozilla Public
2
# License, v. 2.0. If a copy of the MPL was not distributed with this
3
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
from __future__ import absolute_import, print_function, unicode_literals
6
7
import argparse
8
import logging
9
import os
10
11
import mozpack.path as mozpath
12
13
from mozbuild.base import (
14
MachCommandBase,
15
MachCommandConditions as conditions,
16
)
17
18
from mozbuild.shellutil import (
19
split as shell_split,
20
)
21
22
from mach.decorators import (
23
CommandArgument,
24
CommandProvider,
25
Command,
26
SubCommand,
27
)
28
29
30
# Mach's conditions facility doesn't support subcommands. Print a
31
# deprecation message ourselves instead.
32
LINT_DEPRECATION_MESSAGE = """
33
Android lints are now integrated with mozlint. Instead of
34
`mach android {api-lint,checkstyle,lint,test}`, run
35
`mach lint --linter android-{api-lint,checkstyle,lint,test}`.
36
Or run `mach lint`.
37
"""
38
39
40
# NOTE python/mach/mach/commands/commandinfo.py references this function
41
# by name. If this function is renamed or removed, that file should
42
# be updated accordingly as well.
43
def REMOVED(cls):
44
"""Command no longer exists! Use the Gradle configuration rooted in the top source directory
45
instead.
46
48
"""
49
return False
50
51
52
@CommandProvider
53
class MachCommands(MachCommandBase):
54
@Command('android', category='devenv',
55
description='Run Android-specific commands.',
56
conditions=[conditions.is_android])
57
def android(self):
58
pass
59
60
@SubCommand('android', 'assemble-app',
61
"""Assemble Firefox for Android.
63
@CommandArgument('args', nargs=argparse.REMAINDER)
64
def android_assemble_app(self, args):
65
ret = self.gradle(self.substs['GRADLE_ANDROID_APP_TASKS'] +
66
['-x', 'lint'] + args, verbose=True)
67
68
return ret
69
70
@SubCommand('android', 'generate-sdk-bindings',
71
"""Generate SDK bindings used when building GeckoView.""")
72
@CommandArgument('inputs', nargs='+', help='config files, '
73
'like [/path/to/ClassName-classes.txt]+')
74
@CommandArgument('args', nargs=argparse.REMAINDER)
75
def android_generate_sdk_bindings(self, inputs, args):
76
import itertools
77
78
def stem(input):
79
# Turn "/path/to/ClassName-classes.txt" into "ClassName".
80
return os.path.basename(input).rsplit('-classes.txt', 1)[0]
81
82
bindings_inputs = list(itertools.chain(*((input, stem(input)) for input in inputs)))
83
bindings_args = '-Pgenerate_sdk_bindings_args={}'.format(';'.join(bindings_inputs))
84
85
ret = self.gradle(
86
self.substs['GRADLE_ANDROID_GENERATE_SDK_BINDINGS_TASKS'] + [bindings_args] + args,
87
verbose=True)
88
89
return ret
90
91
@SubCommand('android', 'generate-generated-jni-wrappers',
92
"""Generate GeckoView JNI wrappers used when building GeckoView.""")
93
@CommandArgument('args', nargs=argparse.REMAINDER)
94
def android_generate_generated_jni_wrappers(self, args):
95
ret = self.gradle(
96
self.substs['GRADLE_ANDROID_GENERATE_GENERATED_JNI_WRAPPERS_TASKS'] + args,
97
verbose=True)
98
99
return ret
100
101
@SubCommand('android', 'generate-fennec-jni-wrappers',
102
"""Generate Fennec-specific JNI wrappers used when building
103
Firefox for Android.""")
104
@CommandArgument('args', nargs=argparse.REMAINDER)
105
def android_generate_fennec_jni_wrappers(self, args):
106
ret = self.gradle(
107
self.substs['GRADLE_ANDROID_GENERATE_FENNEC_JNI_WRAPPERS_TASKS'] + args, verbose=True)
108
109
return ret
110
111
@SubCommand('android', 'api-lint',
112
"""Run Android api-lint.
113
REMOVED/DEPRECATED: Use 'mach lint --linter android-api-lint'.""")
114
def android_apilint_REMOVED(self):
115
print(LINT_DEPRECATION_MESSAGE)
116
return 1
117
118
@SubCommand('android', 'test',
119
"""Run Android test.
120
REMOVED/DEPRECATED: Use 'mach lint --linter android-test'.""")
121
def android_test_REMOVED(self):
122
print(LINT_DEPRECATION_MESSAGE)
123
return 1
124
125
@SubCommand('android', 'lint',
126
"""Run Android lint.
127
REMOVED/DEPRECATED: Use 'mach lint --linter android-lint'.""")
128
def android_lint_REMOVED(self):
129
print(LINT_DEPRECATION_MESSAGE)
130
return 1
131
132
@SubCommand('android', 'checkstyle',
133
"""Run Android checkstyle.
134
REMOVED/DEPRECATED: Use 'mach lint --linter android-checkstyle'.""")
135
def android_checkstyle_REMOVED(self):
136
print(LINT_DEPRECATION_MESSAGE)
137
return 1
138
139
@SubCommand('android', 'gradle-dependencies',
140
"""Collect Android Gradle dependencies.
142
@CommandArgument('args', nargs=argparse.REMAINDER)
143
def android_gradle_dependencies(self, args):
144
# We don't want to gate producing dependency archives on clean
145
# lint or checkstyle, particularly because toolchain versions
146
# can change the outputs for those processes.
147
self.gradle(self.substs['GRADLE_ANDROID_DEPENDENCIES_TASKS'] +
148
["--continue"] + args, verbose=True)
149
150
return 0
151
152
@SubCommand('android', 'archive-geckoview',
153
"""Create GeckoView archives.
155
@CommandArgument('args', nargs=argparse.REMAINDER)
156
def android_archive_geckoview(self, args):
157
ret = self.gradle(
158
self.substs['GRADLE_ANDROID_ARCHIVE_GECKOVIEW_TASKS'] + args,
159
verbose=True)
160
161
return ret
162
163
@SubCommand('android', 'build-geckoview_example',
164
"""Build geckoview_example """)
165
@CommandArgument('args', nargs=argparse.REMAINDER)
166
def android_build_geckoview_example(self, args):
167
self.gradle(self.substs['GRADLE_ANDROID_BUILD_GECKOVIEW_EXAMPLE_TASKS'] + args,
168
verbose=True)
169
170
print('Execute `mach android install-geckoview_example` '
171
'to push the geckoview_example and test APKs to a device.')
172
173
return 0
174
175
@SubCommand('android', 'install-geckoview_example',
176
"""Install geckoview_example """)
177
@CommandArgument('args', nargs=argparse.REMAINDER)
178
def android_install_geckoview_example(self, args):
179
self.gradle(self.substs['GRADLE_ANDROID_INSTALL_GECKOVIEW_EXAMPLE_TASKS'] + args,
180
verbose=True)
181
182
print('Execute `mach android build-geckoview_example` '
183
'to just build the geckoview_example and test APKs.')
184
185
return 0
186
187
@SubCommand('android', 'geckoview-docs',
188
"""Create GeckoView javadoc and optionally upload to Github""")
189
@CommandArgument('--archive', action='store_true',
190
help='Generate a javadoc archive.')
191
@CommandArgument('--upload', metavar='USER/REPO',
192
help='Upload generated javadoc to Github, '
193
'using the specified USER/REPO.')
194
@CommandArgument('--upload-branch', metavar='BRANCH[/PATH]',
195
default='gh-pages/javadoc',
196
help='Use the specified branch/path for commits.')
197
@CommandArgument('--upload-message', metavar='MSG',
198
default='GeckoView docs upload',
199
help='Use the specified message for commits.')
200
def android_geckoview_docs(self, archive, upload, upload_branch,
201
upload_message):
202
203
tasks = (self.substs['GRADLE_ANDROID_GECKOVIEW_DOCS_ARCHIVE_TASKS'] if archive or upload
204
else self.substs['GRADLE_ANDROID_GECKOVIEW_DOCS_TASKS'])
205
206
ret = self.gradle(tasks, verbose=True)
207
if ret or not upload:
208
return ret
209
210
# Upload to Github.
211
fmt = {
212
'level': os.environ.get('MOZ_SCM_LEVEL', '0'),
213
'project': os.environ.get('MH_BRANCH', 'unknown'),
214
'revision': os.environ.get('GECKO_HEAD_REV', 'tip'),
215
}
216
env = {}
217
218
# In order to push to GitHub from TaskCluster, we store a private key
219
# in the TaskCluster secrets store in the format {"content": "<KEY>"},
220
# and the corresponding public key as a writable deploy key for the
221
# destination repo on GitHub.
222
secret = os.environ.get('GECKOVIEW_DOCS_UPLOAD_SECRET', '').format(**fmt)
223
if secret:
224
# Set up a private key from the secrets store if applicable.
225
import requests
226
req = requests.get('http://taskcluster/secrets/v1/secret/' + secret)
227
req.raise_for_status()
228
229
keyfile = mozpath.abspath('gv-docs-upload-key')
230
with open(keyfile, 'w') as f:
231
os.chmod(keyfile, 0o600)
232
f.write(req.json()['secret']['content'])
233
234
# Turn off strict host key checking so ssh does not complain about
235
# unknown github.com host. We're not pushing anything sensitive, so
236
# it's okay to not check GitHub's host keys.
237
env['GIT_SSH_COMMAND'] = 'ssh -i "%s" -o StrictHostKeyChecking=no' % keyfile
238
239
# Clone remote repo.
240
branch, _, branch_path = upload_branch.partition('/')
241
repo_url = 'git@github.com:%s.git' % upload
242
repo_path = mozpath.abspath('gv-docs-repo')
243
self.run_process(['git', 'clone', '--branch', branch, '--depth', '1',
244
repo_url, repo_path], append_env=env, pass_thru=True)
245
env['GIT_DIR'] = mozpath.join(repo_path, '.git')
246
env['GIT_WORK_TREE'] = repo_path
247
env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = 'GeckoView Docs Bot'
248
env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = 'nobody@mozilla.com'
249
250
# Extract new javadoc to specified directory inside repo.
251
import mozfile
252
src_tar = mozpath.join(self.topobjdir, 'gradle', 'build', 'mobile', 'android',
253
'geckoview', 'libs', 'geckoview-javadoc.jar')
254
dst_path = mozpath.join(repo_path, branch_path.format(**fmt))
255
mozfile.remove(dst_path)
256
mozfile.extract_zip(src_tar, dst_path)
257
258
# Commit and push.
259
self.run_process(['git', 'add', '--all'], append_env=env, pass_thru=True)
260
if self.run_process(['git', 'diff', '--cached', '--quiet'],
261
append_env=env, pass_thru=True, ensure_exit_code=False) != 0:
262
# We have something to commit.
263
self.run_process(['git', 'commit',
264
'--message', upload_message.format(**fmt)],
265
append_env=env, pass_thru=True)
266
self.run_process(['git', 'push', 'origin', 'gh-pages'],
267
append_env=env, pass_thru=True)
268
269
mozfile.remove(repo_path)
270
if secret:
271
mozfile.remove(keyfile)
272
return 0
273
274
@Command('gradle', category='devenv',
275
description='Run gradle.',
276
conditions=[conditions.is_android])
277
@CommandArgument('-v', '--verbose', action='store_true',
278
help='Verbose output for what commands the build is running.')
279
@CommandArgument('args', nargs=argparse.REMAINDER)
280
def gradle(self, args, verbose=False):
281
if not verbose:
282
# Avoid logging the command
283
self.log_manager.terminal_handler.setLevel(logging.CRITICAL)
284
285
# In automation, JAVA_HOME is set via mozconfig, which needs
286
# to be specially handled in each mach command. This turns
287
# $JAVA_HOME/bin/java into $JAVA_HOME.
288
java_home = os.path.dirname(os.path.dirname(self.substs['JAVA']))
289
290
gradle_flags = self.substs.get('GRADLE_FLAGS', '') or \
291
os.environ.get('GRADLE_FLAGS', '')
292
gradle_flags = shell_split(gradle_flags)
293
294
# We force the Gradle JVM to run with the UTF-8 encoding, since we
295
# filter strings.xml, which is really UTF-8; the ellipsis character is
296
# replaced with ??? in some encodings (including ASCII). It's not yet
297
# possible to filter with encodings in Gradle
298
# (https://github.com/gradle/gradle/pull/520) and it's challenging to
299
# do our filtering with Gradle's Ant support. Moreover, all of the
300
# Android tools expect UTF-8: see
302
# http://stackoverflow.com/a/21267635 for discussion of this approach.
303
#
304
# It's not even enough to set the encoding just for Gradle; it
305
# needs to be for JVMs spawned by Gradle as well. This
306
# happens during the maven deployment generating the GeckoView
307
# documents; this works around "error: unmappable character
308
# for encoding ASCII" in exoplayer2. See
310
# and especially https://stackoverflow.com/a/21755671.
311
312
if self.substs.get('MOZ_AUTOMATION'):
313
gradle_flags += ['--console=plain']
314
315
env = os.environ.copy()
316
env.update({
317
'GRADLE_OPTS': '-Dfile.encoding=utf-8',
318
'JAVA_HOME': java_home,
319
'JAVA_TOOL_OPTIONS': '-Dfile.encoding=utf-8',
320
})
321
# Set ANDROID_SDK_ROOT if --with-android-sdk was set.
323
android_sdk_root = self.substs.get('ANDROID_SDK_ROOT', '')
324
if android_sdk_root:
325
env['ANDROID_SDK_ROOT'] = android_sdk_root
326
327
return self.run_process(
328
[self.substs['GRADLE']] + gradle_flags + args,
329
explicit_env=env,
330
pass_thru=True, # Allow user to run gradle interactively.
331
ensure_exit_code=False, # Don't throw on non-zero exit code.
332
cwd=mozpath.join(self.topsrcdir))
333
334
@Command('gradle-install', category='devenv',
335
conditions=[REMOVED])
336
def gradle_install_REMOVED(self):
337
pass
338
339
340
@CommandProvider
341
class AndroidEmulatorCommands(MachCommandBase):
342
"""
343
Run the Android emulator with one of the AVDs used in the Mozilla
344
automated test environment. If necessary, the AVD is fetched from
345
the tooltool server and installed.
346
"""
347
@Command('android-emulator', category='devenv',
348
conditions=[],
349
description='Run the Android emulator with an AVD from test automation.')
350
@CommandArgument('--version', metavar='VERSION',
351
choices=['4.3', 'x86', 'x86-7.0'],
352
help='Specify Android version to run in emulator. '
353
'One of "4.3", "x86", or "x86-7.0".')
354
@CommandArgument('--wait', action='store_true',
355
help='Wait for emulator to be closed.')
356
@CommandArgument('--force-update', action='store_true',
357
help='Update AVD definition even when AVD is already installed.')
358
@CommandArgument('--verbose', action='store_true',
359
help='Log informative status messages.')
360
def emulator(self, version, wait=False, force_update=False, verbose=False):
361
from mozrunner.devices.android_device import AndroidEmulator
362
363
emulator = AndroidEmulator(version, verbose, substs=self.substs,
364
device_serial='emulator-5554')
365
if emulator.is_running():
366
# It is possible to run multiple emulators simultaneously, but:
367
# - if more than one emulator is using the same avd, errors may
368
# occur due to locked resources;
369
# - additional parameters must be specified when running tests,
370
# to select a specific device.
371
# To avoid these complications, allow just one emulator at a time.
372
self.log(logging.ERROR, "emulator", {},
373
"An Android emulator is already running.\n"
374
"Close the existing emulator and re-run this command.")
375
return 1
376
377
if not emulator.is_available():
378
self.log(logging.WARN, "emulator", {},
379
"Emulator binary not found.\n"
380
"Install the Android SDK and make sure 'emulator' is in your PATH.")
381
return 2
382
383
if not emulator.check_avd(force_update):
384
self.log(logging.INFO, "emulator", {},
385
"Fetching and installing AVD. This may take a few minutes...")
386
emulator.update_avd(force_update)
387
388
self.log(logging.INFO, "emulator", {},
389
"Starting Android emulator running %s..." %
390
emulator.get_avd_description())
391
emulator.start()
392
if emulator.wait_for_start():
393
self.log(logging.INFO, "emulator", {},
394
"Android emulator is running.")
395
else:
396
# This is unusual but the emulator may still function.
397
self.log(logging.WARN, "emulator", {},
398
"Unable to verify that emulator is running.")
399
400
if conditions.is_android(self):
401
self.log(logging.INFO, "emulator", {},
402
"Use 'mach install' to install or update Firefox on your emulator.")
403
else:
404
self.log(logging.WARN, "emulator", {},
405
"No Firefox for Android build detected.\n"
406
"Switch to a Firefox for Android build context or use 'mach bootstrap'\n"
407
"to setup an Android build environment.")
408
409
if wait:
410
self.log(logging.INFO, "emulator", {},
411
"Waiting for Android emulator to close...")
412
rc = emulator.wait()
413
if rc is not None:
414
self.log(logging.INFO, "emulator", {},
415
"Android emulator completed with return code %d." % rc)
416
else:
417
self.log(logging.WARN, "emulator", {},
418
"Unable to retrieve Android emulator return code.")
419
return 0