blob: 47dcde19d651671a929ca03f912cb90e8b3cf41d [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
Mike Frysinger64477332023-08-21 21:20:32 -040024import json
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070025import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026import optparse
27import os
Mike Frysinger949bc342020-02-18 21:37:00 -050028import shlex
Jason Changc6578442023-06-22 15:04:06 -070029import signal
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050031import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070032import time
Mike Frysingeracf63b22019-06-13 02:24:21 -040033import urllib.request
Mike Frysinger64477332023-08-21 21:20:32 -040034
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000035from repo_logging import RepoLogger
36
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070037
Carlos Aguado1242e602014-02-03 13:48:47 +010038try:
Gavin Makea2e3302023-03-11 06:46:20 +000039 import kerberos
Carlos Aguado1242e602014-02-03 13:48:47 +010040except ImportError:
Gavin Makea2e3302023-03-11 06:46:20 +000041 kerberos = None
Carlos Aguado1242e602014-02-03 13:48:47 +010042
Mike Frysinger902665b2014-12-22 15:17:59 -050043from color import SetDefaultColoring
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080044from command import InteractiveCommand
45from command import MirrorSafeCommand
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070046from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070047from error import DownloadError
Mike Frysinger64477332023-08-21 21:20:32 -040048from error import GitcUnsupportedError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070049from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080050from error import ManifestInvalidRevisionError
LuK133789f761c2023-11-01 09:37:53 +010051from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080052from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070053from error import NoSuchProjectError
54from error import RepoChangedException
Mike Frysinger64477332023-08-21 21:20:32 -040055from error import RepoError
Jason Chang32b59562023-07-14 16:45:35 -070056from error import RepoExitError
57from error import RepoUnhandledExceptionError
Jason Chang1a3612f2023-08-08 14:12:53 -070058from error import SilentRepoExitError
Mike Frysinger64477332023-08-21 21:20:32 -040059import event_log
60from git_command import user_agent
61from git_config import RepoConfig
62from git_trace2_event_log import EventLog
Jason Chang8914b1f2023-05-26 12:44:50 -070063from manifest_xml import RepoClient
Mike Frysinger64477332023-08-21 21:20:32 -040064from pager import RunPager
65from pager import TerminatePager
66from repo_trace import SetTrace
67from repo_trace import SetTraceToStderr
68from repo_trace import Trace
David Pursehouse5c6eeac2012-10-11 16:44:48 +090069from subcmds import all_commands
Mike Frysinger64477332023-08-21 21:20:32 -040070from subcmds.version import Version
71from wrapper import Wrapper
72from wrapper import WrapperPath
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070073
Chirayu Desai217ea7d2013-03-01 19:14:38 +053074
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000075logger = RepoLogger(__file__)
76
77
Mike Frysinger37f28f12020-02-16 15:15:53 -050078# NB: These do not need to be kept in sync with the repo launcher script.
79# These may be much newer as it allows the repo launcher to roll between
80# different repo releases while source versions might require a newer python.
81#
82# The soft version is when we start warning users that the version is old and
83# we'll be dropping support for it. We'll refuse to work with versions older
84# than the hard version.
85#
86# python-3.6 is in Ubuntu Bionic.
87MIN_PYTHON_VERSION_SOFT = (3, 6)
Peter Kjellerstedta3b2edf2021-04-15 01:32:40 +020088MIN_PYTHON_VERSION_HARD = (3, 6)
Mike Frysinger37f28f12020-02-16 15:15:53 -050089
Mike Frysinger8f4f9852023-10-14 01:10:29 +054590if sys.version_info < MIN_PYTHON_VERSION_HARD:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000091 logger.error(
Mike Frysinger8f4f9852023-10-14 01:10:29 +054592 "repo: error: Python version is too old; "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000093 "Please upgrade to Python %d.%d+.",
94 *MIN_PYTHON_VERSION_SOFT,
Gavin Makea2e3302023-03-11 06:46:20 +000095 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050096 sys.exit(1)
Mike Frysinger8f4f9852023-10-14 01:10:29 +054597elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
98 logger.error(
99 "repo: warning: your Python version is no longer supported; "
100 "Please upgrade to Python %d.%d+.",
101 *MIN_PYTHON_VERSION_SOFT,
102 )
Mike Frysinger37f28f12020-02-16 15:15:53 -0500103
Jason Changc6578442023-06-22 15:04:06 -0700104KEYBOARD_INTERRUPT_EXIT = 128 + signal.SIGINT
Jason Chang32b59562023-07-14 16:45:35 -0700105MAX_PRINT_ERRORS = 5
Mike Frysinger37f28f12020-02-16 15:15:53 -0500106
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107global_options = optparse.OptionParser(
Gavin Makea2e3302023-03-11 06:46:20 +0000108 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]",
109 add_help_option=False,
110)
111global_options.add_option(
112 "-h", "--help", action="store_true", help="show this help message and exit"
113)
114global_options.add_option(
115 "--help-all",
116 action="store_true",
117 help="show this help message with all subcommands and exit",
118)
119global_options.add_option(
120 "-p",
121 "--paginate",
122 dest="pager",
123 action="store_true",
124 help="display command output in the pager",
125)
126global_options.add_option(
127 "--no-pager", dest="pager", action="store_false", help="disable the pager"
128)
129global_options.add_option(
130 "--color",
131 choices=("auto", "always", "never"),
132 default=None,
133 help="control color usage: auto, always, never",
134)
135global_options.add_option(
136 "--trace",
137 dest="trace",
138 action="store_true",
139 help="trace git command execution (REPO_TRACE=1)",
140)
141global_options.add_option(
142 "--trace-to-stderr",
143 dest="trace_to_stderr",
144 action="store_true",
145 help="trace outputs go to stderr in addition to .repo/TRACE_FILE",
146)
147global_options.add_option(
148 "--trace-python",
149 dest="trace_python",
150 action="store_true",
151 help="trace python command execution",
152)
153global_options.add_option(
154 "--time",
155 dest="time",
156 action="store_true",
157 help="time repo command execution",
158)
159global_options.add_option(
160 "--version",
161 dest="show_version",
162 action="store_true",
163 help="display this version of repo",
164)
165global_options.add_option(
166 "--show-toplevel",
167 action="store_true",
168 help="display the path of the top-level directory of "
169 "the repo client checkout",
170)
171global_options.add_option(
172 "--event-log",
173 dest="event_log",
174 action="store",
175 help="filename of event log to append timeline to",
176)
177global_options.add_option(
178 "--git-trace2-event-log",
179 action="store",
180 help="directory to write git trace2 event log to",
181)
182global_options.add_option(
183 "--submanifest-path",
184 action="store",
185 metavar="REL_PATH",
186 help="submanifest path",
187)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700188
David Pursehouse819827a2020-02-12 15:20:19 +0900189
Mike Frysingerd4aee652023-10-19 05:13:32 -0400190class _Repo:
Gavin Makea2e3302023-03-11 06:46:20 +0000191 def __init__(self, repodir):
192 self.repodir = repodir
193 self.commands = all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194
Gavin Makea2e3302023-03-11 06:46:20 +0000195 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
196 """Show --help screen."""
197 global_options.print_help()
198 print()
199 if short:
200 commands = " ".join(sorted(self.commands))
201 wrapped_commands = textwrap.wrap(commands, width=77)
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400202 help_commands = "".join(f"\n {x}" for x in wrapped_commands)
203 print(f"Available commands:{help_commands}")
Gavin Makea2e3302023-03-11 06:46:20 +0000204 print("\nRun `repo help <command>` for command-specific details.")
205 print("Bug reports:", Wrapper().BUG_URL)
Conley Owens7ba25be2012-11-14 14:18:06 -0800206 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000207 cmd = self.commands["help"]()
208 if all_commands:
209 cmd.PrintAllCommandsBody()
210 else:
211 cmd.PrintCommonCommandsBody()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400212
Gavin Makea2e3302023-03-11 06:46:20 +0000213 def _ParseArgs(self, argv):
214 """Parse the main `repo` command line options."""
215 for i, arg in enumerate(argv):
216 if not arg.startswith("-"):
217 name = arg
218 glob = argv[:i]
219 argv = argv[i + 1 :]
220 break
221 else:
222 name = None
223 glob = argv
224 argv = []
225 gopts, _gargs = global_options.parse_args(glob)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800226
Gavin Makea2e3302023-03-11 06:46:20 +0000227 if name:
228 name, alias_args = self._ExpandAlias(name)
229 argv = alias_args + argv
David Rileye0684ad2017-04-05 00:02:59 -0700230
Gavin Makea2e3302023-03-11 06:46:20 +0000231 return (name, gopts, argv)
232
233 def _ExpandAlias(self, name):
234 """Look up user registered aliases."""
235 # We don't resolve aliases for existing subcommands. This matches git.
236 if name in self.commands:
237 return name, []
238
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400239 key = f"alias.{name}"
Gavin Makea2e3302023-03-11 06:46:20 +0000240 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
241 if alias is None:
242 alias = RepoConfig.ForUser().GetString(key)
243 if alias is None:
244 return name, []
245
246 args = alias.strip().split(" ", 1)
247 name = args[0]
248 if len(args) == 2:
249 args = shlex.split(args[1])
250 else:
251 args = []
252 return name, args
253
254 def _Run(self, name, gopts, argv):
255 """Execute the requested subcommand."""
256 result = 0
257
258 # Handle options that terminate quickly first.
259 if gopts.help or gopts.help_all:
260 self._PrintHelp(short=False, all_commands=gopts.help_all)
261 return 0
262 elif gopts.show_version:
263 # Always allow global --version regardless of subcommand validity.
264 name = "version"
265 elif gopts.show_toplevel:
266 print(os.path.dirname(self.repodir))
267 return 0
268 elif not name:
269 # No subcommand specified, so show the help/subcommand.
270 self._PrintHelp(short=True)
271 return 1
272
273 run = lambda: self._RunLong(name, gopts, argv) or 0
274 with Trace(
275 "starting new command: %s",
276 ", ".join([name] + argv),
277 first_trace=True,
278 ):
279 if gopts.trace_python:
280 import trace
281
282 tracer = trace.Trace(
283 count=False,
284 trace=True,
285 timing=True,
286 ignoredirs=set(sys.path[1:]),
287 )
288 result = tracer.runfunc(run)
289 else:
290 result = run()
291 return result
292
293 def _RunLong(self, name, gopts, argv):
294 """Execute the (longer running) requested subcommand."""
295 result = 0
296 SetDefaultColoring(gopts.color)
297
298 git_trace2_event_log = EventLog()
299 outer_client = RepoClient(self.repodir)
300 repo_client = outer_client
301 if gopts.submanifest_path:
302 repo_client = RepoClient(
303 self.repodir,
304 submanifest_path=gopts.submanifest_path,
305 outer_client=outer_client,
306 )
Jason Chang8914b1f2023-05-26 12:44:50 -0700307
308 if Wrapper().gitc_parse_clientdir(os.getcwd()):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000309 logger.error("GITC is not supported.")
Jason Chang8914b1f2023-05-26 12:44:50 -0700310 raise GitcUnsupportedError()
Gavin Makea2e3302023-03-11 06:46:20 +0000311
312 try:
313 cmd = self.commands[name](
314 repodir=self.repodir,
315 client=repo_client,
316 manifest=repo_client.manifest,
317 outer_client=outer_client,
318 outer_manifest=outer_client.manifest,
Gavin Makea2e3302023-03-11 06:46:20 +0000319 git_event_log=git_trace2_event_log,
320 )
321 except KeyError:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000322 logger.error(
323 "repo: '%s' is not a repo command. See 'repo help'.", name
Gavin Makea2e3302023-03-11 06:46:20 +0000324 )
325 return 1
326
327 Editor.globalConfig = cmd.client.globalConfig
328
329 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000330 logger.error("fatal: '%s' requires a working directory", name)
Gavin Makea2e3302023-03-11 06:46:20 +0000331 return 1
332
Gavin Makea2e3302023-03-11 06:46:20 +0000333 try:
334 copts, cargs = cmd.OptionParser.parse_args(argv)
335 copts = cmd.ReadEnvironmentOptions(copts)
336 except NoManifestException as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000337 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
338 logger.error(
339 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000340 )
341 return 1
342
343 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
344 config = cmd.client.globalConfig
345 if gopts.pager:
346 use_pager = True
347 else:
348 use_pager = config.GetBoolean("pager.%s" % name)
349 if use_pager is None:
350 use_pager = cmd.WantPager(copts)
351 if use_pager:
352 RunPager(config)
353
354 start = time.time()
355 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
356 cmd.event_log.SetParent(cmd_event)
357 git_trace2_event_log.StartEvent()
358 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
359
Jason Changc6578442023-06-22 15:04:06 -0700360 def execute_command_helper():
361 """
362 Execute the subcommand.
363 """
364 nonlocal result
Gavin Makea2e3302023-03-11 06:46:20 +0000365 cmd.CommonValidateOptions(copts, cargs)
366 cmd.ValidateOptions(copts, cargs)
367
368 this_manifest_only = copts.this_manifest_only
369 outer_manifest = copts.outer_manifest
370 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
371 result = cmd.Execute(copts, cargs)
372 elif outer_manifest and repo_client.manifest.is_submanifest:
373 # The command does not support multi-manifest, we are using a
374 # submanifest, and the command line is for the outermost
375 # manifest. Re-run using the outermost manifest, which will
376 # recurse through the submanifests.
377 gopts.submanifest_path = ""
378 result = self._Run(name, gopts, argv)
379 else:
380 # No multi-manifest support. Run the command in the current
381 # (sub)manifest, and then any child submanifests.
382 result = cmd.Execute(copts, cargs)
383 for submanifest in repo_client.manifest.submanifests.values():
384 spec = submanifest.ToSubmanifestSpec()
385 gopts.submanifest_path = submanifest.repo_client.path_prefix
386 child_argv = argv[:]
387 child_argv.append("--no-outer-manifest")
388 # Not all subcommands support the 3 manifest options, so
389 # only add them if the original command includes them.
390 if hasattr(copts, "manifest_url"):
391 child_argv.extend(["--manifest-url", spec.manifestUrl])
392 if hasattr(copts, "manifest_name"):
393 child_argv.extend(
394 ["--manifest-name", spec.manifestName]
395 )
396 if hasattr(copts, "manifest_branch"):
397 child_argv.extend(["--manifest-branch", spec.revision])
398 result = self._Run(name, gopts, child_argv) or result
Jason Changc6578442023-06-22 15:04:06 -0700399
400 def execute_command():
401 """
402 Execute the command and log uncaught exceptions.
403 """
404 try:
405 execute_command_helper()
Jason Chang32b59562023-07-14 16:45:35 -0700406 except (
407 KeyboardInterrupt,
408 SystemExit,
409 Exception,
410 RepoExitError,
411 ) as e:
Jason Changc6578442023-06-22 15:04:06 -0700412 ok = isinstance(e, SystemExit) and not e.code
Jason Chang32b59562023-07-14 16:45:35 -0700413 exception_name = type(e).__name__
414 if isinstance(e, RepoUnhandledExceptionError):
415 exception_name = type(e.error).__name__
416 if isinstance(e, RepoExitError):
417 aggregated_errors = e.aggregate_errors or []
418 for error in aggregated_errors:
419 project = None
420 if isinstance(error, RepoError):
421 project = error.project
422 error_info = json.dumps(
423 {
424 "ErrorType": type(error).__name__,
425 "Project": project,
426 "Message": str(error),
427 }
428 )
429 git_trace2_event_log.ErrorEvent(
430 f"AggregateExitError:{error_info}"
431 )
Jason Changc6578442023-06-22 15:04:06 -0700432 if not ok:
Jason Changc6578442023-06-22 15:04:06 -0700433 git_trace2_event_log.ErrorEvent(
Gavin Mak1d2e99d2023-07-22 02:56:44 +0000434 f"RepoExitError:{exception_name}"
435 )
Jason Changc6578442023-06-22 15:04:06 -0700436 raise
437
438 try:
439 execute_command()
Gavin Makea2e3302023-03-11 06:46:20 +0000440 except (
441 DownloadError,
442 ManifestInvalidRevisionError,
LuK133789f761c2023-11-01 09:37:53 +0100443 ManifestParseError,
Gavin Makea2e3302023-03-11 06:46:20 +0000444 NoManifestException,
445 ) as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000446 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
Gavin Makea2e3302023-03-11 06:46:20 +0000447 if isinstance(e, NoManifestException):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000448 logger.error(
449 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000450 )
Jason Chang32b59562023-07-14 16:45:35 -0700451 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000452 except NoSuchProjectError as e:
453 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000454 logger.error("error: project %s not found", e.name)
Gavin Makea2e3302023-03-11 06:46:20 +0000455 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000456 logger.error("error: no project in current directory")
Jason Chang32b59562023-07-14 16:45:35 -0700457 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000458 except InvalidProjectGroupsError as e:
459 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000460 logger.error(
461 "error: project group must be enabled for project %s",
462 e.name,
Gavin Makea2e3302023-03-11 06:46:20 +0000463 )
464 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000465 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000466 "error: project group must be enabled for the project in "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000467 "the current directory"
Gavin Makea2e3302023-03-11 06:46:20 +0000468 )
Jason Chang32b59562023-07-14 16:45:35 -0700469 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000470 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
Jason Chang32b59562023-07-14 16:45:35 -0700477 except RepoExitError as e:
478 result = e.exit_code
479 raise
Jason Changc6578442023-06-22 15:04:06 -0700480 except Exception:
481 result = 1
482 raise
Gavin Makea2e3302023-03-11 06:46:20 +0000483 finally:
484 finish = time.time()
485 elapsed = finish - start
486 hours, remainder = divmod(elapsed, 3600)
487 minutes, seconds = divmod(remainder, 60)
488 if gopts.time:
489 if hours == 0:
490 print(
491 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
492 )
493 else:
494 print(
495 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
496 file=sys.stderr,
497 )
498
499 cmd.event_log.FinishEvent(
500 cmd_event, finish, result is None or result == 0
501 )
502 git_trace2_event_log.DefParamRepoEvents(
503 cmd.manifest.manifestProject.config.DumpConfigDict()
504 )
505 git_trace2_event_log.ExitEvent(result)
506
507 if gopts.event_log:
508 cmd.event_log.Write(
509 os.path.abspath(os.path.expanduser(gopts.event_log))
510 )
511
512 git_trace2_event_log.Write(gopts.git_trace2_event_log)
513 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700514
Conley Owens094cdbe2014-01-30 15:09:59 -0800515
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500516def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000517 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500518
Gavin Makea2e3302023-03-11 06:46:20 +0000519 Args:
520 ver_str: The version string passed from the repo launcher when it ran
521 us.
522 repo_path: The path to the repo launcher that loaded us.
523 """
524 # Refuse to work with really old wrapper versions. We don't test these,
525 # so might as well require a somewhat recent sane version.
526 # v1.15 of the repo launcher was released in ~Mar 2012.
527 MIN_REPO_VERSION = (1, 15)
528 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500529
Gavin Makea2e3302023-03-11 06:46:20 +0000530 if not repo_path:
531 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700532
Gavin Makea2e3302023-03-11 06:46:20 +0000533 if not ver_str:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000534 logger.error("no --wrapper-version argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000535 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700536
Gavin Makea2e3302023-03-11 06:46:20 +0000537 # Pull out the version of the repo launcher we know about to compare.
538 exp = Wrapper().VERSION
539 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700540
Gavin Makea2e3302023-03-11 06:46:20 +0000541 exp_str = ".".join(map(str, exp))
542 if ver < MIN_REPO_VERSION:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000543 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000544 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500545repo: error:
546!!! Your version of repo %s is too old.
547!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900548!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500549!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700550
551 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000552""",
553 ver_str,
554 min_str,
555 exp_str,
556 WrapperPath(),
557 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000558 )
559 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700560
Gavin Makea2e3302023-03-11 06:46:20 +0000561 if exp > ver:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000562 logger.warning(
563 "\n... A new version of repo (%s) is available.", exp_str
564 )
Gavin Makea2e3302023-03-11 06:46:20 +0000565 if os.access(repo_path, os.W_OK):
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000566 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000567 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700568... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700569 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000570""",
571 WrapperPath(),
572 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000573 )
574 else:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000575 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000576 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500577... New version is available at: %s
578... The launcher is run from: %s
579!!! The launcher is not writable. Please talk to your sysadmin or distro
580!!! to get an update installed.
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000581""",
582 WrapperPath(),
583 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000584 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700585
David Pursehouse819827a2020-02-12 15:20:19 +0900586
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200587def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000588 if not repo_dir:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000589 logger.error("no --repo-dir argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000590 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700591
David Pursehouse819827a2020-02-12 15:20:19 +0900592
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700593def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000594 i = 0
595 while i < len(argv):
596 a = argv[i]
597 if a == "--":
598 break
599 if a.startswith("--"):
600 eq = a.find("=")
601 if eq > 0:
602 a = a[0:eq]
603 if not opt.has_option(a):
604 del argv[i]
605 continue
606 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700607
David Pursehouse819827a2020-02-12 15:20:19 +0900608
Sarah Owens1f7627f2012-10-31 09:21:55 -0700609class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000610 def http_request(self, req):
611 req.add_header("User-Agent", user_agent.repo)
612 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700613
Gavin Makea2e3302023-03-11 06:46:20 +0000614 def https_request(self, req):
615 req.add_header("User-Agent", user_agent.repo)
616 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700617
David Pursehouse819827a2020-02-12 15:20:19 +0900618
JoonCheol Parke9860722012-10-11 02:31:44 +0900619def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000620 # If repo could not find auth info from netrc, try to get it from user input
621 url = req.get_full_url()
622 user, password = handler.passwd.find_user_password(None, url)
623 if user is None:
624 print(msg)
625 try:
626 user = input("User: ")
627 password = getpass.getpass()
628 except KeyboardInterrupt:
629 return
630 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900631
David Pursehouse819827a2020-02-12 15:20:19 +0900632
Sarah Owens1f7627f2012-10-31 09:21:55 -0700633class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000634 def http_error_401(self, req, fp, code, msg, headers):
635 _AddPasswordFromUserInput(self, msg, req)
636 return urllib.request.HTTPBasicAuthHandler.http_error_401(
637 self, req, fp, code, msg, headers
638 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900639
Gavin Makea2e3302023-03-11 06:46:20 +0000640 def http_error_auth_reqed(self, authreq, host, req, headers):
641 try:
642 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900643
Gavin Makea2e3302023-03-11 06:46:20 +0000644 def _add_header(name, val):
645 val = val.replace("\n", "")
646 old_add_header(name, val)
647
648 req.add_header = _add_header
649 return (
650 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
651 self, authreq, host, req, headers
652 )
653 )
654 except Exception:
655 reset = getattr(self, "reset_retry_count", None)
656 if reset is not None:
657 reset()
658 elif getattr(self, "retried", None):
659 self.retried = 0
660 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700661
David Pursehouse819827a2020-02-12 15:20:19 +0900662
Sarah Owens1f7627f2012-10-31 09:21:55 -0700663class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000664 def http_error_401(self, req, fp, code, msg, headers):
665 _AddPasswordFromUserInput(self, msg, req)
666 return urllib.request.HTTPDigestAuthHandler.http_error_401(
667 self, req, fp, code, msg, headers
668 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900669
Gavin Makea2e3302023-03-11 06:46:20 +0000670 def http_error_auth_reqed(self, auth_header, host, req, headers):
671 try:
672 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900673
Gavin Makea2e3302023-03-11 06:46:20 +0000674 def _add_header(name, val):
675 val = val.replace("\n", "")
676 old_add_header(name, val)
677
678 req.add_header = _add_header
679 return (
680 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
681 self, auth_header, host, req, headers
682 )
683 )
684 except Exception:
685 reset = getattr(self, "reset_retry_count", None)
686 if reset is not None:
687 reset()
688 elif getattr(self, "retried", None):
689 self.retried = 0
690 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800691
David Pursehouse819827a2020-02-12 15:20:19 +0900692
Carlos Aguado1242e602014-02-03 13:48:47 +0100693class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000694 def __init__(self):
695 self.retried = 0
696 self.context = None
697 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100698
Gavin Makea2e3302023-03-11 06:46:20 +0000699 def http_error_401(self, req, fp, code, msg, headers):
700 host = req.get_host()
701 retry = self.http_error_auth_reqed(
702 "www-authenticate", host, req, headers
703 )
704 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100705
Gavin Makea2e3302023-03-11 06:46:20 +0000706 def http_error_auth_reqed(self, auth_header, host, req, headers):
707 try:
708 spn = "HTTP@%s" % host
709 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100710
Gavin Makea2e3302023-03-11 06:46:20 +0000711 if self.retried > 3:
712 raise urllib.request.HTTPError(
713 req.get_full_url(),
714 401,
715 "Negotiate auth failed",
716 headers,
717 None,
718 )
719 else:
720 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100721
Gavin Makea2e3302023-03-11 06:46:20 +0000722 neghdr = self._negotiate_get_svctk(spn, authdata)
723 if neghdr is None:
724 return None
725
726 req.add_unredirected_header("Authorization", neghdr)
727 response = self.parent.open(req)
728
729 srvauth = self._negotiate_get_authdata(auth_header, response.info())
730 if self._validate_response(srvauth):
731 return response
732 except kerberos.GSSError:
733 return None
734 except Exception:
735 self.reset_retry_count()
736 raise
737 finally:
738 self._clean_context()
739
740 def reset_retry_count(self):
741 self.retried = 0
742
743 def _negotiate_get_authdata(self, auth_header, headers):
744 authhdr = headers.get(auth_header, None)
745 if authhdr is not None:
746 for mech_tuple in authhdr.split(","):
747 mech, __, authdata = mech_tuple.strip().partition(" ")
748 if mech.lower() == "negotiate":
749 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100750 return None
751
Gavin Makea2e3302023-03-11 06:46:20 +0000752 def _negotiate_get_svctk(self, spn, authdata):
753 if authdata is None:
754 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100755
Gavin Makea2e3302023-03-11 06:46:20 +0000756 result, self.context = kerberos.authGSSClientInit(spn)
757 if result < kerberos.AUTH_GSS_COMPLETE:
758 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100759
Gavin Makea2e3302023-03-11 06:46:20 +0000760 result = kerberos.authGSSClientStep(self.context, authdata)
761 if result < kerberos.AUTH_GSS_CONTINUE:
762 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100763
Gavin Makea2e3302023-03-11 06:46:20 +0000764 response = kerberos.authGSSClientResponse(self.context)
765 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100766
Gavin Makea2e3302023-03-11 06:46:20 +0000767 def _validate_response(self, authdata):
768 if authdata is None:
769 return None
770 result = kerberos.authGSSClientStep(self.context, authdata)
771 if result == kerberos.AUTH_GSS_COMPLETE:
772 return True
773 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100774
Gavin Makea2e3302023-03-11 06:46:20 +0000775 def _clean_context(self):
776 if self.context is not None:
777 kerberos.authGSSClientClean(self.context)
778 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100779
David Pursehouse819827a2020-02-12 15:20:19 +0900780
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700781def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000782 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700783
Gavin Makea2e3302023-03-11 06:46:20 +0000784 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
785 try:
786 n = netrc.netrc()
787 for host in n.hosts:
788 p = n.hosts[host]
789 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
790 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
791 except netrc.NetrcParseError:
792 pass
Jason R. Coombsae824fb2023-10-20 23:32:40 +0545793 except OSError:
Gavin Makea2e3302023-03-11 06:46:20 +0000794 pass
795 handlers.append(_BasicAuthHandler(mgr))
796 handlers.append(_DigestAuthHandler(mgr))
797 if kerberos:
798 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700799
Gavin Makea2e3302023-03-11 06:46:20 +0000800 if "http_proxy" in os.environ:
801 url = os.environ["http_proxy"]
802 handlers.append(
803 urllib.request.ProxyHandler({"http": url, "https": url})
804 )
805 if "REPO_CURL_VERBOSE" in os.environ:
806 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
807 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
808 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700809
David Pursehouse819827a2020-02-12 15:20:19 +0900810
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700811def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000812 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400813
Gavin Makea2e3302023-03-11 06:46:20 +0000814 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
815 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
816 opt.add_option(
817 "--wrapper-version",
818 dest="wrapper_version",
819 help="version of the wrapper script",
820 )
821 opt.add_option(
822 "--wrapper-path",
823 dest="wrapper_path",
824 help="location of the wrapper script",
825 )
826 _PruneOptions(argv, opt)
827 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700828
Gavin Makea2e3302023-03-11 06:46:20 +0000829 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
830 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700831
Gavin Makea2e3302023-03-11 06:46:20 +0000832 Version.wrapper_version = opt.wrapper_version
833 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800834
Gavin Makea2e3302023-03-11 06:46:20 +0000835 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400836
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700837 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000838 init_http()
839 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400840
Gavin Makea2e3302023-03-11 06:46:20 +0000841 if gopts.trace:
842 SetTrace()
843
844 if gopts.trace_to_stderr:
845 SetTraceToStderr()
846
847 result = repo._Run(name, gopts, argv) or 0
Jason Chang32b59562023-07-14 16:45:35 -0700848 except RepoExitError as e:
Jason Chang1a3612f2023-08-08 14:12:53 -0700849 if not isinstance(e, SilentRepoExitError):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000850 logger.log_aggregated_errors(e)
Jason Chang32b59562023-07-14 16:45:35 -0700851 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000852 except KeyboardInterrupt:
853 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700854 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000855 except RepoChangedException as rce:
856 # If repo changed, re-exec ourselves.
Gavin Makea2e3302023-03-11 06:46:20 +0000857 argv = list(sys.argv)
858 argv.extend(rce.extra_args)
859 try:
Gavin Makf1ddaaa2023-08-04 21:13:38 +0000860 os.execv(sys.executable, [sys.executable, __file__] + argv)
Gavin Makea2e3302023-03-11 06:46:20 +0000861 except OSError as e:
862 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
863 print("fatal: %s" % e, file=sys.stderr)
864 result = 128
865
866 TerminatePager()
867 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700868
David Pursehouse819827a2020-02-12 15:20:19 +0900869
Gavin Makea2e3302023-03-11 06:46:20 +0000870if __name__ == "__main__":
871 _Main(sys.argv[1:])