blob: 2e1058d49e144d414c4d5af61e7dcb44aeee8d99 [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
Josip Sokcevic8896b682024-02-21 11:04:03 -0800273 git_trace2_event_log = EventLog()
274 run = (
275 lambda: self._RunLong(name, gopts, argv, git_trace2_event_log) or 0
276 )
Gavin Makea2e3302023-03-11 06:46:20 +0000277 with Trace(
Josip Sokcevic8896b682024-02-21 11:04:03 -0800278 "starting new command: %s [sid=%s]",
Gavin Makea2e3302023-03-11 06:46:20 +0000279 ", ".join([name] + argv),
Josip Sokcevic8896b682024-02-21 11:04:03 -0800280 git_trace2_event_log.full_sid,
Gavin Makea2e3302023-03-11 06:46:20 +0000281 first_trace=True,
282 ):
283 if gopts.trace_python:
284 import trace
285
286 tracer = trace.Trace(
287 count=False,
288 trace=True,
289 timing=True,
290 ignoredirs=set(sys.path[1:]),
291 )
292 result = tracer.runfunc(run)
293 else:
294 result = run()
295 return result
296
Josip Sokcevic8896b682024-02-21 11:04:03 -0800297 def _RunLong(self, name, gopts, argv, git_trace2_event_log):
Gavin Makea2e3302023-03-11 06:46:20 +0000298 """Execute the (longer running) requested subcommand."""
299 result = 0
300 SetDefaultColoring(gopts.color)
301
Gavin Makea2e3302023-03-11 06:46:20 +0000302 outer_client = RepoClient(self.repodir)
303 repo_client = outer_client
304 if gopts.submanifest_path:
305 repo_client = RepoClient(
306 self.repodir,
307 submanifest_path=gopts.submanifest_path,
308 outer_client=outer_client,
309 )
Jason Chang8914b1f2023-05-26 12:44:50 -0700310
311 if Wrapper().gitc_parse_clientdir(os.getcwd()):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000312 logger.error("GITC is not supported.")
Jason Chang8914b1f2023-05-26 12:44:50 -0700313 raise GitcUnsupportedError()
Gavin Makea2e3302023-03-11 06:46:20 +0000314
315 try:
316 cmd = self.commands[name](
317 repodir=self.repodir,
318 client=repo_client,
319 manifest=repo_client.manifest,
320 outer_client=outer_client,
321 outer_manifest=outer_client.manifest,
Gavin Makea2e3302023-03-11 06:46:20 +0000322 git_event_log=git_trace2_event_log,
323 )
324 except KeyError:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000325 logger.error(
326 "repo: '%s' is not a repo command. See 'repo help'.", name
Gavin Makea2e3302023-03-11 06:46:20 +0000327 )
328 return 1
329
330 Editor.globalConfig = cmd.client.globalConfig
331
332 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000333 logger.error("fatal: '%s' requires a working directory", name)
Gavin Makea2e3302023-03-11 06:46:20 +0000334 return 1
335
Gavin Makea2e3302023-03-11 06:46:20 +0000336 try:
337 copts, cargs = cmd.OptionParser.parse_args(argv)
338 copts = cmd.ReadEnvironmentOptions(copts)
339 except NoManifestException as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000340 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
341 logger.error(
342 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000343 )
344 return 1
345
346 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
347 config = cmd.client.globalConfig
348 if gopts.pager:
349 use_pager = True
350 else:
351 use_pager = config.GetBoolean("pager.%s" % name)
352 if use_pager is None:
353 use_pager = cmd.WantPager(copts)
354 if use_pager:
355 RunPager(config)
356
357 start = time.time()
358 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
359 cmd.event_log.SetParent(cmd_event)
360 git_trace2_event_log.StartEvent()
361 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
362
Jason Changc6578442023-06-22 15:04:06 -0700363 def execute_command_helper():
364 """
365 Execute the subcommand.
366 """
367 nonlocal result
Gavin Makea2e3302023-03-11 06:46:20 +0000368 cmd.CommonValidateOptions(copts, cargs)
369 cmd.ValidateOptions(copts, cargs)
370
371 this_manifest_only = copts.this_manifest_only
372 outer_manifest = copts.outer_manifest
373 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
374 result = cmd.Execute(copts, cargs)
375 elif outer_manifest and repo_client.manifest.is_submanifest:
376 # The command does not support multi-manifest, we are using a
377 # submanifest, and the command line is for the outermost
378 # manifest. Re-run using the outermost manifest, which will
379 # recurse through the submanifests.
380 gopts.submanifest_path = ""
381 result = self._Run(name, gopts, argv)
382 else:
383 # No multi-manifest support. Run the command in the current
384 # (sub)manifest, and then any child submanifests.
385 result = cmd.Execute(copts, cargs)
386 for submanifest in repo_client.manifest.submanifests.values():
387 spec = submanifest.ToSubmanifestSpec()
388 gopts.submanifest_path = submanifest.repo_client.path_prefix
389 child_argv = argv[:]
390 child_argv.append("--no-outer-manifest")
391 # Not all subcommands support the 3 manifest options, so
392 # only add them if the original command includes them.
393 if hasattr(copts, "manifest_url"):
394 child_argv.extend(["--manifest-url", spec.manifestUrl])
395 if hasattr(copts, "manifest_name"):
396 child_argv.extend(
397 ["--manifest-name", spec.manifestName]
398 )
399 if hasattr(copts, "manifest_branch"):
400 child_argv.extend(["--manifest-branch", spec.revision])
401 result = self._Run(name, gopts, child_argv) or result
Jason Changc6578442023-06-22 15:04:06 -0700402
403 def execute_command():
404 """
405 Execute the command and log uncaught exceptions.
406 """
407 try:
408 execute_command_helper()
Jason Chang32b59562023-07-14 16:45:35 -0700409 except (
410 KeyboardInterrupt,
411 SystemExit,
412 Exception,
413 RepoExitError,
414 ) as e:
Jason Changc6578442023-06-22 15:04:06 -0700415 ok = isinstance(e, SystemExit) and not e.code
Jason Chang32b59562023-07-14 16:45:35 -0700416 exception_name = type(e).__name__
417 if isinstance(e, RepoUnhandledExceptionError):
418 exception_name = type(e.error).__name__
419 if isinstance(e, RepoExitError):
420 aggregated_errors = e.aggregate_errors or []
421 for error in aggregated_errors:
422 project = None
423 if isinstance(error, RepoError):
424 project = error.project
425 error_info = json.dumps(
426 {
427 "ErrorType": type(error).__name__,
428 "Project": project,
429 "Message": str(error),
430 }
431 )
432 git_trace2_event_log.ErrorEvent(
433 f"AggregateExitError:{error_info}"
434 )
Jason Changc6578442023-06-22 15:04:06 -0700435 if not ok:
Jason Changc6578442023-06-22 15:04:06 -0700436 git_trace2_event_log.ErrorEvent(
Gavin Mak1d2e99d2023-07-22 02:56:44 +0000437 f"RepoExitError:{exception_name}"
438 )
Jason Changc6578442023-06-22 15:04:06 -0700439 raise
440
441 try:
442 execute_command()
Gavin Makea2e3302023-03-11 06:46:20 +0000443 except (
444 DownloadError,
445 ManifestInvalidRevisionError,
LuK133789f761c2023-11-01 09:37:53 +0100446 ManifestParseError,
Gavin Makea2e3302023-03-11 06:46:20 +0000447 NoManifestException,
448 ) as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000449 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
Gavin Makea2e3302023-03-11 06:46:20 +0000450 if isinstance(e, NoManifestException):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000451 logger.error(
452 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000453 )
Jason Chang32b59562023-07-14 16:45:35 -0700454 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000455 except NoSuchProjectError as e:
456 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000457 logger.error("error: project %s not found", e.name)
Gavin Makea2e3302023-03-11 06:46:20 +0000458 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000459 logger.error("error: no project in current directory")
Jason Chang32b59562023-07-14 16:45:35 -0700460 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000461 except InvalidProjectGroupsError as e:
462 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000463 logger.error(
464 "error: project group must be enabled for project %s",
465 e.name,
Gavin Makea2e3302023-03-11 06:46:20 +0000466 )
467 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000468 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000469 "error: project group must be enabled for the project in "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000470 "the current directory"
Gavin Makea2e3302023-03-11 06:46:20 +0000471 )
Jason Chang32b59562023-07-14 16:45:35 -0700472 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000473 except SystemExit as e:
474 if e.code:
475 result = e.code
476 raise
Jason Changc6578442023-06-22 15:04:06 -0700477 except KeyboardInterrupt:
478 result = KEYBOARD_INTERRUPT_EXIT
479 raise
Jason Chang32b59562023-07-14 16:45:35 -0700480 except RepoExitError as e:
481 result = e.exit_code
482 raise
Jason Changc6578442023-06-22 15:04:06 -0700483 except Exception:
484 result = 1
485 raise
Gavin Makea2e3302023-03-11 06:46:20 +0000486 finally:
487 finish = time.time()
488 elapsed = finish - start
489 hours, remainder = divmod(elapsed, 3600)
490 minutes, seconds = divmod(remainder, 60)
491 if gopts.time:
492 if hours == 0:
493 print(
494 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
495 )
496 else:
497 print(
498 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
499 file=sys.stderr,
500 )
501
502 cmd.event_log.FinishEvent(
503 cmd_event, finish, result is None or result == 0
504 )
505 git_trace2_event_log.DefParamRepoEvents(
506 cmd.manifest.manifestProject.config.DumpConfigDict()
507 )
508 git_trace2_event_log.ExitEvent(result)
509
510 if gopts.event_log:
511 cmd.event_log.Write(
512 os.path.abspath(os.path.expanduser(gopts.event_log))
513 )
514
515 git_trace2_event_log.Write(gopts.git_trace2_event_log)
516 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700517
Conley Owens094cdbe2014-01-30 15:09:59 -0800518
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500519def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000520 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500521
Gavin Makea2e3302023-03-11 06:46:20 +0000522 Args:
523 ver_str: The version string passed from the repo launcher when it ran
524 us.
525 repo_path: The path to the repo launcher that loaded us.
526 """
527 # Refuse to work with really old wrapper versions. We don't test these,
528 # so might as well require a somewhat recent sane version.
529 # v1.15 of the repo launcher was released in ~Mar 2012.
530 MIN_REPO_VERSION = (1, 15)
531 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500532
Gavin Makea2e3302023-03-11 06:46:20 +0000533 if not repo_path:
534 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700535
Gavin Makea2e3302023-03-11 06:46:20 +0000536 if not ver_str:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000537 logger.error("no --wrapper-version argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000538 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539
Gavin Makea2e3302023-03-11 06:46:20 +0000540 # Pull out the version of the repo launcher we know about to compare.
541 exp = Wrapper().VERSION
542 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543
Gavin Makea2e3302023-03-11 06:46:20 +0000544 exp_str = ".".join(map(str, exp))
545 if ver < MIN_REPO_VERSION:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000546 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000547 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500548repo: error:
549!!! Your version of repo %s is too old.
550!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900551!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500552!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700553
554 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000555""",
556 ver_str,
557 min_str,
558 exp_str,
559 WrapperPath(),
560 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000561 )
562 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700563
Gavin Makea2e3302023-03-11 06:46:20 +0000564 if exp > ver:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000565 logger.warning(
566 "\n... A new version of repo (%s) is available.", exp_str
567 )
Gavin Makea2e3302023-03-11 06:46:20 +0000568 if os.access(repo_path, os.W_OK):
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000569 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000570 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700571... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700572 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000573""",
574 WrapperPath(),
575 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000576 )
577 else:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000578 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000579 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500580... New version is available at: %s
581... The launcher is run from: %s
582!!! The launcher is not writable. Please talk to your sysadmin or distro
583!!! to get an update installed.
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000584""",
585 WrapperPath(),
586 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000587 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700588
David Pursehouse819827a2020-02-12 15:20:19 +0900589
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200590def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000591 if not repo_dir:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000592 logger.error("no --repo-dir argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000593 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700594
David Pursehouse819827a2020-02-12 15:20:19 +0900595
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700596def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000597 i = 0
598 while i < len(argv):
599 a = argv[i]
600 if a == "--":
601 break
602 if a.startswith("--"):
603 eq = a.find("=")
604 if eq > 0:
605 a = a[0:eq]
606 if not opt.has_option(a):
607 del argv[i]
608 continue
609 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700610
David Pursehouse819827a2020-02-12 15:20:19 +0900611
Sarah Owens1f7627f2012-10-31 09:21:55 -0700612class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000613 def http_request(self, req):
614 req.add_header("User-Agent", user_agent.repo)
615 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700616
Gavin Makea2e3302023-03-11 06:46:20 +0000617 def https_request(self, req):
618 req.add_header("User-Agent", user_agent.repo)
619 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700620
David Pursehouse819827a2020-02-12 15:20:19 +0900621
JoonCheol Parke9860722012-10-11 02:31:44 +0900622def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000623 # If repo could not find auth info from netrc, try to get it from user input
624 url = req.get_full_url()
625 user, password = handler.passwd.find_user_password(None, url)
626 if user is None:
627 print(msg)
628 try:
629 user = input("User: ")
630 password = getpass.getpass()
631 except KeyboardInterrupt:
632 return
633 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900634
David Pursehouse819827a2020-02-12 15:20:19 +0900635
Sarah Owens1f7627f2012-10-31 09:21:55 -0700636class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000637 def http_error_401(self, req, fp, code, msg, headers):
638 _AddPasswordFromUserInput(self, msg, req)
639 return urllib.request.HTTPBasicAuthHandler.http_error_401(
640 self, req, fp, code, msg, headers
641 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900642
Gavin Makea2e3302023-03-11 06:46:20 +0000643 def http_error_auth_reqed(self, authreq, host, req, headers):
644 try:
645 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900646
Gavin Makea2e3302023-03-11 06:46:20 +0000647 def _add_header(name, val):
648 val = val.replace("\n", "")
649 old_add_header(name, val)
650
651 req.add_header = _add_header
652 return (
653 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
654 self, authreq, host, req, headers
655 )
656 )
657 except Exception:
658 reset = getattr(self, "reset_retry_count", None)
659 if reset is not None:
660 reset()
661 elif getattr(self, "retried", None):
662 self.retried = 0
663 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700664
David Pursehouse819827a2020-02-12 15:20:19 +0900665
Sarah Owens1f7627f2012-10-31 09:21:55 -0700666class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000667 def http_error_401(self, req, fp, code, msg, headers):
668 _AddPasswordFromUserInput(self, msg, req)
669 return urllib.request.HTTPDigestAuthHandler.http_error_401(
670 self, req, fp, code, msg, headers
671 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900672
Gavin Makea2e3302023-03-11 06:46:20 +0000673 def http_error_auth_reqed(self, auth_header, host, req, headers):
674 try:
675 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900676
Gavin Makea2e3302023-03-11 06:46:20 +0000677 def _add_header(name, val):
678 val = val.replace("\n", "")
679 old_add_header(name, val)
680
681 req.add_header = _add_header
682 return (
683 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
684 self, auth_header, host, req, headers
685 )
686 )
687 except Exception:
688 reset = getattr(self, "reset_retry_count", None)
689 if reset is not None:
690 reset()
691 elif getattr(self, "retried", None):
692 self.retried = 0
693 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800694
David Pursehouse819827a2020-02-12 15:20:19 +0900695
Carlos Aguado1242e602014-02-03 13:48:47 +0100696class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000697 def __init__(self):
698 self.retried = 0
699 self.context = None
700 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100701
Gavin Makea2e3302023-03-11 06:46:20 +0000702 def http_error_401(self, req, fp, code, msg, headers):
703 host = req.get_host()
704 retry = self.http_error_auth_reqed(
705 "www-authenticate", host, req, headers
706 )
707 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100708
Gavin Makea2e3302023-03-11 06:46:20 +0000709 def http_error_auth_reqed(self, auth_header, host, req, headers):
710 try:
711 spn = "HTTP@%s" % host
712 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100713
Gavin Makea2e3302023-03-11 06:46:20 +0000714 if self.retried > 3:
715 raise urllib.request.HTTPError(
716 req.get_full_url(),
717 401,
718 "Negotiate auth failed",
719 headers,
720 None,
721 )
722 else:
723 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100724
Gavin Makea2e3302023-03-11 06:46:20 +0000725 neghdr = self._negotiate_get_svctk(spn, authdata)
726 if neghdr is None:
727 return None
728
729 req.add_unredirected_header("Authorization", neghdr)
730 response = self.parent.open(req)
731
732 srvauth = self._negotiate_get_authdata(auth_header, response.info())
733 if self._validate_response(srvauth):
734 return response
735 except kerberos.GSSError:
736 return None
737 except Exception:
738 self.reset_retry_count()
739 raise
740 finally:
741 self._clean_context()
742
743 def reset_retry_count(self):
744 self.retried = 0
745
746 def _negotiate_get_authdata(self, auth_header, headers):
747 authhdr = headers.get(auth_header, None)
748 if authhdr is not None:
749 for mech_tuple in authhdr.split(","):
750 mech, __, authdata = mech_tuple.strip().partition(" ")
751 if mech.lower() == "negotiate":
752 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100753 return None
754
Gavin Makea2e3302023-03-11 06:46:20 +0000755 def _negotiate_get_svctk(self, spn, authdata):
756 if authdata is None:
757 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100758
Gavin Makea2e3302023-03-11 06:46:20 +0000759 result, self.context = kerberos.authGSSClientInit(spn)
760 if result < kerberos.AUTH_GSS_COMPLETE:
761 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100762
Gavin Makea2e3302023-03-11 06:46:20 +0000763 result = kerberos.authGSSClientStep(self.context, authdata)
764 if result < kerberos.AUTH_GSS_CONTINUE:
765 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100766
Gavin Makea2e3302023-03-11 06:46:20 +0000767 response = kerberos.authGSSClientResponse(self.context)
768 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100769
Gavin Makea2e3302023-03-11 06:46:20 +0000770 def _validate_response(self, authdata):
771 if authdata is None:
772 return None
773 result = kerberos.authGSSClientStep(self.context, authdata)
774 if result == kerberos.AUTH_GSS_COMPLETE:
775 return True
776 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100777
Gavin Makea2e3302023-03-11 06:46:20 +0000778 def _clean_context(self):
779 if self.context is not None:
780 kerberos.authGSSClientClean(self.context)
781 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100782
David Pursehouse819827a2020-02-12 15:20:19 +0900783
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700784def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000785 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700786
Gavin Makea2e3302023-03-11 06:46:20 +0000787 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
788 try:
789 n = netrc.netrc()
790 for host in n.hosts:
791 p = n.hosts[host]
792 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
793 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
794 except netrc.NetrcParseError:
795 pass
Jason R. Coombsae824fb2023-10-20 23:32:40 +0545796 except OSError:
Gavin Makea2e3302023-03-11 06:46:20 +0000797 pass
798 handlers.append(_BasicAuthHandler(mgr))
799 handlers.append(_DigestAuthHandler(mgr))
800 if kerberos:
801 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700802
Gavin Makea2e3302023-03-11 06:46:20 +0000803 if "http_proxy" in os.environ:
804 url = os.environ["http_proxy"]
805 handlers.append(
806 urllib.request.ProxyHandler({"http": url, "https": url})
807 )
808 if "REPO_CURL_VERBOSE" in os.environ:
809 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
810 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
811 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700812
David Pursehouse819827a2020-02-12 15:20:19 +0900813
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700814def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000815 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400816
Gavin Makea2e3302023-03-11 06:46:20 +0000817 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
818 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
819 opt.add_option(
820 "--wrapper-version",
821 dest="wrapper_version",
822 help="version of the wrapper script",
823 )
824 opt.add_option(
825 "--wrapper-path",
826 dest="wrapper_path",
827 help="location of the wrapper script",
828 )
829 _PruneOptions(argv, opt)
830 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700831
Gavin Makea2e3302023-03-11 06:46:20 +0000832 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
833 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700834
Gavin Makea2e3302023-03-11 06:46:20 +0000835 Version.wrapper_version = opt.wrapper_version
836 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800837
Gavin Makea2e3302023-03-11 06:46:20 +0000838 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400839
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700840 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000841 init_http()
842 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400843
Gavin Makea2e3302023-03-11 06:46:20 +0000844 if gopts.trace:
845 SetTrace()
846
847 if gopts.trace_to_stderr:
848 SetTraceToStderr()
849
850 result = repo._Run(name, gopts, argv) or 0
Jason Chang32b59562023-07-14 16:45:35 -0700851 except RepoExitError as e:
Jason Chang1a3612f2023-08-08 14:12:53 -0700852 if not isinstance(e, SilentRepoExitError):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000853 logger.log_aggregated_errors(e)
Jason Chang32b59562023-07-14 16:45:35 -0700854 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000855 except KeyboardInterrupt:
856 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700857 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000858 except RepoChangedException as rce:
859 # If repo changed, re-exec ourselves.
Gavin Makea2e3302023-03-11 06:46:20 +0000860 argv = list(sys.argv)
861 argv.extend(rce.extra_args)
862 try:
Gavin Makf1ddaaa2023-08-04 21:13:38 +0000863 os.execv(sys.executable, [sys.executable, __file__] + argv)
Gavin Makea2e3302023-03-11 06:46:20 +0000864 except OSError as e:
865 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
866 print("fatal: %s" % e, file=sys.stderr)
867 result = 128
868
869 TerminatePager()
870 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700871
David Pursehouse819827a2020-02-12 15:20:19 +0900872
Gavin Makea2e3302023-03-11 06:46:20 +0000873if __name__ == "__main__":
874 _Main(sys.argv[1:])