blob: 90aba144252d083033140f2ae3b71f4edcfe3096 [file] [log] [blame]
Mike Frysingera488af52020-09-06 13:33:45 -04001#!/usr/bin/env python3
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002#
3# Copyright (C) 2008 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Mike Frysinger87fb5a12019-06-13 01:54:46 -040017"""The repo tool.
18
19People shouldn't run this directly; instead, they should use the `repo` wrapper
20which takes care of execing this entry point.
21"""
22
JoonCheol Parke9860722012-10-11 02:31:44 +090023import getpass
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070024import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025import optparse
26import os
Mike Frysinger949bc342020-02-18 21:37:00 -050027import shlex
Jason Changc6578442023-06-22 15:04:06 -070028import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050030import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070031import time
Mike Frysingeracf63b22019-06-13 02:24:21 -040032import urllib.request
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
Carlos Aguado1242e602014-02-03 13:48:47 +010034try:
Gavin Makea2e3302023-03-11 06:46:20 +000035 import kerberos
Carlos Aguado1242e602014-02-03 13:48:47 +010036except ImportError:
Gavin Makea2e3302023-03-11 06:46:20 +000037 kerberos = None
Carlos Aguado1242e602014-02-03 13:48:47 +010038
Mike Frysinger902665b2014-12-22 15:17:59 -050039from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070040import event_log
Joanna Wanga6c52f52022-11-03 16:51:19 -040041from repo_trace import SetTrace, Trace, SetTraceToStderr
David Pursehouse9090e802020-02-12 11:25:13 +090042from git_command import user_agent
Mike Frysinger5291eaf2021-05-05 15:53:03 -040043from git_config import RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080044from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080045from command import InteractiveCommand
46from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070047from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080048from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070049from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070050from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070051from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080052from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090053from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080054from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070055from error import NoSuchProjectError
56from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070057import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040058from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070059from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080060from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061
David Pursehouse5c6eeac2012-10-11 16:44:48 +090062from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063
Chirayu Desai217ea7d2013-03-01 19:14:38 +053064
Mike Frysinger37f28f12020-02-16 15:15:53 -050065# NB: These do not need to be kept in sync with the repo launcher script.
66# These may be much newer as it allows the repo launcher to roll between
67# different repo releases while source versions might require a newer python.
68#
69# The soft version is when we start warning users that the version is old and
70# we'll be dropping support for it. We'll refuse to work with versions older
71# than the hard version.
72#
73# python-3.6 is in Ubuntu Bionic.
74MIN_PYTHON_VERSION_SOFT = (3, 6)
Peter Kjellerstedta3b2edf2021-04-15 01:32:40 +020075MIN_PYTHON_VERSION_HARD = (3, 6)
Mike Frysinger37f28f12020-02-16 15:15:53 -050076
77if sys.version_info.major < 3:
Gavin Makea2e3302023-03-11 06:46:20 +000078 print(
79 "repo: error: Python 2 is no longer supported; "
80 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
81 file=sys.stderr,
82 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050083 sys.exit(1)
Gavin Makea2e3302023-03-11 06:46:20 +000084else:
85 if sys.version_info < MIN_PYTHON_VERSION_HARD:
86 print(
87 "repo: error: Python 3 version is too old; "
88 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
89 file=sys.stderr,
90 )
91 sys.exit(1)
92 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
93 print(
94 "repo: warning: your Python 3 version is no longer supported; "
95 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
96 file=sys.stderr,
97 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050098
Jason Changc6578442023-06-22 15:04:06 -070099KEYBOARD_INTERRUPT_EXIT = 128 + signal.SIGINT
Mike Frysinger37f28f12020-02-16 15:15:53 -0500100
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700101global_options = optparse.OptionParser(
Gavin Makea2e3302023-03-11 06:46:20 +0000102 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]",
103 add_help_option=False,
104)
105global_options.add_option(
106 "-h", "--help", action="store_true", help="show this help message and exit"
107)
108global_options.add_option(
109 "--help-all",
110 action="store_true",
111 help="show this help message with all subcommands and exit",
112)
113global_options.add_option(
114 "-p",
115 "--paginate",
116 dest="pager",
117 action="store_true",
118 help="display command output in the pager",
119)
120global_options.add_option(
121 "--no-pager", dest="pager", action="store_false", help="disable the pager"
122)
123global_options.add_option(
124 "--color",
125 choices=("auto", "always", "never"),
126 default=None,
127 help="control color usage: auto, always, never",
128)
129global_options.add_option(
130 "--trace",
131 dest="trace",
132 action="store_true",
133 help="trace git command execution (REPO_TRACE=1)",
134)
135global_options.add_option(
136 "--trace-to-stderr",
137 dest="trace_to_stderr",
138 action="store_true",
139 help="trace outputs go to stderr in addition to .repo/TRACE_FILE",
140)
141global_options.add_option(
142 "--trace-python",
143 dest="trace_python",
144 action="store_true",
145 help="trace python command execution",
146)
147global_options.add_option(
148 "--time",
149 dest="time",
150 action="store_true",
151 help="time repo command execution",
152)
153global_options.add_option(
154 "--version",
155 dest="show_version",
156 action="store_true",
157 help="display this version of repo",
158)
159global_options.add_option(
160 "--show-toplevel",
161 action="store_true",
162 help="display the path of the top-level directory of "
163 "the repo client checkout",
164)
165global_options.add_option(
166 "--event-log",
167 dest="event_log",
168 action="store",
169 help="filename of event log to append timeline to",
170)
171global_options.add_option(
172 "--git-trace2-event-log",
173 action="store",
174 help="directory to write git trace2 event log to",
175)
176global_options.add_option(
177 "--submanifest-path",
178 action="store",
179 metavar="REL_PATH",
180 help="submanifest path",
181)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700182
David Pursehouse819827a2020-02-12 15:20:19 +0900183
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700184class _Repo(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000185 def __init__(self, repodir):
186 self.repodir = repodir
187 self.commands = all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700188
Gavin Makea2e3302023-03-11 06:46:20 +0000189 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
190 """Show --help screen."""
191 global_options.print_help()
192 print()
193 if short:
194 commands = " ".join(sorted(self.commands))
195 wrapped_commands = textwrap.wrap(commands, width=77)
196 print(
197 "Available commands:\n %s" % ("\n ".join(wrapped_commands),)
198 )
199 print("\nRun `repo help <command>` for command-specific details.")
200 print("Bug reports:", Wrapper().BUG_URL)
Conley Owens7ba25be2012-11-14 14:18:06 -0800201 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000202 cmd = self.commands["help"]()
203 if all_commands:
204 cmd.PrintAllCommandsBody()
205 else:
206 cmd.PrintCommonCommandsBody()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400207
Gavin Makea2e3302023-03-11 06:46:20 +0000208 def _ParseArgs(self, argv):
209 """Parse the main `repo` command line options."""
210 for i, arg in enumerate(argv):
211 if not arg.startswith("-"):
212 name = arg
213 glob = argv[:i]
214 argv = argv[i + 1 :]
215 break
216 else:
217 name = None
218 glob = argv
219 argv = []
220 gopts, _gargs = global_options.parse_args(glob)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800221
Gavin Makea2e3302023-03-11 06:46:20 +0000222 if name:
223 name, alias_args = self._ExpandAlias(name)
224 argv = alias_args + argv
David Rileye0684ad2017-04-05 00:02:59 -0700225
Gavin Makea2e3302023-03-11 06:46:20 +0000226 return (name, gopts, argv)
227
228 def _ExpandAlias(self, name):
229 """Look up user registered aliases."""
230 # We don't resolve aliases for existing subcommands. This matches git.
231 if name in self.commands:
232 return name, []
233
234 key = "alias.%s" % (name,)
235 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
236 if alias is None:
237 alias = RepoConfig.ForUser().GetString(key)
238 if alias is None:
239 return name, []
240
241 args = alias.strip().split(" ", 1)
242 name = args[0]
243 if len(args) == 2:
244 args = shlex.split(args[1])
245 else:
246 args = []
247 return name, args
248
249 def _Run(self, name, gopts, argv):
250 """Execute the requested subcommand."""
251 result = 0
252
253 # Handle options that terminate quickly first.
254 if gopts.help or gopts.help_all:
255 self._PrintHelp(short=False, all_commands=gopts.help_all)
256 return 0
257 elif gopts.show_version:
258 # Always allow global --version regardless of subcommand validity.
259 name = "version"
260 elif gopts.show_toplevel:
261 print(os.path.dirname(self.repodir))
262 return 0
263 elif not name:
264 # No subcommand specified, so show the help/subcommand.
265 self._PrintHelp(short=True)
266 return 1
267
268 run = lambda: self._RunLong(name, gopts, argv) or 0
269 with Trace(
270 "starting new command: %s",
271 ", ".join([name] + argv),
272 first_trace=True,
273 ):
274 if gopts.trace_python:
275 import trace
276
277 tracer = trace.Trace(
278 count=False,
279 trace=True,
280 timing=True,
281 ignoredirs=set(sys.path[1:]),
282 )
283 result = tracer.runfunc(run)
284 else:
285 result = run()
286 return result
287
288 def _RunLong(self, name, gopts, argv):
289 """Execute the (longer running) requested subcommand."""
290 result = 0
291 SetDefaultColoring(gopts.color)
292
293 git_trace2_event_log = EventLog()
294 outer_client = RepoClient(self.repodir)
295 repo_client = outer_client
296 if gopts.submanifest_path:
297 repo_client = RepoClient(
298 self.repodir,
299 submanifest_path=gopts.submanifest_path,
300 outer_client=outer_client,
301 )
302 gitc_manifest = None
303 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
304 if gitc_client_name:
305 gitc_manifest = GitcClient(self.repodir, gitc_client_name)
306 repo_client.isGitcClient = True
307
308 try:
309 cmd = self.commands[name](
310 repodir=self.repodir,
311 client=repo_client,
312 manifest=repo_client.manifest,
313 outer_client=outer_client,
314 outer_manifest=outer_client.manifest,
315 gitc_manifest=gitc_manifest,
316 git_event_log=git_trace2_event_log,
317 )
318 except KeyError:
319 print(
320 "repo: '%s' is not a repo command. See 'repo help'." % name,
321 file=sys.stderr,
322 )
323 return 1
324
325 Editor.globalConfig = cmd.client.globalConfig
326
327 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
328 print(
329 "fatal: '%s' requires a working directory" % name,
330 file=sys.stderr,
331 )
332 return 1
333
334 if (
335 isinstance(cmd, GitcAvailableCommand)
336 and not gitc_utils.get_gitc_manifest_dir()
337 ):
338 print(
339 "fatal: '%s' requires GITC to be available" % name,
340 file=sys.stderr,
341 )
342 return 1
343
344 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
345 print("fatal: '%s' requires a GITC client" % name, file=sys.stderr)
346 return 1
347
348 try:
349 copts, cargs = cmd.OptionParser.parse_args(argv)
350 copts = cmd.ReadEnvironmentOptions(copts)
351 except NoManifestException as e:
352 print(
353 "error: in `%s`: %s" % (" ".join([name] + argv), str(e)),
354 file=sys.stderr,
355 )
356 print(
357 "error: manifest missing or unreadable -- please run init",
358 file=sys.stderr,
359 )
360 return 1
361
362 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
363 config = cmd.client.globalConfig
364 if gopts.pager:
365 use_pager = True
366 else:
367 use_pager = config.GetBoolean("pager.%s" % name)
368 if use_pager is None:
369 use_pager = cmd.WantPager(copts)
370 if use_pager:
371 RunPager(config)
372
373 start = time.time()
374 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
375 cmd.event_log.SetParent(cmd_event)
376 git_trace2_event_log.StartEvent()
377 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
378
Jason Changc6578442023-06-22 15:04:06 -0700379 def execute_command_helper():
380 """
381 Execute the subcommand.
382 """
383 nonlocal result
Gavin Makea2e3302023-03-11 06:46:20 +0000384 cmd.CommonValidateOptions(copts, cargs)
385 cmd.ValidateOptions(copts, cargs)
386
387 this_manifest_only = copts.this_manifest_only
388 outer_manifest = copts.outer_manifest
389 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
390 result = cmd.Execute(copts, cargs)
391 elif outer_manifest and repo_client.manifest.is_submanifest:
392 # The command does not support multi-manifest, we are using a
393 # submanifest, and the command line is for the outermost
394 # manifest. Re-run using the outermost manifest, which will
395 # recurse through the submanifests.
396 gopts.submanifest_path = ""
397 result = self._Run(name, gopts, argv)
398 else:
399 # No multi-manifest support. Run the command in the current
400 # (sub)manifest, and then any child submanifests.
401 result = cmd.Execute(copts, cargs)
402 for submanifest in repo_client.manifest.submanifests.values():
403 spec = submanifest.ToSubmanifestSpec()
404 gopts.submanifest_path = submanifest.repo_client.path_prefix
405 child_argv = argv[:]
406 child_argv.append("--no-outer-manifest")
407 # Not all subcommands support the 3 manifest options, so
408 # only add them if the original command includes them.
409 if hasattr(copts, "manifest_url"):
410 child_argv.extend(["--manifest-url", spec.manifestUrl])
411 if hasattr(copts, "manifest_name"):
412 child_argv.extend(
413 ["--manifest-name", spec.manifestName]
414 )
415 if hasattr(copts, "manifest_branch"):
416 child_argv.extend(["--manifest-branch", spec.revision])
417 result = self._Run(name, gopts, child_argv) or result
Jason Changc6578442023-06-22 15:04:06 -0700418
419 def execute_command():
420 """
421 Execute the command and log uncaught exceptions.
422 """
423 try:
424 execute_command_helper()
425 except (KeyboardInterrupt, SystemExit, Exception) as e:
426 ok = isinstance(e, SystemExit) and not e.code
427 if not ok:
428 exception_name = type(e).__name__
429 git_trace2_event_log.ErrorEvent(
430 f"RepoExitError:{exception_name}")
431 raise
432
433 try:
434 execute_command()
Gavin Makea2e3302023-03-11 06:46:20 +0000435 except (
436 DownloadError,
437 ManifestInvalidRevisionError,
438 NoManifestException,
439 ) as e:
440 print(
441 "error: in `%s`: %s" % (" ".join([name] + argv), str(e)),
442 file=sys.stderr,
443 )
444 if isinstance(e, NoManifestException):
445 print(
446 "error: manifest missing or unreadable -- please run init",
447 file=sys.stderr,
448 )
449 result = 1
450 except NoSuchProjectError as e:
451 if e.name:
452 print("error: project %s not found" % e.name, file=sys.stderr)
453 else:
454 print("error: no project in current directory", file=sys.stderr)
455 result = 1
456 except InvalidProjectGroupsError as e:
457 if e.name:
458 print(
459 "error: project group must be enabled for project %s"
460 % e.name,
461 file=sys.stderr,
462 )
463 else:
464 print(
465 "error: project group must be enabled for the project in "
466 "the current directory",
467 file=sys.stderr,
468 )
469 result = 1
470 except SystemExit as e:
471 if e.code:
472 result = e.code
473 raise
Jason Changc6578442023-06-22 15:04:06 -0700474 except KeyboardInterrupt:
475 result = KEYBOARD_INTERRUPT_EXIT
476 raise
477 except Exception:
478 result = 1
479 raise
Gavin Makea2e3302023-03-11 06:46:20 +0000480 finally:
481 finish = time.time()
482 elapsed = finish - start
483 hours, remainder = divmod(elapsed, 3600)
484 minutes, seconds = divmod(remainder, 60)
485 if gopts.time:
486 if hours == 0:
487 print(
488 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
489 )
490 else:
491 print(
492 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
493 file=sys.stderr,
494 )
495
496 cmd.event_log.FinishEvent(
497 cmd_event, finish, result is None or result == 0
498 )
499 git_trace2_event_log.DefParamRepoEvents(
500 cmd.manifest.manifestProject.config.DumpConfigDict()
501 )
502 git_trace2_event_log.ExitEvent(result)
503
504 if gopts.event_log:
505 cmd.event_log.Write(
506 os.path.abspath(os.path.expanduser(gopts.event_log))
507 )
508
509 git_trace2_event_log.Write(gopts.git_trace2_event_log)
510 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700511
Conley Owens094cdbe2014-01-30 15:09:59 -0800512
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500513def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000514 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500515
Gavin Makea2e3302023-03-11 06:46:20 +0000516 Args:
517 ver_str: The version string passed from the repo launcher when it ran
518 us.
519 repo_path: The path to the repo launcher that loaded us.
520 """
521 # Refuse to work with really old wrapper versions. We don't test these,
522 # so might as well require a somewhat recent sane version.
523 # v1.15 of the repo launcher was released in ~Mar 2012.
524 MIN_REPO_VERSION = (1, 15)
525 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500526
Gavin Makea2e3302023-03-11 06:46:20 +0000527 if not repo_path:
528 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529
Gavin Makea2e3302023-03-11 06:46:20 +0000530 if not ver_str:
531 print("no --wrapper-version argument", file=sys.stderr)
532 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700533
Gavin Makea2e3302023-03-11 06:46:20 +0000534 # Pull out the version of the repo launcher we know about to compare.
535 exp = Wrapper().VERSION
536 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537
Gavin Makea2e3302023-03-11 06:46:20 +0000538 exp_str = ".".join(map(str, exp))
539 if ver < MIN_REPO_VERSION:
540 print(
541 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500542repo: error:
543!!! Your version of repo %s is too old.
544!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900545!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500546!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700547
548 cp %s %s
Gavin Makea2e3302023-03-11 06:46:20 +0000549"""
550 % (ver_str, min_str, exp_str, WrapperPath(), repo_path),
551 file=sys.stderr,
552 )
553 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700554
Gavin Makea2e3302023-03-11 06:46:20 +0000555 if exp > ver:
556 print(
557 "\n... A new version of repo (%s) is available." % (exp_str,),
558 file=sys.stderr,
559 )
560 if os.access(repo_path, os.W_OK):
561 print(
562 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700563... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700564 cp %s %s
Gavin Makea2e3302023-03-11 06:46:20 +0000565"""
566 % (WrapperPath(), repo_path),
567 file=sys.stderr,
568 )
569 else:
570 print(
571 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500572... New version is available at: %s
573... The launcher is run from: %s
574!!! The launcher is not writable. Please talk to your sysadmin or distro
575!!! to get an update installed.
Gavin Makea2e3302023-03-11 06:46:20 +0000576"""
577 % (WrapperPath(), repo_path),
578 file=sys.stderr,
579 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700580
David Pursehouse819827a2020-02-12 15:20:19 +0900581
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200582def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000583 if not repo_dir:
584 print("no --repo-dir argument", file=sys.stderr)
585 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586
David Pursehouse819827a2020-02-12 15:20:19 +0900587
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700588def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000589 i = 0
590 while i < len(argv):
591 a = argv[i]
592 if a == "--":
593 break
594 if a.startswith("--"):
595 eq = a.find("=")
596 if eq > 0:
597 a = a[0:eq]
598 if not opt.has_option(a):
599 del argv[i]
600 continue
601 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700602
David Pursehouse819827a2020-02-12 15:20:19 +0900603
Sarah Owens1f7627f2012-10-31 09:21:55 -0700604class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000605 def http_request(self, req):
606 req.add_header("User-Agent", user_agent.repo)
607 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700608
Gavin Makea2e3302023-03-11 06:46:20 +0000609 def https_request(self, req):
610 req.add_header("User-Agent", user_agent.repo)
611 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700612
David Pursehouse819827a2020-02-12 15:20:19 +0900613
JoonCheol Parke9860722012-10-11 02:31:44 +0900614def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000615 # If repo could not find auth info from netrc, try to get it from user input
616 url = req.get_full_url()
617 user, password = handler.passwd.find_user_password(None, url)
618 if user is None:
619 print(msg)
620 try:
621 user = input("User: ")
622 password = getpass.getpass()
623 except KeyboardInterrupt:
624 return
625 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900626
David Pursehouse819827a2020-02-12 15:20:19 +0900627
Sarah Owens1f7627f2012-10-31 09:21:55 -0700628class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000629 def http_error_401(self, req, fp, code, msg, headers):
630 _AddPasswordFromUserInput(self, msg, req)
631 return urllib.request.HTTPBasicAuthHandler.http_error_401(
632 self, req, fp, code, msg, headers
633 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900634
Gavin Makea2e3302023-03-11 06:46:20 +0000635 def http_error_auth_reqed(self, authreq, host, req, headers):
636 try:
637 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900638
Gavin Makea2e3302023-03-11 06:46:20 +0000639 def _add_header(name, val):
640 val = val.replace("\n", "")
641 old_add_header(name, val)
642
643 req.add_header = _add_header
644 return (
645 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
646 self, authreq, host, req, headers
647 )
648 )
649 except Exception:
650 reset = getattr(self, "reset_retry_count", None)
651 if reset is not None:
652 reset()
653 elif getattr(self, "retried", None):
654 self.retried = 0
655 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700656
David Pursehouse819827a2020-02-12 15:20:19 +0900657
Sarah Owens1f7627f2012-10-31 09:21:55 -0700658class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000659 def http_error_401(self, req, fp, code, msg, headers):
660 _AddPasswordFromUserInput(self, msg, req)
661 return urllib.request.HTTPDigestAuthHandler.http_error_401(
662 self, req, fp, code, msg, headers
663 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900664
Gavin Makea2e3302023-03-11 06:46:20 +0000665 def http_error_auth_reqed(self, auth_header, host, req, headers):
666 try:
667 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900668
Gavin Makea2e3302023-03-11 06:46:20 +0000669 def _add_header(name, val):
670 val = val.replace("\n", "")
671 old_add_header(name, val)
672
673 req.add_header = _add_header
674 return (
675 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
676 self, auth_header, host, req, headers
677 )
678 )
679 except Exception:
680 reset = getattr(self, "reset_retry_count", None)
681 if reset is not None:
682 reset()
683 elif getattr(self, "retried", None):
684 self.retried = 0
685 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800686
David Pursehouse819827a2020-02-12 15:20:19 +0900687
Carlos Aguado1242e602014-02-03 13:48:47 +0100688class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000689 def __init__(self):
690 self.retried = 0
691 self.context = None
692 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100693
Gavin Makea2e3302023-03-11 06:46:20 +0000694 def http_error_401(self, req, fp, code, msg, headers):
695 host = req.get_host()
696 retry = self.http_error_auth_reqed(
697 "www-authenticate", host, req, headers
698 )
699 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100700
Gavin Makea2e3302023-03-11 06:46:20 +0000701 def http_error_auth_reqed(self, auth_header, host, req, headers):
702 try:
703 spn = "HTTP@%s" % host
704 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100705
Gavin Makea2e3302023-03-11 06:46:20 +0000706 if self.retried > 3:
707 raise urllib.request.HTTPError(
708 req.get_full_url(),
709 401,
710 "Negotiate auth failed",
711 headers,
712 None,
713 )
714 else:
715 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100716
Gavin Makea2e3302023-03-11 06:46:20 +0000717 neghdr = self._negotiate_get_svctk(spn, authdata)
718 if neghdr is None:
719 return None
720
721 req.add_unredirected_header("Authorization", neghdr)
722 response = self.parent.open(req)
723
724 srvauth = self._negotiate_get_authdata(auth_header, response.info())
725 if self._validate_response(srvauth):
726 return response
727 except kerberos.GSSError:
728 return None
729 except Exception:
730 self.reset_retry_count()
731 raise
732 finally:
733 self._clean_context()
734
735 def reset_retry_count(self):
736 self.retried = 0
737
738 def _negotiate_get_authdata(self, auth_header, headers):
739 authhdr = headers.get(auth_header, None)
740 if authhdr is not None:
741 for mech_tuple in authhdr.split(","):
742 mech, __, authdata = mech_tuple.strip().partition(" ")
743 if mech.lower() == "negotiate":
744 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100745 return None
746
Gavin Makea2e3302023-03-11 06:46:20 +0000747 def _negotiate_get_svctk(self, spn, authdata):
748 if authdata is None:
749 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100750
Gavin Makea2e3302023-03-11 06:46:20 +0000751 result, self.context = kerberos.authGSSClientInit(spn)
752 if result < kerberos.AUTH_GSS_COMPLETE:
753 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100754
Gavin Makea2e3302023-03-11 06:46:20 +0000755 result = kerberos.authGSSClientStep(self.context, authdata)
756 if result < kerberos.AUTH_GSS_CONTINUE:
757 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100758
Gavin Makea2e3302023-03-11 06:46:20 +0000759 response = kerberos.authGSSClientResponse(self.context)
760 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100761
Gavin Makea2e3302023-03-11 06:46:20 +0000762 def _validate_response(self, authdata):
763 if authdata is None:
764 return None
765 result = kerberos.authGSSClientStep(self.context, authdata)
766 if result == kerberos.AUTH_GSS_COMPLETE:
767 return True
768 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100769
Gavin Makea2e3302023-03-11 06:46:20 +0000770 def _clean_context(self):
771 if self.context is not None:
772 kerberos.authGSSClientClean(self.context)
773 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100774
David Pursehouse819827a2020-02-12 15:20:19 +0900775
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700776def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000777 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700778
Gavin Makea2e3302023-03-11 06:46:20 +0000779 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
780 try:
781 n = netrc.netrc()
782 for host in n.hosts:
783 p = n.hosts[host]
784 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
785 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
786 except netrc.NetrcParseError:
787 pass
788 except IOError:
789 pass
790 handlers.append(_BasicAuthHandler(mgr))
791 handlers.append(_DigestAuthHandler(mgr))
792 if kerberos:
793 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700794
Gavin Makea2e3302023-03-11 06:46:20 +0000795 if "http_proxy" in os.environ:
796 url = os.environ["http_proxy"]
797 handlers.append(
798 urllib.request.ProxyHandler({"http": url, "https": url})
799 )
800 if "REPO_CURL_VERBOSE" in os.environ:
801 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
802 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
803 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700804
David Pursehouse819827a2020-02-12 15:20:19 +0900805
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700806def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000807 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400808
Gavin Makea2e3302023-03-11 06:46:20 +0000809 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
810 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
811 opt.add_option(
812 "--wrapper-version",
813 dest="wrapper_version",
814 help="version of the wrapper script",
815 )
816 opt.add_option(
817 "--wrapper-path",
818 dest="wrapper_path",
819 help="location of the wrapper script",
820 )
821 _PruneOptions(argv, opt)
822 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700823
Gavin Makea2e3302023-03-11 06:46:20 +0000824 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
825 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700826
Gavin Makea2e3302023-03-11 06:46:20 +0000827 Version.wrapper_version = opt.wrapper_version
828 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800829
Gavin Makea2e3302023-03-11 06:46:20 +0000830 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400831
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700832 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000833 init_http()
834 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400835
Gavin Makea2e3302023-03-11 06:46:20 +0000836 if gopts.trace:
837 SetTrace()
838
839 if gopts.trace_to_stderr:
840 SetTraceToStderr()
841
842 result = repo._Run(name, gopts, argv) or 0
843 except KeyboardInterrupt:
844 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700845 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000846 except ManifestParseError as mpe:
847 print("fatal: %s" % mpe, file=sys.stderr)
848 result = 1
849 except RepoChangedException as rce:
850 # If repo changed, re-exec ourselves.
851 #
852 argv = list(sys.argv)
853 argv.extend(rce.extra_args)
854 try:
855 os.execv(sys.executable, [__file__] + argv)
856 except OSError as e:
857 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
858 print("fatal: %s" % e, file=sys.stderr)
859 result = 128
860
861 TerminatePager()
862 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700863
David Pursehouse819827a2020-02-12 15:20:19 +0900864
Gavin Makea2e3302023-03-11 06:46:20 +0000865if __name__ == "__main__":
866 _Main(sys.argv[1:])