blob: 6dcb66f628db4c8353c50dbbec22d65952c367bf [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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050029import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070030import time
Mike Frysingeracf63b22019-06-13 02:24:21 -040031import urllib.request
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
Carlos Aguado1242e602014-02-03 13:48:47 +010033try:
Gavin Makea2e3302023-03-11 06:46:20 +000034 import kerberos
Carlos Aguado1242e602014-02-03 13:48:47 +010035except ImportError:
Gavin Makea2e3302023-03-11 06:46:20 +000036 kerberos = None
Carlos Aguado1242e602014-02-03 13:48:47 +010037
Mike Frysinger902665b2014-12-22 15:17:59 -050038from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070039import event_log
Joanna Wanga6c52f52022-11-03 16:51:19 -040040from repo_trace import SetTrace, Trace, SetTraceToStderr
David Pursehouse9090e802020-02-12 11:25:13 +090041from git_command import user_agent
Mike Frysinger5291eaf2021-05-05 15:53:03 -040042from git_config import RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080043from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080044from command import InteractiveCommand
45from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070046from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080047from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070048from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070049from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070050from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080051from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090052from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080053from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070054from error import NoSuchProjectError
55from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070056import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040057from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070058from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080059from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070060
David Pursehouse5c6eeac2012-10-11 16:44:48 +090061from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070062
Chirayu Desai217ea7d2013-03-01 19:14:38 +053063
Mike Frysinger37f28f12020-02-16 15:15:53 -050064# NB: These do not need to be kept in sync with the repo launcher script.
65# These may be much newer as it allows the repo launcher to roll between
66# different repo releases while source versions might require a newer python.
67#
68# The soft version is when we start warning users that the version is old and
69# we'll be dropping support for it. We'll refuse to work with versions older
70# than the hard version.
71#
72# python-3.6 is in Ubuntu Bionic.
73MIN_PYTHON_VERSION_SOFT = (3, 6)
Peter Kjellerstedta3b2edf2021-04-15 01:32:40 +020074MIN_PYTHON_VERSION_HARD = (3, 6)
Mike Frysinger37f28f12020-02-16 15:15:53 -050075
76if sys.version_info.major < 3:
Gavin Makea2e3302023-03-11 06:46:20 +000077 print(
78 "repo: error: Python 2 is no longer supported; "
79 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
80 file=sys.stderr,
81 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050082 sys.exit(1)
Gavin Makea2e3302023-03-11 06:46:20 +000083else:
84 if sys.version_info < MIN_PYTHON_VERSION_HARD:
85 print(
86 "repo: error: Python 3 version is too old; "
87 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
88 file=sys.stderr,
89 )
90 sys.exit(1)
91 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
92 print(
93 "repo: warning: your Python 3 version is no longer supported; "
94 "Please upgrade to Python {}.{}+.".format(*MIN_PYTHON_VERSION_SOFT),
95 file=sys.stderr,
96 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050097
98
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070099global_options = optparse.OptionParser(
Gavin Makea2e3302023-03-11 06:46:20 +0000100 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]",
101 add_help_option=False,
102)
103global_options.add_option(
104 "-h", "--help", action="store_true", help="show this help message and exit"
105)
106global_options.add_option(
107 "--help-all",
108 action="store_true",
109 help="show this help message with all subcommands and exit",
110)
111global_options.add_option(
112 "-p",
113 "--paginate",
114 dest="pager",
115 action="store_true",
116 help="display command output in the pager",
117)
118global_options.add_option(
119 "--no-pager", dest="pager", action="store_false", help="disable the pager"
120)
121global_options.add_option(
122 "--color",
123 choices=("auto", "always", "never"),
124 default=None,
125 help="control color usage: auto, always, never",
126)
127global_options.add_option(
128 "--trace",
129 dest="trace",
130 action="store_true",
131 help="trace git command execution (REPO_TRACE=1)",
132)
133global_options.add_option(
134 "--trace-to-stderr",
135 dest="trace_to_stderr",
136 action="store_true",
137 help="trace outputs go to stderr in addition to .repo/TRACE_FILE",
138)
139global_options.add_option(
140 "--trace-python",
141 dest="trace_python",
142 action="store_true",
143 help="trace python command execution",
144)
145global_options.add_option(
146 "--time",
147 dest="time",
148 action="store_true",
149 help="time repo command execution",
150)
151global_options.add_option(
152 "--version",
153 dest="show_version",
154 action="store_true",
155 help="display this version of repo",
156)
157global_options.add_option(
158 "--show-toplevel",
159 action="store_true",
160 help="display the path of the top-level directory of "
161 "the repo client checkout",
162)
163global_options.add_option(
164 "--event-log",
165 dest="event_log",
166 action="store",
167 help="filename of event log to append timeline to",
168)
169global_options.add_option(
170 "--git-trace2-event-log",
171 action="store",
172 help="directory to write git trace2 event log to",
173)
174global_options.add_option(
175 "--submanifest-path",
176 action="store",
177 metavar="REL_PATH",
178 help="submanifest path",
179)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700180
David Pursehouse819827a2020-02-12 15:20:19 +0900181
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700182class _Repo(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000183 def __init__(self, repodir):
184 self.repodir = repodir
185 self.commands = all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700186
Gavin Makea2e3302023-03-11 06:46:20 +0000187 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
188 """Show --help screen."""
189 global_options.print_help()
190 print()
191 if short:
192 commands = " ".join(sorted(self.commands))
193 wrapped_commands = textwrap.wrap(commands, width=77)
194 print(
195 "Available commands:\n %s" % ("\n ".join(wrapped_commands),)
196 )
197 print("\nRun `repo help <command>` for command-specific details.")
198 print("Bug reports:", Wrapper().BUG_URL)
Conley Owens7ba25be2012-11-14 14:18:06 -0800199 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000200 cmd = self.commands["help"]()
201 if all_commands:
202 cmd.PrintAllCommandsBody()
203 else:
204 cmd.PrintCommonCommandsBody()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400205
Gavin Makea2e3302023-03-11 06:46:20 +0000206 def _ParseArgs(self, argv):
207 """Parse the main `repo` command line options."""
208 for i, arg in enumerate(argv):
209 if not arg.startswith("-"):
210 name = arg
211 glob = argv[:i]
212 argv = argv[i + 1 :]
213 break
214 else:
215 name = None
216 glob = argv
217 argv = []
218 gopts, _gargs = global_options.parse_args(glob)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800219
Gavin Makea2e3302023-03-11 06:46:20 +0000220 if name:
221 name, alias_args = self._ExpandAlias(name)
222 argv = alias_args + argv
David Rileye0684ad2017-04-05 00:02:59 -0700223
Gavin Makea2e3302023-03-11 06:46:20 +0000224 return (name, gopts, argv)
225
226 def _ExpandAlias(self, name):
227 """Look up user registered aliases."""
228 # We don't resolve aliases for existing subcommands. This matches git.
229 if name in self.commands:
230 return name, []
231
232 key = "alias.%s" % (name,)
233 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
234 if alias is None:
235 alias = RepoConfig.ForUser().GetString(key)
236 if alias is None:
237 return name, []
238
239 args = alias.strip().split(" ", 1)
240 name = args[0]
241 if len(args) == 2:
242 args = shlex.split(args[1])
243 else:
244 args = []
245 return name, args
246
247 def _Run(self, name, gopts, argv):
248 """Execute the requested subcommand."""
249 result = 0
250
251 # Handle options that terminate quickly first.
252 if gopts.help or gopts.help_all:
253 self._PrintHelp(short=False, all_commands=gopts.help_all)
254 return 0
255 elif gopts.show_version:
256 # Always allow global --version regardless of subcommand validity.
257 name = "version"
258 elif gopts.show_toplevel:
259 print(os.path.dirname(self.repodir))
260 return 0
261 elif not name:
262 # No subcommand specified, so show the help/subcommand.
263 self._PrintHelp(short=True)
264 return 1
265
266 run = lambda: self._RunLong(name, gopts, argv) or 0
267 with Trace(
268 "starting new command: %s",
269 ", ".join([name] + argv),
270 first_trace=True,
271 ):
272 if gopts.trace_python:
273 import trace
274
275 tracer = trace.Trace(
276 count=False,
277 trace=True,
278 timing=True,
279 ignoredirs=set(sys.path[1:]),
280 )
281 result = tracer.runfunc(run)
282 else:
283 result = run()
284 return result
285
286 def _RunLong(self, name, gopts, argv):
287 """Execute the (longer running) requested subcommand."""
288 result = 0
289 SetDefaultColoring(gopts.color)
290
291 git_trace2_event_log = EventLog()
292 outer_client = RepoClient(self.repodir)
293 repo_client = outer_client
294 if gopts.submanifest_path:
295 repo_client = RepoClient(
296 self.repodir,
297 submanifest_path=gopts.submanifest_path,
298 outer_client=outer_client,
299 )
300 gitc_manifest = None
301 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
302 if gitc_client_name:
303 gitc_manifest = GitcClient(self.repodir, gitc_client_name)
304 repo_client.isGitcClient = True
305
306 try:
307 cmd = self.commands[name](
308 repodir=self.repodir,
309 client=repo_client,
310 manifest=repo_client.manifest,
311 outer_client=outer_client,
312 outer_manifest=outer_client.manifest,
313 gitc_manifest=gitc_manifest,
314 git_event_log=git_trace2_event_log,
315 )
316 except KeyError:
317 print(
318 "repo: '%s' is not a repo command. See 'repo help'." % name,
319 file=sys.stderr,
320 )
321 return 1
322
323 Editor.globalConfig = cmd.client.globalConfig
324
325 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
326 print(
327 "fatal: '%s' requires a working directory" % name,
328 file=sys.stderr,
329 )
330 return 1
331
332 if (
333 isinstance(cmd, GitcAvailableCommand)
334 and not gitc_utils.get_gitc_manifest_dir()
335 ):
336 print(
337 "fatal: '%s' requires GITC to be available" % name,
338 file=sys.stderr,
339 )
340 return 1
341
342 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
343 print("fatal: '%s' requires a GITC client" % name, file=sys.stderr)
344 return 1
345
346 try:
347 copts, cargs = cmd.OptionParser.parse_args(argv)
348 copts = cmd.ReadEnvironmentOptions(copts)
349 except NoManifestException as e:
350 print(
351 "error: in `%s`: %s" % (" ".join([name] + argv), str(e)),
352 file=sys.stderr,
353 )
354 print(
355 "error: manifest missing or unreadable -- please run init",
356 file=sys.stderr,
357 )
358 return 1
359
360 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
361 config = cmd.client.globalConfig
362 if gopts.pager:
363 use_pager = True
364 else:
365 use_pager = config.GetBoolean("pager.%s" % name)
366 if use_pager is None:
367 use_pager = cmd.WantPager(copts)
368 if use_pager:
369 RunPager(config)
370
371 start = time.time()
372 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
373 cmd.event_log.SetParent(cmd_event)
374 git_trace2_event_log.StartEvent()
375 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
376
377 try:
378 cmd.CommonValidateOptions(copts, cargs)
379 cmd.ValidateOptions(copts, cargs)
380
381 this_manifest_only = copts.this_manifest_only
382 outer_manifest = copts.outer_manifest
383 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
384 result = cmd.Execute(copts, cargs)
385 elif outer_manifest and repo_client.manifest.is_submanifest:
386 # The command does not support multi-manifest, we are using a
387 # submanifest, and the command line is for the outermost
388 # manifest. Re-run using the outermost manifest, which will
389 # recurse through the submanifests.
390 gopts.submanifest_path = ""
391 result = self._Run(name, gopts, argv)
392 else:
393 # No multi-manifest support. Run the command in the current
394 # (sub)manifest, and then any child submanifests.
395 result = cmd.Execute(copts, cargs)
396 for submanifest in repo_client.manifest.submanifests.values():
397 spec = submanifest.ToSubmanifestSpec()
398 gopts.submanifest_path = submanifest.repo_client.path_prefix
399 child_argv = argv[:]
400 child_argv.append("--no-outer-manifest")
401 # Not all subcommands support the 3 manifest options, so
402 # only add them if the original command includes them.
403 if hasattr(copts, "manifest_url"):
404 child_argv.extend(["--manifest-url", spec.manifestUrl])
405 if hasattr(copts, "manifest_name"):
406 child_argv.extend(
407 ["--manifest-name", spec.manifestName]
408 )
409 if hasattr(copts, "manifest_branch"):
410 child_argv.extend(["--manifest-branch", spec.revision])
411 result = self._Run(name, gopts, child_argv) or result
412 except (
413 DownloadError,
414 ManifestInvalidRevisionError,
415 NoManifestException,
416 ) as e:
417 print(
418 "error: in `%s`: %s" % (" ".join([name] + argv), str(e)),
419 file=sys.stderr,
420 )
421 if isinstance(e, NoManifestException):
422 print(
423 "error: manifest missing or unreadable -- please run init",
424 file=sys.stderr,
425 )
426 result = 1
427 except NoSuchProjectError as e:
428 if e.name:
429 print("error: project %s not found" % e.name, file=sys.stderr)
430 else:
431 print("error: no project in current directory", file=sys.stderr)
432 result = 1
433 except InvalidProjectGroupsError as e:
434 if e.name:
435 print(
436 "error: project group must be enabled for project %s"
437 % e.name,
438 file=sys.stderr,
439 )
440 else:
441 print(
442 "error: project group must be enabled for the project in "
443 "the current directory",
444 file=sys.stderr,
445 )
446 result = 1
447 except SystemExit as e:
448 if e.code:
449 result = e.code
450 raise
451 finally:
452 finish = time.time()
453 elapsed = finish - start
454 hours, remainder = divmod(elapsed, 3600)
455 minutes, seconds = divmod(remainder, 60)
456 if gopts.time:
457 if hours == 0:
458 print(
459 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
460 )
461 else:
462 print(
463 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
464 file=sys.stderr,
465 )
466
467 cmd.event_log.FinishEvent(
468 cmd_event, finish, result is None or result == 0
469 )
470 git_trace2_event_log.DefParamRepoEvents(
471 cmd.manifest.manifestProject.config.DumpConfigDict()
472 )
473 git_trace2_event_log.ExitEvent(result)
474
475 if gopts.event_log:
476 cmd.event_log.Write(
477 os.path.abspath(os.path.expanduser(gopts.event_log))
478 )
479
480 git_trace2_event_log.Write(gopts.git_trace2_event_log)
481 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700482
Conley Owens094cdbe2014-01-30 15:09:59 -0800483
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500484def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000485 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500486
Gavin Makea2e3302023-03-11 06:46:20 +0000487 Args:
488 ver_str: The version string passed from the repo launcher when it ran
489 us.
490 repo_path: The path to the repo launcher that loaded us.
491 """
492 # Refuse to work with really old wrapper versions. We don't test these,
493 # so might as well require a somewhat recent sane version.
494 # v1.15 of the repo launcher was released in ~Mar 2012.
495 MIN_REPO_VERSION = (1, 15)
496 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500497
Gavin Makea2e3302023-03-11 06:46:20 +0000498 if not repo_path:
499 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700500
Gavin Makea2e3302023-03-11 06:46:20 +0000501 if not ver_str:
502 print("no --wrapper-version argument", file=sys.stderr)
503 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700504
Gavin Makea2e3302023-03-11 06:46:20 +0000505 # Pull out the version of the repo launcher we know about to compare.
506 exp = Wrapper().VERSION
507 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700508
Gavin Makea2e3302023-03-11 06:46:20 +0000509 exp_str = ".".join(map(str, exp))
510 if ver < MIN_REPO_VERSION:
511 print(
512 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500513repo: error:
514!!! Your version of repo %s is too old.
515!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900516!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500517!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518
519 cp %s %s
Gavin Makea2e3302023-03-11 06:46:20 +0000520"""
521 % (ver_str, min_str, exp_str, WrapperPath(), repo_path),
522 file=sys.stderr,
523 )
524 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700525
Gavin Makea2e3302023-03-11 06:46:20 +0000526 if exp > ver:
527 print(
528 "\n... A new version of repo (%s) is available." % (exp_str,),
529 file=sys.stderr,
530 )
531 if os.access(repo_path, os.W_OK):
532 print(
533 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700535 cp %s %s
Gavin Makea2e3302023-03-11 06:46:20 +0000536"""
537 % (WrapperPath(), repo_path),
538 file=sys.stderr,
539 )
540 else:
541 print(
542 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500543... New version is available at: %s
544... The launcher is run from: %s
545!!! The launcher is not writable. Please talk to your sysadmin or distro
546!!! to get an update installed.
Gavin Makea2e3302023-03-11 06:46:20 +0000547"""
548 % (WrapperPath(), repo_path),
549 file=sys.stderr,
550 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700551
David Pursehouse819827a2020-02-12 15:20:19 +0900552
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200553def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000554 if not repo_dir:
555 print("no --repo-dir argument", file=sys.stderr)
556 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700557
David Pursehouse819827a2020-02-12 15:20:19 +0900558
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700559def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000560 i = 0
561 while i < len(argv):
562 a = argv[i]
563 if a == "--":
564 break
565 if a.startswith("--"):
566 eq = a.find("=")
567 if eq > 0:
568 a = a[0:eq]
569 if not opt.has_option(a):
570 del argv[i]
571 continue
572 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700573
David Pursehouse819827a2020-02-12 15:20:19 +0900574
Sarah Owens1f7627f2012-10-31 09:21:55 -0700575class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000576 def http_request(self, req):
577 req.add_header("User-Agent", user_agent.repo)
578 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700579
Gavin Makea2e3302023-03-11 06:46:20 +0000580 def https_request(self, req):
581 req.add_header("User-Agent", user_agent.repo)
582 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700583
David Pursehouse819827a2020-02-12 15:20:19 +0900584
JoonCheol Parke9860722012-10-11 02:31:44 +0900585def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000586 # If repo could not find auth info from netrc, try to get it from user input
587 url = req.get_full_url()
588 user, password = handler.passwd.find_user_password(None, url)
589 if user is None:
590 print(msg)
591 try:
592 user = input("User: ")
593 password = getpass.getpass()
594 except KeyboardInterrupt:
595 return
596 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900597
David Pursehouse819827a2020-02-12 15:20:19 +0900598
Sarah Owens1f7627f2012-10-31 09:21:55 -0700599class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000600 def http_error_401(self, req, fp, code, msg, headers):
601 _AddPasswordFromUserInput(self, msg, req)
602 return urllib.request.HTTPBasicAuthHandler.http_error_401(
603 self, req, fp, code, msg, headers
604 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900605
Gavin Makea2e3302023-03-11 06:46:20 +0000606 def http_error_auth_reqed(self, authreq, host, req, headers):
607 try:
608 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900609
Gavin Makea2e3302023-03-11 06:46:20 +0000610 def _add_header(name, val):
611 val = val.replace("\n", "")
612 old_add_header(name, val)
613
614 req.add_header = _add_header
615 return (
616 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
617 self, authreq, host, req, headers
618 )
619 )
620 except Exception:
621 reset = getattr(self, "reset_retry_count", None)
622 if reset is not None:
623 reset()
624 elif getattr(self, "retried", None):
625 self.retried = 0
626 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700627
David Pursehouse819827a2020-02-12 15:20:19 +0900628
Sarah Owens1f7627f2012-10-31 09:21:55 -0700629class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000630 def http_error_401(self, req, fp, code, msg, headers):
631 _AddPasswordFromUserInput(self, msg, req)
632 return urllib.request.HTTPDigestAuthHandler.http_error_401(
633 self, req, fp, code, msg, headers
634 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900635
Gavin Makea2e3302023-03-11 06:46:20 +0000636 def http_error_auth_reqed(self, auth_header, host, req, headers):
637 try:
638 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900639
Gavin Makea2e3302023-03-11 06:46:20 +0000640 def _add_header(name, val):
641 val = val.replace("\n", "")
642 old_add_header(name, val)
643
644 req.add_header = _add_header
645 return (
646 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
647 self, auth_header, host, req, headers
648 )
649 )
650 except Exception:
651 reset = getattr(self, "reset_retry_count", None)
652 if reset is not None:
653 reset()
654 elif getattr(self, "retried", None):
655 self.retried = 0
656 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800657
David Pursehouse819827a2020-02-12 15:20:19 +0900658
Carlos Aguado1242e602014-02-03 13:48:47 +0100659class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000660 def __init__(self):
661 self.retried = 0
662 self.context = None
663 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100664
Gavin Makea2e3302023-03-11 06:46:20 +0000665 def http_error_401(self, req, fp, code, msg, headers):
666 host = req.get_host()
667 retry = self.http_error_auth_reqed(
668 "www-authenticate", host, req, headers
669 )
670 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100671
Gavin Makea2e3302023-03-11 06:46:20 +0000672 def http_error_auth_reqed(self, auth_header, host, req, headers):
673 try:
674 spn = "HTTP@%s" % host
675 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100676
Gavin Makea2e3302023-03-11 06:46:20 +0000677 if self.retried > 3:
678 raise urllib.request.HTTPError(
679 req.get_full_url(),
680 401,
681 "Negotiate auth failed",
682 headers,
683 None,
684 )
685 else:
686 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100687
Gavin Makea2e3302023-03-11 06:46:20 +0000688 neghdr = self._negotiate_get_svctk(spn, authdata)
689 if neghdr is None:
690 return None
691
692 req.add_unredirected_header("Authorization", neghdr)
693 response = self.parent.open(req)
694
695 srvauth = self._negotiate_get_authdata(auth_header, response.info())
696 if self._validate_response(srvauth):
697 return response
698 except kerberos.GSSError:
699 return None
700 except Exception:
701 self.reset_retry_count()
702 raise
703 finally:
704 self._clean_context()
705
706 def reset_retry_count(self):
707 self.retried = 0
708
709 def _negotiate_get_authdata(self, auth_header, headers):
710 authhdr = headers.get(auth_header, None)
711 if authhdr is not None:
712 for mech_tuple in authhdr.split(","):
713 mech, __, authdata = mech_tuple.strip().partition(" ")
714 if mech.lower() == "negotiate":
715 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100716 return None
717
Gavin Makea2e3302023-03-11 06:46:20 +0000718 def _negotiate_get_svctk(self, spn, authdata):
719 if authdata is None:
720 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100721
Gavin Makea2e3302023-03-11 06:46:20 +0000722 result, self.context = kerberos.authGSSClientInit(spn)
723 if result < kerberos.AUTH_GSS_COMPLETE:
724 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100725
Gavin Makea2e3302023-03-11 06:46:20 +0000726 result = kerberos.authGSSClientStep(self.context, authdata)
727 if result < kerberos.AUTH_GSS_CONTINUE:
728 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100729
Gavin Makea2e3302023-03-11 06:46:20 +0000730 response = kerberos.authGSSClientResponse(self.context)
731 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100732
Gavin Makea2e3302023-03-11 06:46:20 +0000733 def _validate_response(self, authdata):
734 if authdata is None:
735 return None
736 result = kerberos.authGSSClientStep(self.context, authdata)
737 if result == kerberos.AUTH_GSS_COMPLETE:
738 return True
739 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100740
Gavin Makea2e3302023-03-11 06:46:20 +0000741 def _clean_context(self):
742 if self.context is not None:
743 kerberos.authGSSClientClean(self.context)
744 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100745
David Pursehouse819827a2020-02-12 15:20:19 +0900746
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700747def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000748 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700749
Gavin Makea2e3302023-03-11 06:46:20 +0000750 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
751 try:
752 n = netrc.netrc()
753 for host in n.hosts:
754 p = n.hosts[host]
755 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
756 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
757 except netrc.NetrcParseError:
758 pass
759 except IOError:
760 pass
761 handlers.append(_BasicAuthHandler(mgr))
762 handlers.append(_DigestAuthHandler(mgr))
763 if kerberos:
764 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700765
Gavin Makea2e3302023-03-11 06:46:20 +0000766 if "http_proxy" in os.environ:
767 url = os.environ["http_proxy"]
768 handlers.append(
769 urllib.request.ProxyHandler({"http": url, "https": url})
770 )
771 if "REPO_CURL_VERBOSE" in os.environ:
772 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
773 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
774 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700775
David Pursehouse819827a2020-02-12 15:20:19 +0900776
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700777def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000778 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400779
Gavin Makea2e3302023-03-11 06:46:20 +0000780 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
781 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
782 opt.add_option(
783 "--wrapper-version",
784 dest="wrapper_version",
785 help="version of the wrapper script",
786 )
787 opt.add_option(
788 "--wrapper-path",
789 dest="wrapper_path",
790 help="location of the wrapper script",
791 )
792 _PruneOptions(argv, opt)
793 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700794
Gavin Makea2e3302023-03-11 06:46:20 +0000795 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
796 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700797
Gavin Makea2e3302023-03-11 06:46:20 +0000798 Version.wrapper_version = opt.wrapper_version
799 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800800
Gavin Makea2e3302023-03-11 06:46:20 +0000801 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400802
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700803 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000804 init_http()
805 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400806
Gavin Makea2e3302023-03-11 06:46:20 +0000807 if gopts.trace:
808 SetTrace()
809
810 if gopts.trace_to_stderr:
811 SetTraceToStderr()
812
813 result = repo._Run(name, gopts, argv) or 0
814 except KeyboardInterrupt:
815 print("aborted by user", file=sys.stderr)
816 result = 1
817 except ManifestParseError as mpe:
818 print("fatal: %s" % mpe, file=sys.stderr)
819 result = 1
820 except RepoChangedException as rce:
821 # If repo changed, re-exec ourselves.
822 #
823 argv = list(sys.argv)
824 argv.extend(rce.extra_args)
825 try:
826 os.execv(sys.executable, [__file__] + argv)
827 except OSError as e:
828 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
829 print("fatal: %s" % e, file=sys.stderr)
830 result = 128
831
832 TerminatePager()
833 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700834
David Pursehouse819827a2020-02-12 15:20:19 +0900835
Gavin Makea2e3302023-03-11 06:46:20 +0000836if __name__ == "__main__":
837 _Main(sys.argv[1:])