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/.
5 from __future__
import print_function
, unicode_literals
14 if sys
.version_info
[0] < 3:
15 import __builtin__
as builtins
19 from types
import ModuleType
22 STATE_DIR_FIRST_RUN
= '''
23 mach and the build system store shared state in a common directory on the
24 filesystem. The following directory will be created:
28 If you would like to use a different directory, hit CTRL+c and set the
29 MOZBUILD_STATE_PATH environment variable to the directory you would like to
30 use and re-run mach. For this change to take effect forever, you'll likely
31 want to export this environment variable from your shell's init scripts.
33 Press ENTER/RETURN to continue or CTRL+c to abort.
37 # Individual files providing mach commands.
39 'build/valgrind/mach_commands.py',
40 'devtools/shared/css/generated/mach_commands.py',
41 'dom/bindings/mach_commands.py',
42 'js/src/devtools/rootAnalysis/mach_commands.py',
43 'layout/tools/reftest/mach_commands.py',
44 'mobile/android/mach_commands.py',
45 'python/mach/mach/commands/commandinfo.py',
46 'python/mach/mach/commands/settings.py',
47 'python/mach_commands.py',
48 'python/mozboot/mozboot/mach_commands.py',
49 'python/mozbuild/mozbuild/artifact_commands.py',
50 'python/mozbuild/mozbuild/backend/mach_commands.py',
51 'python/mozbuild/mozbuild/build_commands.py',
52 'python/mozbuild/mozbuild/code-analysis/mach_commands.py',
53 'python/mozbuild/mozbuild/compilation/codecomplete.py',
54 'python/mozbuild/mozbuild/frontend/mach_commands.py',
55 'python/mozbuild/mozbuild/mach_commands.py',
56 'python/mozrelease/mozrelease/mach_commands.py',
57 'python/safety/mach_commands.py',
58 'remote/mach_commands.py',
59 'taskcluster/mach_commands.py',
60 'testing/awsy/mach_commands.py',
61 'testing/condprofile/mach_commands.py',
62 'testing/firefox-ui/mach_commands.py',
63 'testing/geckodriver/mach_commands.py',
64 'testing/mach_commands.py',
65 'testing/marionette/mach_commands.py',
66 'testing/mochitest/mach_commands.py',
67 'testing/mozharness/mach_commands.py',
68 'testing/raptor/mach_commands.py',
69 'testing/talos/mach_commands.py',
70 'testing/tps/mach_commands.py',
71 'testing/web-platform/mach_commands.py',
72 'testing/xpcshell/mach_commands.py',
73 'toolkit/components/telemetry/tests/marionette/mach_commands.py',
74 'tools/browsertime/mach_commands.py',
75 'tools/compare-locales/mach_commands.py',
76 'tools/lint/mach_commands.py',
77 'tools/mach_commands.py',
78 'tools/moztreedocs/mach_commands.py',
79 'tools/phabricator/mach_commands.py',
80 'tools/power/mach_commands.py',
81 'tools/tryselect/mach_commands.py',
82 'tools/vcs/mach_commands.py',
88 'short': 'Build Commands',
89 'long': 'Interact with the build system',
93 'short': 'Post-build Commands',
94 'long': 'Common actions performed after completing a build.',
104 'long': 'Taskcluster commands',
108 'short': 'Development Environment',
109 'long': 'Set up and configure your development environment.',
113 'short': 'Low-level Build System Interaction',
114 'long': 'Interact with specific parts of the build system.',
118 'short': 'Potpourri',
119 'long': 'Potent potables and assorted snacks.',
123 'short': 'Release automation',
124 'long': 'Commands for used in release automation.',
129 'long': 'The disabled commands are hidden by default. Use -v to display them. '
130 'These commands are unavailable for your current context, '
131 'run "mach <command>" to see why.',
137 def search_path(mozilla_dir
, packages_txt
):
138 with
open(os
.path
.join(mozilla_dir
, packages_txt
)) as f
:
139 packages
= [line
.rstrip().split(':') for line
in f
]
141 def handle_package(package
):
142 if package
[0] == 'optional':
144 for path
in handle_package(package
[1:]):
149 if package
[0] in ('windows', '!windows'):
150 for_win
= not package
[0].startswith('!')
151 is_win
= sys
.platform
== 'win32'
152 if is_win
== for_win
:
153 for path
in handle_package(package
[1:]):
156 if package
[0] in ('python2', 'python3'):
157 for_python3
= package
[0].endswith('3')
158 is_python3
= sys
.version_info
[0] > 2
159 if is_python3
== for_python3
:
160 for path
in handle_package(package
[1:]):
163 if package
[0] == 'packages.txt':
164 assert len(package
) == 2
165 for p
in search_path(mozilla_dir
, package
[1]):
166 yield os
.path
.join(mozilla_dir
, p
)
168 if package
[0].endswith('.pth'):
169 assert len(package
) == 2
170 yield os
.path
.join(mozilla_dir
, package
[1])
172 for package
in packages
:
173 for path
in handle_package(package
):
177 def bootstrap(topsrcdir
, mozilla_dir
=None):
178 if mozilla_dir
is None:
179 mozilla_dir
= topsrcdir
181 # Ensure we are running Python 2.7 or 3.5+. We put this check here so we
182 # generate a user-friendly error message rather than a cryptic stack trace
184 major
, minor
= sys
.version_info
[:2]
185 if (major
== 2 and minor
< 7) or (major
== 3 and minor
< 5):
186 print('Python 2.7 or Python 3.5+ is required to run mach.')
187 print('You are running Python', platform
.python_version())
190 # Global build system and mach state is stored in a central directory. By
191 # default, this is ~/.mozbuild. However, it can be defined via an
192 # environment variable. We detect first run (by lack of this directory
193 # existing) and notify the user that it will be created. The logic for
194 # creation is much simpler for the "advanced" environment variable use
195 # case. For default behavior, we educate users and give them an opportunity
196 # to react. We always exit after creating the directory because users don't
198 sys
.path
[0:0] = [os
.path
.join(mozilla_dir
, path
)
199 for path
in search_path(mozilla_dir
,
200 'build/virtualenv_packages.txt')]
203 from mach
.util
import setenv
204 from mozboot
.util
import get_state_dir
206 from mozbuild
.util
import patch_main
209 def resolve_repository():
210 import mozversioncontrol
213 # This API doesn't respect the vcs binary choices from configure.
214 # If we ever need to use the VCS binary here, consider something
216 return mozversioncontrol
.get_repository_object(path
=mozilla_dir
)
217 except (mozversioncontrol
.InvalidRepoPath
,
218 mozversioncontrol
.MissingVCSTool
):
221 def pre_dispatch_handler(context
, handler
, args
):
222 # If --disable-tests flag was enabled in the mozconfig used to compile
223 # the build, tests will be disabled. Instead of trying to run
224 # nonexistent tests then reporting a failure, this will prevent mach
225 # from progressing beyond this point.
226 if handler
.category
== 'testing':
227 from mozbuild
.base
import BuildEnvironmentNotFoundException
229 from mozbuild
.base
import MozbuildObject
230 # all environments should have an instance of build object.
231 build
= MozbuildObject
.from_environment()
232 if build
is not None and hasattr(build
, 'mozconfig'):
233 ac_options
= build
.mozconfig
['configure_args']
234 if ac_options
and '--disable-tests' in ac_options
:
235 print('Tests have been disabled by mozconfig with the flag ' +
236 '"ac_add_options --disable-tests".\n' +
237 'Remove the flag, and re-compile to enable tests.')
239 except BuildEnvironmentNotFoundException
:
240 # likely automation environment, so do nothing.
243 def should_skip_telemetry_submission(handler
):
244 # The user is performing a maintenance command.
245 if handler
.name
in ('bootstrap', 'doctor', 'mach-commands', 'vcs-setup',
246 # We call mach environment in client.mk which would cause the
247 # data submission to block the forward progress of make.
251 # Never submit data when running in automation or when running tests.
252 if any(e
in os
.environ
for e
in ('MOZ_AUTOMATION', 'TASK_ID', 'MACH_TELEMETRY_NO_SUBMIT')):
257 def post_dispatch_handler(context
, handler
, instance
, result
,
258 start_time
, end_time
, depth
, args
):
259 """Perform global operations after command dispatch.
262 For now, we will use this to handle build system telemetry.
264 # Don't write telemetry data if this mach command was invoked as part of another
266 if depth
!= 1 or os
.environ
.get('MACH_MAIN_PID') != str(os
.getpid()):
269 # Don't write telemetry data for 'mach' when 'DISABLE_TELEMETRY' is set.
270 if os
.environ
.get('DISABLE_TELEMETRY') == '1':
273 # We have not opted-in to telemetry
274 if not context
.settings
.build
.telemetry
:
277 from mozbuild
.telemetry
import gather_telemetry
278 from mozbuild
.base
import MozbuildObject
279 import mozpack
.path
as mozpath
281 if not isinstance(instance
, MozbuildObject
):
282 instance
= MozbuildObject
.from_environment()
285 substs
= instance
.substs
289 command_attrs
= getattr(context
, 'command_attrs', {})
291 # We gather telemetry for every operation.
293 instance
.topsrcdir
: '$topsrcdir/',
294 instance
.topobjdir
: '$topobjdir/',
295 mozpath
.normpath(os
.path
.expanduser('~')): '$HOME/',
297 # This might override one of the existing entries, that's OK.
298 # We don't use a sigil here because we treat all arguments as potentially relative
299 # paths, so we'd like to get them back as they were specified.
300 paths
[mozpath
.normpath(os
.getcwd())] = ''
301 data
= gather_telemetry(command
=handler
.name
, success
=(result
== 0),
302 start_time
=start_time
, end_time
=end_time
,
303 mach_context
=context
, substs
=substs
,
304 command_attrs
=command_attrs
, paths
=paths
)
306 telemetry_dir
= os
.path
.join(get_state_dir(), 'telemetry')
308 os
.mkdir(telemetry_dir
)
310 if e
.errno
!= errno
.EEXIST
:
312 outgoing_dir
= os
.path
.join(telemetry_dir
, 'outgoing')
314 os
.mkdir(outgoing_dir
)
316 if e
.errno
!= errno
.EEXIST
:
319 with
open(os
.path
.join(outgoing_dir
, str(uuid
.uuid4()) + '.json'),
321 json
.dump(data
, f
, sort_keys
=True)
323 if should_skip_telemetry_submission(handler
):
326 state_dir
= get_state_dir()
328 machpath
= os
.path
.join(instance
.topsrcdir
, 'mach')
329 with
open(os
.devnull
, 'wb') as devnull
:
330 subprocess
.Popen([sys
.executable
, machpath
, 'python',
332 os
.path
.join(topsrcdir
, 'build',
333 'submit_telemetry_data.py'),
335 stdout
=devnull
, stderr
=devnull
)
337 def populate_context(context
, key
=None):
340 if key
== 'state_dir':
341 state_dir
= get_state_dir()
342 if state_dir
== os
.environ
.get('MOZBUILD_STATE_PATH'):
343 if not os
.path
.exists(state_dir
):
344 print('Creating global state directory from environment variable: %s'
346 os
.makedirs(state_dir
, mode
=0o770)
348 if not os
.path
.exists(state_dir
):
349 if not os
.environ
.get('MOZ_AUTOMATION'):
350 print(STATE_DIR_FIRST_RUN
.format(userdir
=state_dir
))
353 except KeyboardInterrupt:
356 print('\nCreating default state directory: %s' % state_dir
)
357 os
.makedirs(state_dir
, mode
=0o770)
361 if key
== 'local_state_dir':
362 return get_state_dir(srcdir
=True)
367 if key
== 'pre_dispatch_handler':
368 return pre_dispatch_handler
370 if key
== 'post_dispatch_handler':
371 return post_dispatch_handler
373 if key
== 'repository':
374 return resolve_repository()
376 raise AttributeError(key
)
378 # Note which process is top-level so that recursive mach invocations can avoid writing
380 if 'MACH_MAIN_PID' not in os
.environ
:
381 setenv('MACH_MAIN_PID', str(os
.getpid()))
383 driver
= mach
.main
.Mach(os
.getcwd())
384 driver
.populate_context_handler
= populate_context
386 if not driver
.settings_paths
:
387 # default global machrc location
388 driver
.settings_paths
.append(get_state_dir())
389 # always load local repository configuration
390 driver
.settings_paths
.append(mozilla_dir
)
392 for category
, meta
in CATEGORIES
.items():
393 driver
.define_category(category
, meta
['short'], meta
['long'],
396 repo
= resolve_repository()
398 for path
in MACH_MODULES
:
399 # Sparse checkouts may not have all mach_commands.py files. Ignore
400 # errors from missing files.
402 driver
.load_commands_from_file(os
.path
.join(mozilla_dir
, path
))
403 except mach
.base
.MissingFileError
:
404 if not repo
or not repo
.sparse_checkout_present():
410 # Hook import such that .pyc/.pyo files without a corresponding .py file in
411 # the source directory are essentially ignored. See further below for details
413 # Objdirs outside the source directory are ignored because in most cases, if
414 # a .pyc/.pyo file exists there, a .py file will be next to it anyways.
415 class ImportHook(object):
416 def __init__(self
, original_import
):
417 self
._original
_import
= original_import
418 # Assume the source directory is the parent directory of the one
419 # containing this file.
420 self
._source
_dir
= os
.path
.normcase(os
.path
.abspath(
421 os
.path
.dirname(os
.path
.dirname(__file__
)))) + os
.sep
422 self
._modules
= set()
424 def __call__(self
, name
, globals=None, locals=None, fromlist
=None,
426 if sys
.version_info
[0] >= 3 and level
< 0:
429 # name might be a relative import. Instead of figuring out what that
430 # resolves to, which is complex, just rely on the real import.
431 # Since we don't know the full module name, we can't check sys.modules,
432 # so we need to keep track of which modules we've already seen to avoid
433 # to stat() them again when they are imported multiple times.
434 module
= self
._original
_import
(name
, globals, locals, fromlist
, level
)
436 # Some tests replace modules in sys.modules with non-module instances.
437 if not isinstance(module
, ModuleType
):
440 resolved_name
= module
.__name
__
441 if resolved_name
in self
._modules
:
443 self
._modules
.add(resolved_name
)
445 # Builtin modules don't have a __file__ attribute.
446 if not getattr(module
, '__file__', None):
449 # Note: module.__file__ is not always absolute.
450 path
= os
.path
.normcase(os
.path
.abspath(module
.__file
__))
451 # Note: we could avoid normcase and abspath above for non pyc/pyo
452 # files, but those are actually rare, so it doesn't really matter.
453 if not path
.endswith(('.pyc', '.pyo')):
456 # Ignore modules outside our source directory
457 if not path
.startswith(self
._source
_dir
):
460 # If there is no .py corresponding to the .pyc/.pyo module we're
461 # loading, remove the .pyc/.pyo file, and reload the module.
462 # Since we already loaded the .pyc/.pyo module, if it had side
463 # effects, they will have happened already, and loading the module
464 # with the same name, from another directory may have the same side
465 # effects (or different ones). We assume it's not a problem for the
466 # python modules under our source directory (either because it
467 # doesn't happen or because it doesn't matter).
468 if not os
.path
.exists(module
.__file
__[:-1]):
469 if os
.path
.exists(module
.__file
__):
470 os
.remove(module
.__file
__)
471 del sys
.modules
[module
.__name
__]
472 module
= self(name
, globals, locals, fromlist
, level
)
478 builtins
.__import
__ = ImportHook(builtins
.__import
__)