blob: bafa64df06e90a4ce717e3bf6fa0dc69eacf3d1b [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
Conley Owens75ee0572012-11-15 17:33:11 -080051from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070052from error import NoSuchProjectError
53from error import RepoChangedException
Mike Frysinger64477332023-08-21 21:20:32 -040054from error import RepoError
Jason Chang32b59562023-07-14 16:45:35 -070055from error import RepoExitError
56from error import RepoUnhandledExceptionError
Jason Chang1a3612f2023-08-08 14:12:53 -070057from error import SilentRepoExitError
Mike Frysinger64477332023-08-21 21:20:32 -040058import event_log
59from git_command import user_agent
60from git_config import RepoConfig
61from git_trace2_event_log import EventLog
Jason Chang8914b1f2023-05-26 12:44:50 -070062from manifest_xml import RepoClient
Mike Frysinger64477332023-08-21 21:20:32 -040063from pager import RunPager
64from pager import TerminatePager
65from repo_trace import SetTrace
66from repo_trace import SetTraceToStderr
67from repo_trace import Trace
David Pursehouse5c6eeac2012-10-11 16:44:48 +090068from subcmds import all_commands
Mike Frysinger64477332023-08-21 21:20:32 -040069from subcmds.version import Version
70from wrapper import Wrapper
71from wrapper import WrapperPath
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070072
Chirayu Desai217ea7d2013-03-01 19:14:38 +053073
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000074logger = RepoLogger(__file__)
75
76
Mike Frysinger37f28f12020-02-16 15:15:53 -050077# NB: These do not need to be kept in sync with the repo launcher script.
78# These may be much newer as it allows the repo launcher to roll between
79# different repo releases while source versions might require a newer python.
80#
81# The soft version is when we start warning users that the version is old and
82# we'll be dropping support for it. We'll refuse to work with versions older
83# than the hard version.
84#
85# python-3.6 is in Ubuntu Bionic.
86MIN_PYTHON_VERSION_SOFT = (3, 6)
Peter Kjellerstedta3b2edf2021-04-15 01:32:40 +020087MIN_PYTHON_VERSION_HARD = (3, 6)
Mike Frysinger37f28f12020-02-16 15:15:53 -050088
89if sys.version_info.major < 3:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000090 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +000091 "repo: error: Python 2 is no longer supported; "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000092 "Please upgrade to Python %d.%d+.",
93 *MIN_PYTHON_VERSION_SOFT,
Gavin Makea2e3302023-03-11 06:46:20 +000094 )
Mike Frysinger37f28f12020-02-16 15:15:53 -050095 sys.exit(1)
Gavin Makea2e3302023-03-11 06:46:20 +000096else:
97 if sys.version_info < MIN_PYTHON_VERSION_HARD:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000098 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +000099 "repo: error: Python 3 version is too old; "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000100 "Please upgrade to Python %d.%d+.",
101 *MIN_PYTHON_VERSION_SOFT,
Gavin Makea2e3302023-03-11 06:46:20 +0000102 )
103 sys.exit(1)
104 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000105 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000106 "repo: warning: your Python 3 version is no longer supported; "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000107 "Please upgrade to Python %d.%d+.",
108 *MIN_PYTHON_VERSION_SOFT,
Gavin Makea2e3302023-03-11 06:46:20 +0000109 )
Mike Frysinger37f28f12020-02-16 15:15:53 -0500110
Jason Changc6578442023-06-22 15:04:06 -0700111KEYBOARD_INTERRUPT_EXIT = 128 + signal.SIGINT
Jason Chang32b59562023-07-14 16:45:35 -0700112MAX_PRINT_ERRORS = 5
Mike Frysinger37f28f12020-02-16 15:15:53 -0500113
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114global_options = optparse.OptionParser(
Gavin Makea2e3302023-03-11 06:46:20 +0000115 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]",
116 add_help_option=False,
117)
118global_options.add_option(
119 "-h", "--help", action="store_true", help="show this help message and exit"
120)
121global_options.add_option(
122 "--help-all",
123 action="store_true",
124 help="show this help message with all subcommands and exit",
125)
126global_options.add_option(
127 "-p",
128 "--paginate",
129 dest="pager",
130 action="store_true",
131 help="display command output in the pager",
132)
133global_options.add_option(
134 "--no-pager", dest="pager", action="store_false", help="disable the pager"
135)
136global_options.add_option(
137 "--color",
138 choices=("auto", "always", "never"),
139 default=None,
140 help="control color usage: auto, always, never",
141)
142global_options.add_option(
143 "--trace",
144 dest="trace",
145 action="store_true",
146 help="trace git command execution (REPO_TRACE=1)",
147)
148global_options.add_option(
149 "--trace-to-stderr",
150 dest="trace_to_stderr",
151 action="store_true",
152 help="trace outputs go to stderr in addition to .repo/TRACE_FILE",
153)
154global_options.add_option(
155 "--trace-python",
156 dest="trace_python",
157 action="store_true",
158 help="trace python command execution",
159)
160global_options.add_option(
161 "--time",
162 dest="time",
163 action="store_true",
164 help="time repo command execution",
165)
166global_options.add_option(
167 "--version",
168 dest="show_version",
169 action="store_true",
170 help="display this version of repo",
171)
172global_options.add_option(
173 "--show-toplevel",
174 action="store_true",
175 help="display the path of the top-level directory of "
176 "the repo client checkout",
177)
178global_options.add_option(
179 "--event-log",
180 dest="event_log",
181 action="store",
182 help="filename of event log to append timeline to",
183)
184global_options.add_option(
185 "--git-trace2-event-log",
186 action="store",
187 help="directory to write git trace2 event log to",
188)
189global_options.add_option(
190 "--submanifest-path",
191 action="store",
192 metavar="REL_PATH",
193 help="submanifest path",
194)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700195
David Pursehouse819827a2020-02-12 15:20:19 +0900196
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197class _Repo(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000198 def __init__(self, repodir):
199 self.repodir = repodir
200 self.commands = all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201
Gavin Makea2e3302023-03-11 06:46:20 +0000202 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
203 """Show --help screen."""
204 global_options.print_help()
205 print()
206 if short:
207 commands = " ".join(sorted(self.commands))
208 wrapped_commands = textwrap.wrap(commands, width=77)
209 print(
210 "Available commands:\n %s" % ("\n ".join(wrapped_commands),)
211 )
212 print("\nRun `repo help <command>` for command-specific details.")
213 print("Bug reports:", Wrapper().BUG_URL)
Conley Owens7ba25be2012-11-14 14:18:06 -0800214 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000215 cmd = self.commands["help"]()
216 if all_commands:
217 cmd.PrintAllCommandsBody()
218 else:
219 cmd.PrintCommonCommandsBody()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400220
Gavin Makea2e3302023-03-11 06:46:20 +0000221 def _ParseArgs(self, argv):
222 """Parse the main `repo` command line options."""
223 for i, arg in enumerate(argv):
224 if not arg.startswith("-"):
225 name = arg
226 glob = argv[:i]
227 argv = argv[i + 1 :]
228 break
229 else:
230 name = None
231 glob = argv
232 argv = []
233 gopts, _gargs = global_options.parse_args(glob)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800234
Gavin Makea2e3302023-03-11 06:46:20 +0000235 if name:
236 name, alias_args = self._ExpandAlias(name)
237 argv = alias_args + argv
David Rileye0684ad2017-04-05 00:02:59 -0700238
Gavin Makea2e3302023-03-11 06:46:20 +0000239 return (name, gopts, argv)
240
241 def _ExpandAlias(self, name):
242 """Look up user registered aliases."""
243 # We don't resolve aliases for existing subcommands. This matches git.
244 if name in self.commands:
245 return name, []
246
247 key = "alias.%s" % (name,)
248 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
249 if alias is None:
250 alias = RepoConfig.ForUser().GetString(key)
251 if alias is None:
252 return name, []
253
254 args = alias.strip().split(" ", 1)
255 name = args[0]
256 if len(args) == 2:
257 args = shlex.split(args[1])
258 else:
259 args = []
260 return name, args
261
262 def _Run(self, name, gopts, argv):
263 """Execute the requested subcommand."""
264 result = 0
265
266 # Handle options that terminate quickly first.
267 if gopts.help or gopts.help_all:
268 self._PrintHelp(short=False, all_commands=gopts.help_all)
269 return 0
270 elif gopts.show_version:
271 # Always allow global --version regardless of subcommand validity.
272 name = "version"
273 elif gopts.show_toplevel:
274 print(os.path.dirname(self.repodir))
275 return 0
276 elif not name:
277 # No subcommand specified, so show the help/subcommand.
278 self._PrintHelp(short=True)
279 return 1
280
281 run = lambda: self._RunLong(name, gopts, argv) or 0
282 with Trace(
283 "starting new command: %s",
284 ", ".join([name] + argv),
285 first_trace=True,
286 ):
287 if gopts.trace_python:
288 import trace
289
290 tracer = trace.Trace(
291 count=False,
292 trace=True,
293 timing=True,
294 ignoredirs=set(sys.path[1:]),
295 )
296 result = tracer.runfunc(run)
297 else:
298 result = run()
299 return result
300
301 def _RunLong(self, name, gopts, argv):
302 """Execute the (longer running) requested subcommand."""
303 result = 0
304 SetDefaultColoring(gopts.color)
305
306 git_trace2_event_log = EventLog()
307 outer_client = RepoClient(self.repodir)
308 repo_client = outer_client
309 if gopts.submanifest_path:
310 repo_client = RepoClient(
311 self.repodir,
312 submanifest_path=gopts.submanifest_path,
313 outer_client=outer_client,
314 )
Jason Chang8914b1f2023-05-26 12:44:50 -0700315
316 if Wrapper().gitc_parse_clientdir(os.getcwd()):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000317 logger.error("GITC is not supported.")
Jason Chang8914b1f2023-05-26 12:44:50 -0700318 raise GitcUnsupportedError()
Gavin Makea2e3302023-03-11 06:46:20 +0000319
320 try:
321 cmd = self.commands[name](
322 repodir=self.repodir,
323 client=repo_client,
324 manifest=repo_client.manifest,
325 outer_client=outer_client,
326 outer_manifest=outer_client.manifest,
Gavin Makea2e3302023-03-11 06:46:20 +0000327 git_event_log=git_trace2_event_log,
328 )
329 except KeyError:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000330 logger.error(
331 "repo: '%s' is not a repo command. See 'repo help'.", name
Gavin Makea2e3302023-03-11 06:46:20 +0000332 )
333 return 1
334
335 Editor.globalConfig = cmd.client.globalConfig
336
337 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000338 logger.error("fatal: '%s' requires a working directory", name)
Gavin Makea2e3302023-03-11 06:46:20 +0000339 return 1
340
Gavin Makea2e3302023-03-11 06:46:20 +0000341 try:
342 copts, cargs = cmd.OptionParser.parse_args(argv)
343 copts = cmd.ReadEnvironmentOptions(copts)
344 except NoManifestException as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000345 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
346 logger.error(
347 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000348 )
349 return 1
350
351 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
352 config = cmd.client.globalConfig
353 if gopts.pager:
354 use_pager = True
355 else:
356 use_pager = config.GetBoolean("pager.%s" % name)
357 if use_pager is None:
358 use_pager = cmd.WantPager(copts)
359 if use_pager:
360 RunPager(config)
361
362 start = time.time()
363 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
364 cmd.event_log.SetParent(cmd_event)
365 git_trace2_event_log.StartEvent()
366 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
367
Jason Changc6578442023-06-22 15:04:06 -0700368 def execute_command_helper():
369 """
370 Execute the subcommand.
371 """
372 nonlocal result
Gavin Makea2e3302023-03-11 06:46:20 +0000373 cmd.CommonValidateOptions(copts, cargs)
374 cmd.ValidateOptions(copts, cargs)
375
376 this_manifest_only = copts.this_manifest_only
377 outer_manifest = copts.outer_manifest
378 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
379 result = cmd.Execute(copts, cargs)
380 elif outer_manifest and repo_client.manifest.is_submanifest:
381 # The command does not support multi-manifest, we are using a
382 # submanifest, and the command line is for the outermost
383 # manifest. Re-run using the outermost manifest, which will
384 # recurse through the submanifests.
385 gopts.submanifest_path = ""
386 result = self._Run(name, gopts, argv)
387 else:
388 # No multi-manifest support. Run the command in the current
389 # (sub)manifest, and then any child submanifests.
390 result = cmd.Execute(copts, cargs)
391 for submanifest in repo_client.manifest.submanifests.values():
392 spec = submanifest.ToSubmanifestSpec()
393 gopts.submanifest_path = submanifest.repo_client.path_prefix
394 child_argv = argv[:]
395 child_argv.append("--no-outer-manifest")
396 # Not all subcommands support the 3 manifest options, so
397 # only add them if the original command includes them.
398 if hasattr(copts, "manifest_url"):
399 child_argv.extend(["--manifest-url", spec.manifestUrl])
400 if hasattr(copts, "manifest_name"):
401 child_argv.extend(
402 ["--manifest-name", spec.manifestName]
403 )
404 if hasattr(copts, "manifest_branch"):
405 child_argv.extend(["--manifest-branch", spec.revision])
406 result = self._Run(name, gopts, child_argv) or result
Jason Changc6578442023-06-22 15:04:06 -0700407
408 def execute_command():
409 """
410 Execute the command and log uncaught exceptions.
411 """
412 try:
413 execute_command_helper()
Jason Chang32b59562023-07-14 16:45:35 -0700414 except (
415 KeyboardInterrupt,
416 SystemExit,
417 Exception,
418 RepoExitError,
419 ) as e:
Jason Changc6578442023-06-22 15:04:06 -0700420 ok = isinstance(e, SystemExit) and not e.code
Jason Chang32b59562023-07-14 16:45:35 -0700421 exception_name = type(e).__name__
422 if isinstance(e, RepoUnhandledExceptionError):
423 exception_name = type(e.error).__name__
424 if isinstance(e, RepoExitError):
425 aggregated_errors = e.aggregate_errors or []
426 for error in aggregated_errors:
427 project = None
428 if isinstance(error, RepoError):
429 project = error.project
430 error_info = json.dumps(
431 {
432 "ErrorType": type(error).__name__,
433 "Project": project,
434 "Message": str(error),
435 }
436 )
437 git_trace2_event_log.ErrorEvent(
438 f"AggregateExitError:{error_info}"
439 )
Jason Changc6578442023-06-22 15:04:06 -0700440 if not ok:
Jason Changc6578442023-06-22 15:04:06 -0700441 git_trace2_event_log.ErrorEvent(
Gavin Mak1d2e99d2023-07-22 02:56:44 +0000442 f"RepoExitError:{exception_name}"
443 )
Jason Changc6578442023-06-22 15:04:06 -0700444 raise
445
446 try:
447 execute_command()
Gavin Makea2e3302023-03-11 06:46:20 +0000448 except (
449 DownloadError,
450 ManifestInvalidRevisionError,
451 NoManifestException,
452 ) as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000453 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
Gavin Makea2e3302023-03-11 06:46:20 +0000454 if isinstance(e, NoManifestException):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000455 logger.error(
456 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000457 )
Jason Chang32b59562023-07-14 16:45:35 -0700458 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000459 except NoSuchProjectError as e:
460 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000461 logger.error("error: project %s not found", e.name)
Gavin Makea2e3302023-03-11 06:46:20 +0000462 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000463 logger.error("error: no project in current directory")
Jason Chang32b59562023-07-14 16:45:35 -0700464 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000465 except InvalidProjectGroupsError as e:
466 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000467 logger.error(
468 "error: project group must be enabled for project %s",
469 e.name,
Gavin Makea2e3302023-03-11 06:46:20 +0000470 )
471 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000472 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000473 "error: project group must be enabled for the project in "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000474 "the current directory"
Gavin Makea2e3302023-03-11 06:46:20 +0000475 )
Jason Chang32b59562023-07-14 16:45:35 -0700476 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000477 except SystemExit as e:
478 if e.code:
479 result = e.code
480 raise
Jason Changc6578442023-06-22 15:04:06 -0700481 except KeyboardInterrupt:
482 result = KEYBOARD_INTERRUPT_EXIT
483 raise
Jason Chang32b59562023-07-14 16:45:35 -0700484 except RepoExitError as e:
485 result = e.exit_code
486 raise
Jason Changc6578442023-06-22 15:04:06 -0700487 except Exception:
488 result = 1
489 raise
Gavin Makea2e3302023-03-11 06:46:20 +0000490 finally:
491 finish = time.time()
492 elapsed = finish - start
493 hours, remainder = divmod(elapsed, 3600)
494 minutes, seconds = divmod(remainder, 60)
495 if gopts.time:
496 if hours == 0:
497 print(
498 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
499 )
500 else:
501 print(
502 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
503 file=sys.stderr,
504 )
505
506 cmd.event_log.FinishEvent(
507 cmd_event, finish, result is None or result == 0
508 )
509 git_trace2_event_log.DefParamRepoEvents(
510 cmd.manifest.manifestProject.config.DumpConfigDict()
511 )
512 git_trace2_event_log.ExitEvent(result)
513
514 if gopts.event_log:
515 cmd.event_log.Write(
516 os.path.abspath(os.path.expanduser(gopts.event_log))
517 )
518
519 git_trace2_event_log.Write(gopts.git_trace2_event_log)
520 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700521
Conley Owens094cdbe2014-01-30 15:09:59 -0800522
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500523def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000524 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500525
Gavin Makea2e3302023-03-11 06:46:20 +0000526 Args:
527 ver_str: The version string passed from the repo launcher when it ran
528 us.
529 repo_path: The path to the repo launcher that loaded us.
530 """
531 # Refuse to work with really old wrapper versions. We don't test these,
532 # so might as well require a somewhat recent sane version.
533 # v1.15 of the repo launcher was released in ~Mar 2012.
534 MIN_REPO_VERSION = (1, 15)
535 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500536
Gavin Makea2e3302023-03-11 06:46:20 +0000537 if not repo_path:
538 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539
Gavin Makea2e3302023-03-11 06:46:20 +0000540 if not ver_str:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000541 logger.error("no --wrapper-version argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000542 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543
Gavin Makea2e3302023-03-11 06:46:20 +0000544 # Pull out the version of the repo launcher we know about to compare.
545 exp = Wrapper().VERSION
546 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700547
Gavin Makea2e3302023-03-11 06:46:20 +0000548 exp_str = ".".join(map(str, exp))
549 if ver < MIN_REPO_VERSION:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000550 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000551 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500552repo: error:
553!!! Your version of repo %s is too old.
554!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900555!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500556!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700557
558 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000559""",
560 ver_str,
561 min_str,
562 exp_str,
563 WrapperPath(),
564 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000565 )
566 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700567
Gavin Makea2e3302023-03-11 06:46:20 +0000568 if exp > ver:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000569 logger.warn("\n... A new version of repo (%s) is available.", exp_str)
Gavin Makea2e3302023-03-11 06:46:20 +0000570 if os.access(repo_path, os.W_OK):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000571 logger.warn(
Gavin Makea2e3302023-03-11 06:46:20 +0000572 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700573... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000575""",
576 WrapperPath(),
577 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000578 )
579 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000580 logger.warn(
Gavin Makea2e3302023-03-11 06:46:20 +0000581 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500582... New version is available at: %s
583... The launcher is run from: %s
584!!! The launcher is not writable. Please talk to your sysadmin or distro
585!!! to get an update installed.
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000586""",
587 WrapperPath(),
588 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000589 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700590
David Pursehouse819827a2020-02-12 15:20:19 +0900591
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200592def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000593 if not repo_dir:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000594 logger.error("no --repo-dir argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000595 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700596
David Pursehouse819827a2020-02-12 15:20:19 +0900597
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700598def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000599 i = 0
600 while i < len(argv):
601 a = argv[i]
602 if a == "--":
603 break
604 if a.startswith("--"):
605 eq = a.find("=")
606 if eq > 0:
607 a = a[0:eq]
608 if not opt.has_option(a):
609 del argv[i]
610 continue
611 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700612
David Pursehouse819827a2020-02-12 15:20:19 +0900613
Sarah Owens1f7627f2012-10-31 09:21:55 -0700614class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000615 def http_request(self, req):
616 req.add_header("User-Agent", user_agent.repo)
617 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700618
Gavin Makea2e3302023-03-11 06:46:20 +0000619 def https_request(self, req):
620 req.add_header("User-Agent", user_agent.repo)
621 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700622
David Pursehouse819827a2020-02-12 15:20:19 +0900623
JoonCheol Parke9860722012-10-11 02:31:44 +0900624def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000625 # If repo could not find auth info from netrc, try to get it from user input
626 url = req.get_full_url()
627 user, password = handler.passwd.find_user_password(None, url)
628 if user is None:
629 print(msg)
630 try:
631 user = input("User: ")
632 password = getpass.getpass()
633 except KeyboardInterrupt:
634 return
635 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900636
David Pursehouse819827a2020-02-12 15:20:19 +0900637
Sarah Owens1f7627f2012-10-31 09:21:55 -0700638class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000639 def http_error_401(self, req, fp, code, msg, headers):
640 _AddPasswordFromUserInput(self, msg, req)
641 return urllib.request.HTTPBasicAuthHandler.http_error_401(
642 self, req, fp, code, msg, headers
643 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900644
Gavin Makea2e3302023-03-11 06:46:20 +0000645 def http_error_auth_reqed(self, authreq, host, req, headers):
646 try:
647 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900648
Gavin Makea2e3302023-03-11 06:46:20 +0000649 def _add_header(name, val):
650 val = val.replace("\n", "")
651 old_add_header(name, val)
652
653 req.add_header = _add_header
654 return (
655 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
656 self, authreq, host, req, headers
657 )
658 )
659 except Exception:
660 reset = getattr(self, "reset_retry_count", None)
661 if reset is not None:
662 reset()
663 elif getattr(self, "retried", None):
664 self.retried = 0
665 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700666
David Pursehouse819827a2020-02-12 15:20:19 +0900667
Sarah Owens1f7627f2012-10-31 09:21:55 -0700668class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000669 def http_error_401(self, req, fp, code, msg, headers):
670 _AddPasswordFromUserInput(self, msg, req)
671 return urllib.request.HTTPDigestAuthHandler.http_error_401(
672 self, req, fp, code, msg, headers
673 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900674
Gavin Makea2e3302023-03-11 06:46:20 +0000675 def http_error_auth_reqed(self, auth_header, host, req, headers):
676 try:
677 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900678
Gavin Makea2e3302023-03-11 06:46:20 +0000679 def _add_header(name, val):
680 val = val.replace("\n", "")
681 old_add_header(name, val)
682
683 req.add_header = _add_header
684 return (
685 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
686 self, auth_header, host, req, headers
687 )
688 )
689 except Exception:
690 reset = getattr(self, "reset_retry_count", None)
691 if reset is not None:
692 reset()
693 elif getattr(self, "retried", None):
694 self.retried = 0
695 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800696
David Pursehouse819827a2020-02-12 15:20:19 +0900697
Carlos Aguado1242e602014-02-03 13:48:47 +0100698class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000699 def __init__(self):
700 self.retried = 0
701 self.context = None
702 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100703
Gavin Makea2e3302023-03-11 06:46:20 +0000704 def http_error_401(self, req, fp, code, msg, headers):
705 host = req.get_host()
706 retry = self.http_error_auth_reqed(
707 "www-authenticate", host, req, headers
708 )
709 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100710
Gavin Makea2e3302023-03-11 06:46:20 +0000711 def http_error_auth_reqed(self, auth_header, host, req, headers):
712 try:
713 spn = "HTTP@%s" % host
714 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100715
Gavin Makea2e3302023-03-11 06:46:20 +0000716 if self.retried > 3:
717 raise urllib.request.HTTPError(
718 req.get_full_url(),
719 401,
720 "Negotiate auth failed",
721 headers,
722 None,
723 )
724 else:
725 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100726
Gavin Makea2e3302023-03-11 06:46:20 +0000727 neghdr = self._negotiate_get_svctk(spn, authdata)
728 if neghdr is None:
729 return None
730
731 req.add_unredirected_header("Authorization", neghdr)
732 response = self.parent.open(req)
733
734 srvauth = self._negotiate_get_authdata(auth_header, response.info())
735 if self._validate_response(srvauth):
736 return response
737 except kerberos.GSSError:
738 return None
739 except Exception:
740 self.reset_retry_count()
741 raise
742 finally:
743 self._clean_context()
744
745 def reset_retry_count(self):
746 self.retried = 0
747
748 def _negotiate_get_authdata(self, auth_header, headers):
749 authhdr = headers.get(auth_header, None)
750 if authhdr is not None:
751 for mech_tuple in authhdr.split(","):
752 mech, __, authdata = mech_tuple.strip().partition(" ")
753 if mech.lower() == "negotiate":
754 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100755 return None
756
Gavin Makea2e3302023-03-11 06:46:20 +0000757 def _negotiate_get_svctk(self, spn, authdata):
758 if authdata is None:
759 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100760
Gavin Makea2e3302023-03-11 06:46:20 +0000761 result, self.context = kerberos.authGSSClientInit(spn)
762 if result < kerberos.AUTH_GSS_COMPLETE:
763 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100764
Gavin Makea2e3302023-03-11 06:46:20 +0000765 result = kerberos.authGSSClientStep(self.context, authdata)
766 if result < kerberos.AUTH_GSS_CONTINUE:
767 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100768
Gavin Makea2e3302023-03-11 06:46:20 +0000769 response = kerberos.authGSSClientResponse(self.context)
770 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100771
Gavin Makea2e3302023-03-11 06:46:20 +0000772 def _validate_response(self, authdata):
773 if authdata is None:
774 return None
775 result = kerberos.authGSSClientStep(self.context, authdata)
776 if result == kerberos.AUTH_GSS_COMPLETE:
777 return True
778 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100779
Gavin Makea2e3302023-03-11 06:46:20 +0000780 def _clean_context(self):
781 if self.context is not None:
782 kerberos.authGSSClientClean(self.context)
783 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100784
David Pursehouse819827a2020-02-12 15:20:19 +0900785
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700786def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000787 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700788
Gavin Makea2e3302023-03-11 06:46:20 +0000789 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
790 try:
791 n = netrc.netrc()
792 for host in n.hosts:
793 p = n.hosts[host]
794 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
795 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
796 except netrc.NetrcParseError:
797 pass
798 except IOError:
799 pass
800 handlers.append(_BasicAuthHandler(mgr))
801 handlers.append(_DigestAuthHandler(mgr))
802 if kerberos:
803 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700804
Gavin Makea2e3302023-03-11 06:46:20 +0000805 if "http_proxy" in os.environ:
806 url = os.environ["http_proxy"]
807 handlers.append(
808 urllib.request.ProxyHandler({"http": url, "https": url})
809 )
810 if "REPO_CURL_VERBOSE" in os.environ:
811 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
812 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
813 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700814
David Pursehouse819827a2020-02-12 15:20:19 +0900815
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700816def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000817 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400818
Gavin Makea2e3302023-03-11 06:46:20 +0000819 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
820 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
821 opt.add_option(
822 "--wrapper-version",
823 dest="wrapper_version",
824 help="version of the wrapper script",
825 )
826 opt.add_option(
827 "--wrapper-path",
828 dest="wrapper_path",
829 help="location of the wrapper script",
830 )
831 _PruneOptions(argv, opt)
832 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700833
Gavin Makea2e3302023-03-11 06:46:20 +0000834 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
835 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700836
Gavin Makea2e3302023-03-11 06:46:20 +0000837 Version.wrapper_version = opt.wrapper_version
838 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800839
Gavin Makea2e3302023-03-11 06:46:20 +0000840 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400841
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700842 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000843 init_http()
844 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400845
Gavin Makea2e3302023-03-11 06:46:20 +0000846 if gopts.trace:
847 SetTrace()
848
849 if gopts.trace_to_stderr:
850 SetTraceToStderr()
851
852 result = repo._Run(name, gopts, argv) or 0
Jason Chang32b59562023-07-14 16:45:35 -0700853 except RepoExitError as e:
Jason Chang1a3612f2023-08-08 14:12:53 -0700854 if not isinstance(e, SilentRepoExitError):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000855 logger.log_aggregated_errors(e)
Jason Chang32b59562023-07-14 16:45:35 -0700856 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000857 except KeyboardInterrupt:
858 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700859 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000860 except RepoChangedException as rce:
861 # If repo changed, re-exec ourselves.
Gavin Makea2e3302023-03-11 06:46:20 +0000862 argv = list(sys.argv)
863 argv.extend(rce.extra_args)
864 try:
Gavin Makf1ddaaa2023-08-04 21:13:38 +0000865 os.execv(sys.executable, [sys.executable, __file__] + argv)
Gavin Makea2e3302023-03-11 06:46:20 +0000866 except OSError as e:
867 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
868 print("fatal: %s" % e, file=sys.stderr)
869 result = 128
870
871 TerminatePager()
872 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700873
David Pursehouse819827a2020-02-12 15:20:19 +0900874
Gavin Makea2e3302023-03-11 06:46:20 +0000875if __name__ == "__main__":
876 _Main(sys.argv[1:])