Debian Codegraph @

python/mozboot/bin/bootstrap.py

raw
1 #!/usr/bin/env python3
2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 # You can obtain one at http://mozilla.org/MPL/2.0/.
5
6 # This script provides one-line bootstrap support to configure systems to build
7 # the tree. It does so by cloning the repo before calling directly into `mach
8 # bootstrap`.
9
10 # Note that this script can't assume anything in particular about the host
11 # Python environment (except that it's run with a sufficiently recent version of
12 # Python 3), so we are restricted to stdlib modules.
13
14 import sys
15
16 major, minor = sys.version_info[:2]
17 if (major < 3) or (major == 3 and minor < 8):
18 print(
19 "Bootstrap currently only runs on Python 3.8+."
20 "Please try re-running with python3.8+."
21 )
22 sys.exit(1)
23
24 import ctypes
25 import os
26 import shutil
27 import subprocess
28 import tempfile
29 from optparse import OptionParser
30 from pathlib import Path
31
32 CLONE_MERCURIAL_PULL_FAIL = """
33 Failed to pull from hg.mozilla.org.
34
35 This is most likely because of unstable network connection.
36 Try running `cd %s && hg pull https://hg.mozilla.org/mozilla-unified` manually,
37 or download a mercurial bundle and use it:
38 https://firefox-source-docs.mozilla.org/contributing/vcs/mercurial_bundles.html"""
39
40 WINDOWS = sys.platform.startswith("win32") or sys.platform.startswith("msys")
41 VCS_HUMAN_READABLE = {
42 "hg": "Mercurial",
43 "git": "Git",
44 "git-cinnabar": "Git",
45 }
46 GIT_REPO = "https://github.com/mozilla-firefox/firefox"
47 HG_REPO = "https://hg.mozilla.org/mozilla-unified"
48
49
50 def which(name):
51 """Python implementation of which.
52
53 It returns the path of an executable or None if it couldn't be found.
54 """
55 search_dirs = os.environ["PATH"].split(os.pathsep)
56 potential_names = [name]
57 if WINDOWS:
58 potential_names.insert(0, name + ".exe")
59
60 for path in search_dirs:
61 for executable_name in potential_names:
62 test = Path(path) / executable_name
63 if test.is_file() and os.access(test, os.X_OK):
64 return test
65
66 return None
67
68
69 def validate_clone_dest(dest: Path):
70 dest = dest.resolve()
71
72 if not dest.exists():
73 return dest
74
75 if not dest.is_dir():
76 print(f"ERROR! Destination {dest} exists but is not a directory.")
77 return None
78
79 if not any(dest.iterdir()):
80 return dest
81 else:
82 print(f"ERROR! Destination directory {dest} exists but is nonempty.")
83 print(
84 f"To re-bootstrap the existing checkout, go into '{dest}' and run './mach bootstrap'."
85 )
86 return None
87
88
89 def input_clone_dest(vcs, no_interactive):
90 repo = GIT_REPO if vcs == "git" else HG_REPO
91 repo_name = repo.rpartition("/")[2]
92 print(f"Cloning into {repo_name} using {VCS_HUMAN_READABLE[vcs]}...")
93 while True:
94 dest = None
95 if not no_interactive:
96 dest = input(
97 f"Destination directory for clone (leave empty to use "
98 f"default destination of {repo_name}): "
99 ).strip()
100 if not dest:
101 dest = repo_name
102 dest = validate_clone_dest(Path(dest).expanduser())
103 if dest:
104 return dest
105 if no_interactive:
106 return None
107
108
109 def hg_clone_firefox(hg: Path, dest: Path, head_repo, head_rev):
110 # We create an empty repo then modify the config before adding data.
111 # This is necessary to ensure storage settings are optimally
112 # configured.
113 args = [
114 str(hg),
115 # The unified repo is generaldelta, so ensure the client is as
116 # well.
117 "--config",
118 "format.generaldelta=true",
119 "init",
120 str(dest),
121 ]
122 res = subprocess.call(args)
123 if res:
124 print("unable to create destination repo; please try cloning manually")
125 return None
126
127 # Strictly speaking, this could overwrite a config based on a template
128 # the user has installed. Let's pretend this problem doesn't exist
129 # unless someone complains about it.
130 with open(dest / ".hg" / "hgrc", "a") as fh:
131 fh.write("[paths]\n")
132 fh.write(f"default = {HG_REPO}\n")
133 fh.write("\n")
134
135 # The server uses aggressivemergedeltas which can blow up delta chain
136 # length. This can cause performance to tank due to delta chains being
137 # too long. Limit the delta chain length to something reasonable
138 # to bound revlog read time.
139 fh.write("[format]\n")
140 fh.write("# This is necessary to keep performance in check\n")
141 fh.write("maxchainlen = 10000\n")
142
143 # Pulling a specific revision into an empty repository induces a lot of
144 # load on the Mercurial server, so we always pull from mozilla-unified (which,
145 # when done from an empty repository, is equivalent to a clone), and then pull
146 # the specific revision we want (if we want a specific one, otherwise we just
147 # use the "central" bookmark), at which point it will be an incremental pull,
148 # that the server can process more easily.
149 # This is the same thing that robustcheckout does on automation.
150 res = subprocess.call([str(hg), "pull", HG_REPO], cwd=str(dest))
151 if not res and head_repo:
152 res = subprocess.call(
153 [str(hg), "pull", head_repo, "-r", head_rev], cwd=str(dest)
154 )
155 print("")
156 if res:
157 print(CLONE_MERCURIAL_PULL_FAIL % dest)
158 return None
159
160 head_rev = head_rev or "central"
161 print(f'updating to "{head_rev}" - the development head of Gecko and Firefox')
162 res = subprocess.call([str(hg), "update", "-r", head_rev], cwd=str(dest))
163 if res:
164 print(
165 f"error updating; you will need to `cd {dest} && hg update -r central` "
166 "manually"
167 )
168 return dest
169
170
171 def git_clone_firefox(git: Path, dest: Path, head_repo, head_rev):
172 if head_repo and "hg.mozilla.org" in head_repo:
173 print("GECKO_HEAD_REPOSITORY cannot be a Mercurial repository when using Git")
174 return None
175
176 subprocess.check_call(
177 [
178 str(git),
179 "clone",
180 "-n",
181 GIT_REPO,
182 str(dest),
183 ],
184 )
185 subprocess.check_call([str(git), "config", "pull.ff", "only"], cwd=str(dest))
186
187 if head_repo:
188 subprocess.check_call(
189 [str(git), "fetch", head_repo, head_rev],
190 cwd=str(dest),
191 )
192
193 subprocess.check_call(
194 [
195 str(git),
196 "checkout",
197 "FETCH_HEAD" if head_rev else "main",
198 "--",
199 ],
200 cwd=str(dest),
201 )
202
203 return dest
204
205
206 def git_cinnabar_clone_firefox(git: Path, dest: Path, head_repo, head_rev):
207 tempdir = None
208 cinnabar = None
209 env = dict(os.environ)
210 try:
211 cinnabar = which("git-cinnabar")
212 if not cinnabar:
213 from urllib.request import urlopen
214
215 cinnabar_url = "https://github.com/glandium/git-cinnabar/"
216 # If git-cinnabar isn't installed already, that's fine; we can
217 # download a temporary copy. `mach bootstrap` will install a copy
218 # in the state dir; we don't want to copy all that logic to this
219 # tiny bootstrapping script.
220 tempdir = Path(tempfile.mkdtemp())
221 with open(tempdir / "download.py", "wb") as fh:
222 shutil.copyfileobj(
223 urlopen(f"{cinnabar_url}/raw/master/download.py"), fh
224 )
225
226 subprocess.check_call(
227 [sys.executable, str(tempdir / "download.py")],
228 cwd=str(tempdir),
229 )
230 env["PATH"] = str(tempdir) + os.pathsep + env["PATH"]
231 print(
232 "WARNING! git-cinnabar is required for Firefox development "
233 "with git. After the clone is complete, the bootstrapper "
234 "will ask if you would like to configure git; answer yes, "
235 "and be sure to add git-cinnabar to your PATH according to "
236 "the bootstrapper output."
237 )
238
239 # We're guaranteed to have `git-cinnabar` installed now.
240 # Configure git per the git-cinnabar requirements.
241 subprocess.check_call(
242 [
243 str(git),
244 "-c",
245 "fetch.prune=true",
246 "-c",
247 f"cinnabar.graft={GIT_REPO}",
248 "-c",
249 "cinnabar.refs=bookmarks",
250 "-c",
251 "remote.origin.fetch=refs/heads/central:refs/remotes/origin/main",
252 "clone",
253 "--no-checkout",
254 f"hg::{HG_REPO}",
255 str(dest),
256 ],
257 env=env,
258 )
259 subprocess.check_call(
260 [str(git), "config", "fetch.prune", "true"], cwd=str(dest), env=env
261 )
262 subprocess.check_call(
263 [str(git), "config", "cinnabar.refs", "bookmarks"], cwd=str(dest), env=env
264 )
265 subprocess.check_call(
266 [
267 str(git),
268 "config",
269 "--add",
270 "remote.origin.fetch",
271 "refs/heads/central:refs/remotes/origin/main",
272 ],
273 cwd=str(dest),
274 env=env,
275 )
276 subprocess.check_call(
277 [str(git), "config", "pull.ff", "only"], cwd=str(dest), env=env
278 )
279
280 if head_repo:
281 subprocess.check_call(
282 [str(git), "cinnabar", "fetch", f"hg::{head_repo}", head_rev],
283 cwd=str(dest),
284 env=env,
285 )
286
287 subprocess.check_call(
288 [
289 str(git),
290 "checkout",
291 "FETCH_HEAD" if head_rev else "main",
292 "--",
293 ],
294 cwd=str(dest),
295 env=env,
296 )
297
298 return dest
299 finally:
300 if tempdir:
301 shutil.rmtree(str(tempdir))
302
303
304 def add_microsoft_defender_antivirus_exclusions(dest, no_system_changes):
305 if no_system_changes:
306 return
307
308 if not WINDOWS:
309 return
310
311 powershell_exe = which("powershell")
312
313 if not powershell_exe:
314 return
315
316 def print_attempt_exclusion(path):
317 print(
318 f"Attempting to add exclusion path to Microsoft Defender Antivirus for: {path}"
319 )
320
321 powershell_exe = str(powershell_exe)
322 paths = []
323
324 # mozilla-unified / clone dest
325 repo_dir = Path.cwd() / dest
326 paths.append(repo_dir)
327 print_attempt_exclusion(repo_dir)
328
329 # MOZILLABUILD
330 mozillabuild_dir = os.getenv("MOZILLABUILD")
331 if mozillabuild_dir:
332 paths.append(mozillabuild_dir)
333 print_attempt_exclusion(mozillabuild_dir)
334
335 # .mozbuild
336 mozbuild_dir = Path.home() / ".mozbuild"
337 paths.append(mozbuild_dir)
338 print_attempt_exclusion(mozbuild_dir)
339
340 args = ";".join(f"Add-MpPreference -ExclusionPath '{path}'" for path in paths)
341 command = f'-Command "{args}"'
342
343 # This will attempt to run as administrator by triggering a UAC prompt
344 # for admin credentials. If "No" is selected, no exclusions are added.
345 ctypes.windll.shell32.ShellExecuteW(None, "runas", powershell_exe, command, None, 0)
346
347
348 def clone(options):
349 vcs = options.vcs
350 no_interactive = options.no_interactive
351 no_system_changes = options.no_system_changes
352
353 if vcs == "hg":
354 hg = which("hg")
355 if not hg:
356 print("Mercurial is not installed. Mercurial is required to clone Firefox.")
357 try:
358 # We're going to recommend people install the Mercurial package with
359 # pip3. That will work if `pip3` installs binaries to a location
360 # that's in the PATH, but it might not be. To help out, if we CAN
361 # import "mercurial" (in which case it's already been installed),
362 # offer that as a solution.
363 import mercurial # noqa: F401
364
365 print(
366 "Hint: have you made sure that Mercurial is installed to a "
367 "location in your PATH?"
368 )
369 except ImportError:
370 print("Try installing hg with `pip3 install Mercurial`.")
371 return None
372 binary = hg
373 else:
374 binary = which("git")
375 if not binary:
376 print("Git is not installed.")
377 print("Try installing git using your system package manager.")
378 return None
379
380 dest = input_clone_dest(vcs, no_interactive)
381 if not dest:
382 return None
383
384 add_microsoft_defender_antivirus_exclusions(dest, no_system_changes)
385
386 print(f"Cloning Firefox {VCS_HUMAN_READABLE[vcs]} repository to {dest}")
387
388 head_repo = os.environ.get("GECKO_HEAD_REPOSITORY")
389 head_rev = os.environ.get("GECKO_HEAD_REV")
390
391 if vcs == "hg":
392 return hg_clone_firefox(binary, dest, head_repo, head_rev)
393 elif vcs == "git-cinnabar":
394 return git_cinnabar_clone_firefox(binary, dest, head_repo, head_rev)
395 else:
396 return git_clone_firefox(binary, dest, head_repo, head_rev)
397
398
399 def bootstrap(srcdir: Path, application_choice, no_interactive, no_system_changes):
400 args = [sys.executable, "mach"]
401
402 if no_interactive:
403 # --no-interactive is a global argument, not a command argument,
404 # so it needs to be specified before "bootstrap" is appended.
405 args += ["--no-interactive"]
406
407 args += ["bootstrap"]
408
409 if application_choice:
410 args += ["--application-choice", application_choice]
411 if no_system_changes:
412 args += ["--no-system-changes"]
413
414 print("Running `%s`" % " ".join(args))
415 return subprocess.call(args, cwd=str(srcdir))
416
417
418 def main(args):
419 parser = OptionParser()
420 parser.add_option(
421 "--application-choice",
422 dest="application_choice",
423 help='Pass in an application choice (see "APPLICATIONS" in '
424 "python/mozboot/mozboot/bootstrap.py) instead of using the "
425 "default interactive prompt.",
426 )
427 parser.add_option(
428 "--vcs",
429 dest="vcs",
430 default="git",
431 choices=["git", "git-cinnabar", "hg"],
432 help="VCS (hg or git) to use for downloading the source code, "
433 "instead of using the default interactive prompt.",
434 )
435 parser.add_option(
436 "--no-interactive",
437 dest="no_interactive",
438 action="store_true",
439 help="Answer yes to any (Y/n) interactive prompts.",
440 )
441 parser.add_option(
442 "--no-system-changes",
443 dest="no_system_changes",
444 action="store_true",
445 help="Only executes actions that leave the system " "configuration alone.",
446 )
447
448 options, leftover = parser.parse_args(args)
449 try:
450 srcdir = clone(options)
451 if not srcdir:
452 return 1
453 print("Clone complete.")
454 print(
455 "If you need to run the tooling bootstrapping again, "
456 "then consider running './mach bootstrap' instead."
457 )
458 if not options.no_interactive:
459 remove_bootstrap_file = input(
460 "Unless you are going to have more local copies of Firefox source code, "
461 "this 'bootstrap.py' file is no longer needed and can be deleted. "
462 "Clean up the bootstrap.py file? (Y/n)"
463 )
464 if not remove_bootstrap_file:
465 remove_bootstrap_file = "y"
466 if options.no_interactive or remove_bootstrap_file == "y":
467 try:
468 Path(sys.argv[0]).unlink()
469 except FileNotFoundError:
470 print("File could not be found !")
471 return bootstrap(
472 srcdir,
473 options.application_choice,
474 options.no_interactive,
475 options.no_system_changes,
476 )
477 except Exception:
478 print("Could not bootstrap Firefox! Consider filing a bug.")
479 raise
480
481
482 if __name__ == "__main__":
483 sys.exit(main(sys.argv))