# 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__importprint_function,unicode_literalsimporterrnoimportjsonimportosimportplatformimportsubprocessimportsysimportuuidifsys.version_info[0]<3:import__builtin__asbuiltinselse:importbuiltinsfromtypesimportModuleTypeSTATE_DIR_FIRST_RUN='''mach and the build system store shared state in a common directory on thefilesystem. The following directory will be created: {userdir}If you would like to use a different directory, hit CTRL+c and set theMOZBUILD_STATE_PATH environment variable to the directory you would like touse and re-run mach. For this change to take effect forever, you'll likelywant to export this environment variable from your shell's init scripts.Press ENTER/RETURN to continue or CTRL+c to abort.'''.lstrip()# Individual files providing mach commands.MACH_MODULES=['build/valgrind/mach_commands.py','devtools/shared/css/generated/mach_commands.py','dom/bindings/mach_commands.py','layout/tools/reftest/mach_commands.py','mobile/android/mach_commands.py','python/mach/mach/commands/commandinfo.py','python/mach/mach/commands/settings.py','python/mach_commands.py','python/mozboot/mozboot/mach_commands.py','python/mozbuild/mozbuild/artifact_commands.py','python/mozbuild/mozbuild/backend/mach_commands.py','python/mozbuild/mozbuild/build_commands.py','python/mozbuild/mozbuild/code-analysis/mach_commands.py','python/mozbuild/mozbuild/compilation/codecomplete.py','python/mozbuild/mozbuild/frontend/mach_commands.py','python/mozbuild/mozbuild/mach_commands.py','python/mozrelease/mozrelease/mach_commands.py','python/safety/mach_commands.py','remote/mach_commands.py','taskcluster/mach_commands.py','testing/awsy/mach_commands.py','testing/firefox-ui/mach_commands.py','testing/geckodriver/mach_commands.py','testing/mach_commands.py','testing/marionette/mach_commands.py','testing/mochitest/mach_commands.py','testing/mozharness/mach_commands.py','testing/raptor/mach_commands.py','testing/talos/mach_commands.py','testing/tps/mach_commands.py','testing/web-platform/mach_commands.py','testing/xpcshell/mach_commands.py','toolkit/components/telemetry/tests/marionette/mach_commands.py','tools/browsertime/mach_commands.py','tools/compare-locales/mach_commands.py','tools/docs/mach_commands.py','tools/lint/mach_commands.py','tools/mach_commands.py','tools/power/mach_commands.py','tools/tryselect/mach_commands.py','tools/vcs/mach_commands.py',]CATEGORIES={'build':{'short':'Build Commands','long':'Interact with the build system','priority':80,},'post-build':{'short':'Post-build Commands','long':'Common actions performed after completing a build.','priority':70,},'testing':{'short':'Testing','long':'Run tests.','priority':60,},'ci':{'short':'CI','long':'Taskcluster commands','priority':59,},'devenv':{'short':'Development Environment','long':'Set up and configure your development environment.','priority':50,},'build-dev':{'short':'Low-level Build System Interaction','long':'Interact with specific parts of the build system.','priority':20,},'misc':{'short':'Potpourri','long':'Potent potables and assorted snacks.','priority':10,},'release':{'short':'Release automation','long':'Commands for used in release automation.','priority':5,},'disabled':{'short':'Disabled','long':'The disabled commands are hidden by default. Use -v to display them. ''These commands are unavailable for your current context, ''run "mach <command>" to see why.','priority':0,},}defsearch_path(mozilla_dir,packages_txt):withopen(os.path.join(mozilla_dir,packages_txt))asf:packages=[line.rstrip().split(':')forlineinf]defhandle_package(package):ifpackage[0]=='optional':try:forpathinhandle_package(package[1:]):yieldpathexceptException:passifpackage[0]in('windows','!windows'):for_win=notpackage[0].startswith('!')is_win=sys.platform=='win32'ifis_win==for_win:forpathinhandle_package(package[1:]):yieldpathifpackage[0]in('python2','python3'):for_python3=package[0].endswith('3')is_python3=sys.version_info[0]>2ifis_python3==for_python3:forpathinhandle_package(package[1:]):yieldpathifpackage[0]=='packages.txt':assertlen(package)==2forpinsearch_path(mozilla_dir,package[1]):yieldos.path.join(mozilla_dir,p)ifpackage[0].endswith('.pth'):assertlen(package)==2yieldos.path.join(mozilla_dir,package[1])forpackageinpackages:forpathinhandle_package(package):yieldpathdefbootstrap(topsrcdir,mozilla_dir=None):ifmozilla_dirisNone:mozilla_dir=topsrcdir# Ensure we are running Python 2.7 or 3.5+. We put this check here so we# generate a user-friendly error message rather than a cryptic stack trace# on module import.major,minor=sys.version_info[:2]if(major==2andminor<7)or(major==3andminor<5):print('Python 2.7 or Python 3.5+ is required to run mach.')print('You are running Python',platform.python_version())sys.exit(1)# Global build system and mach state is stored in a central directory. By# default, this is ~/.mozbuild. However, it can be defined via an# environment variable. We detect first run (by lack of this directory# existing) and notify the user that it will be created. The logic for# creation is much simpler for the "advanced" environment variable use# case. For default behavior, we educate users and give them an opportunity# to react. We always exit after creating the directory because users don't# like surprises.sys.path[0:0]=[os.path.join(mozilla_dir,path)forpathinsearch_path(mozilla_dir,'build/virtualenv_packages.txt')]importmach.baseimportmach.mainfrommach.utilimportsetenvfrommozboot.utilimportget_state_dirfrommozbuild.utilimportpatch_mainpatch_main()defresolve_repository():importmozversioncontroltry:# This API doesn't respect the vcs binary choices from configure.# If we ever need to use the VCS binary here, consider something# more robust.returnmozversioncontrol.get_repository_object(path=mozilla_dir)except(mozversioncontrol.InvalidRepoPath,mozversioncontrol.MissingVCSTool):returnNonedefshould_skip_telemetry_submission(handler):# The user is performing a maintenance command.ifhandler.namein('bootstrap','doctor','mach-commands','vcs-setup',# We call mach environment in client.mk which would cause the# data submission to block the forward progress of make.'environment'):returnTrue# Never submit data when running in automation or when running tests.ifany(einos.environforein('MOZ_AUTOMATION','TASK_ID','MACH_TELEMETRY_NO_SUBMIT')):returnTruereturnFalsedefpost_dispatch_handler(context,handler,instance,result,start_time,end_time,depth,args):"""Perform global operations after command dispatch. For now, we will use this to handle build system telemetry. """# Don't write telemetry data if this mach command was invoked as part of another# mach command.ifdepth!=1oros.environ.get('MACH_MAIN_PID')!=str(os.getpid()):return# Don't write telemetry data for 'mach' when 'DISABLE_TELEMETRY' is set.ifos.environ.get('DISABLE_TELEMETRY')=='1':return# We have not opted-in to telemetryifnotcontext.settings.build.telemetry:returnfrommozbuild.telemetryimportgather_telemetryfrommozbuild.baseimportMozbuildObjectimportmozpack.pathasmozpathifnotisinstance(instance,MozbuildObject):instance=MozbuildObject.from_environment()try:substs=instance.substsexceptException:substs={}command_attrs=getattr(context,'command_attrs',{})# We gather telemetry for every operation.paths={instance.topsrcdir:'$topsrcdir/',instance.topobjdir:'$topobjdir/',mozpath.normpath(os.path.expanduser('~')):'$HOME/',}# This might override one of the existing entries, that's OK.# We don't use a sigil here because we treat all arguments as potentially relative# paths, so we'd like to get them back as they were specified.paths[mozpath.normpath(os.getcwd())]=''data=gather_telemetry(command=handler.name,success=(result==0),start_time=start_time,end_time=end_time,mach_context=context,substs=substs,command_attrs=command_attrs,paths=paths)ifdata:telemetry_dir=os.path.join(get_state_dir(),'telemetry')try:os.mkdir(telemetry_dir)exceptOSErrorase:ife.errno!=errno.EEXIST:raiseoutgoing_dir=os.path.join(telemetry_dir,'outgoing')try:os.mkdir(outgoing_dir)exceptOSErrorase:ife.errno!=errno.EEXIST:raisewithopen(os.path.join(outgoing_dir,str(uuid.uuid4())+'.json'),'w')asf:json.dump(data,f,sort_keys=True)ifshould_skip_telemetry_submission(handler):returnTruestate_dir=get_state_dir()machpath=os.path.join(instance.topsrcdir,'mach')withopen(os.devnull,'wb')asdevnull:subprocess.Popen([sys.executable,machpath,'python','--no-virtualenv',os.path.join(topsrcdir,'build','submit_telemetry_data.py'),state_dir],stdout=devnull,stderr=devnull)defpopulate_context(context,key=None):ifkeyisNone:returnifkey=='state_dir':state_dir=get_state_dir()ifstate_dir==os.environ.get('MOZBUILD_STATE_PATH'):ifnotos.path.exists(state_dir):print('Creating global state directory from environment variable: %s'%state_dir)os.makedirs(state_dir,mode=0o770)else:ifnotos.path.exists(state_dir):ifnotos.environ.get('MOZ_AUTOMATION'):print(STATE_DIR_FIRST_RUN.format(userdir=state_dir))try:sys.stdin.readline()exceptKeyboardInterrupt:sys.exit(1)print('\nCreating default state directory: %s'%state_dir)os.makedirs(state_dir,mode=0o770)returnstate_dirifkey=='local_state_dir':returnget_state_dir(srcdir=True)ifkey=='topdir':returntopsrcdirifkey=='post_dispatch_handler':returnpost_dispatch_handlerifkey=='repository':returnresolve_repository()raiseAttributeError(key)# Note which process is top-level so that recursive mach invocations can avoid writing# telemetry data.if'MACH_MAIN_PID'notinos.environ:setenv('MACH_MAIN_PID',str(os.getpid()))driver=mach.main.Mach(os.getcwd())driver.populate_context_handler=populate_contextifnotdriver.settings_paths:# default global machrc locationdriver.settings_paths.append(get_state_dir())# always load local repository configurationdriver.settings_paths.append(mozilla_dir)forcategory,metainCATEGORIES.items():driver.define_category(category,meta['short'],meta['long'],meta['priority'])repo=resolve_repository()forpathinMACH_MODULES:# Sparse checkouts may not have all mach_commands.py files. Ignore# errors from missing files.try:driver.load_commands_from_file(os.path.join(mozilla_dir,path))exceptmach.base.MissingFileError:ifnotrepoornotrepo.sparse_checkout_present():raisereturndriver# Hook import such that .pyc/.pyo files without a corresponding .py file in# the source directory are essentially ignored. See further below for details# and caveats.# Objdirs outside the source directory are ignored because in most cases, if# a .pyc/.pyo file exists there, a .py file will be next to it anyways.classImportHook(object):def__init__(self,original_import):self._original_import=original_import# Assume the source directory is the parent directory of the one# containing this file.self._source_dir=os.path.normcase(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))+os.sepself._modules=set()def__call__(self,name,globals=None,locals=None,fromlist=None,level=-1):ifsys.version_info[0]>=3andlevel<0:level=0# name might be a relative import. Instead of figuring out what that# resolves to, which is complex, just rely on the real import.# Since we don't know the full module name, we can't check sys.modules,# so we need to keep track of which modules we've already seen to avoid# to stat() them again when they are imported multiple times.module=self._original_import(name,globals,locals,fromlist,level)# Some tests replace modules in sys.modules with non-module instances.ifnotisinstance(module,ModuleType):returnmoduleresolved_name=module.__name__ifresolved_nameinself._modules:returnmoduleself._modules.add(resolved_name)# Builtin modules don't have a __file__ attribute.ifnothasattr(module,'__file__'):returnmodule# Note: module.__file__ is not always absolute.path=os.path.normcase(os.path.abspath(module.__file__))# Note: we could avoid normcase and abspath above for non pyc/pyo# files, but those are actually rare, so it doesn't really matter.ifnotpath.endswith(('.pyc','.pyo')):returnmodule# Ignore modules outside our source directoryifnotpath.startswith(self._source_dir):returnmodule# If there is no .py corresponding to the .pyc/.pyo module we're# loading, remove the .pyc/.pyo file, and reload the module.# Since we already loaded the .pyc/.pyo module, if it had side# effects, they will have happened already, and loading the module# with the same name, from another directory may have the same side# effects (or different ones). We assume it's not a problem for the# python modules under our source directory (either because it# doesn't happen or because it doesn't matter).ifnotos.path.exists(module.__file__[:-1]):ifos.path.exists(module.__file__):os.remove(module.__file__)delsys.modules[module.__name__]module=self(name,globals,locals,fromlist,level)returnmodule# Install our hookbuiltins.__import__=ImportHook(builtins.__import__)