blob: 9c62722fded4603469650c43ae3363eb66e5bda9 [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 Vasudevan8bc50002023-10-13 19:22:47 +0000569 logger.warning(
570 "\n... A new version of repo (%s) is available.", exp_str
571 )
Gavin Makea2e3302023-03-11 06:46:20 +0000572 if os.access(repo_path, os.W_OK):
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000573 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000574 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700575... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700576 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000577""",
578 WrapperPath(),
579 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000580 )
581 else:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000582 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000583 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500584... New version is available at: %s
585... The launcher is run from: %s
586!!! The launcher is not writable. Please talk to your sysadmin or distro
587!!! to get an update installed.
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000588""",
589 WrapperPath(),
590 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000591 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700592
David Pursehouse819827a2020-02-12 15:20:19 +0900593
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200594def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000595 if not repo_dir:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000596 logger.error("no --repo-dir argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000597 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700598
David Pursehouse819827a2020-02-12 15:20:19 +0900599
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700600def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000601 i = 0
602 while i < len(argv):
603 a = argv[i]
604 if a == "--":
605 break
606 if a.startswith("--"):
607 eq = a.find("=")
608 if eq > 0:
609 a = a[0:eq]
610 if not opt.has_option(a):
611 del argv[i]
612 continue
613 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700614
David Pursehouse819827a2020-02-12 15:20:19 +0900615
Sarah Owens1f7627f2012-10-31 09:21:55 -0700616class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000617 def http_request(self, req):
618 req.add_header("User-Agent", user_agent.repo)
619 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700620
Gavin Makea2e3302023-03-11 06:46:20 +0000621 def https_request(self, req):
622 req.add_header("User-Agent", user_agent.repo)
623 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700624
David Pursehouse819827a2020-02-12 15:20:19 +0900625
JoonCheol Parke9860722012-10-11 02:31:44 +0900626def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000627 # If repo could not find auth info from netrc, try to get it from user input
628 url = req.get_full_url()
629 user, password = handler.passwd.find_user_password(None, url)
630 if user is None:
631 print(msg)
632 try:
633 user = input("User: ")
634 password = getpass.getpass()
635 except KeyboardInterrupt:
636 return
637 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900638
David Pursehouse819827a2020-02-12 15:20:19 +0900639
Sarah Owens1f7627f2012-10-31 09:21:55 -0700640class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000641 def http_error_401(self, req, fp, code, msg, headers):
642 _AddPasswordFromUserInput(self, msg, req)
643 return urllib.request.HTTPBasicAuthHandler.http_error_401(
644 self, req, fp, code, msg, headers
645 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900646
Gavin Makea2e3302023-03-11 06:46:20 +0000647 def http_error_auth_reqed(self, authreq, host, req, headers):
648 try:
649 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900650
Gavin Makea2e3302023-03-11 06:46:20 +0000651 def _add_header(name, val):
652 val = val.replace("\n", "")
653 old_add_header(name, val)
654
655 req.add_header = _add_header
656 return (
657 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
658 self, authreq, host, req, headers
659 )
660 )
661 except Exception:
662 reset = getattr(self, "reset_retry_count", None)
663 if reset is not None:
664 reset()
665 elif getattr(self, "retried", None):
666 self.retried = 0
667 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700668
David Pursehouse819827a2020-02-12 15:20:19 +0900669
Sarah Owens1f7627f2012-10-31 09:21:55 -0700670class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000671 def http_error_401(self, req, fp, code, msg, headers):
672 _AddPasswordFromUserInput(self, msg, req)
673 return urllib.request.HTTPDigestAuthHandler.http_error_401(
674 self, req, fp, code, msg, headers
675 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900676
Gavin Makea2e3302023-03-11 06:46:20 +0000677 def http_error_auth_reqed(self, auth_header, host, req, headers):
678 try:
679 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900680
Gavin Makea2e3302023-03-11 06:46:20 +0000681 def _add_header(name, val):
682 val = val.replace("\n", "")
683 old_add_header(name, val)
684
685 req.add_header = _add_header
686 return (
687 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
688 self, auth_header, host, req, headers
689 )
690 )
691 except Exception:
692 reset = getattr(self, "reset_retry_count", None)
693 if reset is not None:
694 reset()
695 elif getattr(self, "retried", None):
696 self.retried = 0
697 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800698
David Pursehouse819827a2020-02-12 15:20:19 +0900699
Carlos Aguado1242e602014-02-03 13:48:47 +0100700class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000701 def __init__(self):
702 self.retried = 0
703 self.context = None
704 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100705
Gavin Makea2e3302023-03-11 06:46:20 +0000706 def http_error_401(self, req, fp, code, msg, headers):
707 host = req.get_host()
708 retry = self.http_error_auth_reqed(
709 "www-authenticate", host, req, headers
710 )
711 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100712
Gavin Makea2e3302023-03-11 06:46:20 +0000713 def http_error_auth_reqed(self, auth_header, host, req, headers):
714 try:
715 spn = "HTTP@%s" % host
716 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100717
Gavin Makea2e3302023-03-11 06:46:20 +0000718 if self.retried > 3:
719 raise urllib.request.HTTPError(
720 req.get_full_url(),
721 401,
722 "Negotiate auth failed",
723 headers,
724 None,
725 )
726 else:
727 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100728
Gavin Makea2e3302023-03-11 06:46:20 +0000729 neghdr = self._negotiate_get_svctk(spn, authdata)
730 if neghdr is None:
731 return None
732
733 req.add_unredirected_header("Authorization", neghdr)
734 response = self.parent.open(req)
735
736 srvauth = self._negotiate_get_authdata(auth_header, response.info())
737 if self._validate_response(srvauth):
738 return response
739 except kerberos.GSSError:
740 return None
741 except Exception:
742 self.reset_retry_count()
743 raise
744 finally:
745 self._clean_context()
746
747 def reset_retry_count(self):
748 self.retried = 0
749
750 def _negotiate_get_authdata(self, auth_header, headers):
751 authhdr = headers.get(auth_header, None)
752 if authhdr is not None:
753 for mech_tuple in authhdr.split(","):
754 mech, __, authdata = mech_tuple.strip().partition(" ")
755 if mech.lower() == "negotiate":
756 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100757 return None
758
Gavin Makea2e3302023-03-11 06:46:20 +0000759 def _negotiate_get_svctk(self, spn, authdata):
760 if authdata is None:
761 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100762
Gavin Makea2e3302023-03-11 06:46:20 +0000763 result, self.context = kerberos.authGSSClientInit(spn)
764 if result < kerberos.AUTH_GSS_COMPLETE:
765 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100766
Gavin Makea2e3302023-03-11 06:46:20 +0000767 result = kerberos.authGSSClientStep(self.context, authdata)
768 if result < kerberos.AUTH_GSS_CONTINUE:
769 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100770
Gavin Makea2e3302023-03-11 06:46:20 +0000771 response = kerberos.authGSSClientResponse(self.context)
772 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100773
Gavin Makea2e3302023-03-11 06:46:20 +0000774 def _validate_response(self, authdata):
775 if authdata is None:
776 return None
777 result = kerberos.authGSSClientStep(self.context, authdata)
778 if result == kerberos.AUTH_GSS_COMPLETE:
779 return True
780 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100781
Gavin Makea2e3302023-03-11 06:46:20 +0000782 def _clean_context(self):
783 if self.context is not None:
784 kerberos.authGSSClientClean(self.context)
785 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100786
David Pursehouse819827a2020-02-12 15:20:19 +0900787
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700788def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000789 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700790
Gavin Makea2e3302023-03-11 06:46:20 +0000791 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
792 try:
793 n = netrc.netrc()
794 for host in n.hosts:
795 p = n.hosts[host]
796 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
797 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
798 except netrc.NetrcParseError:
799 pass
800 except IOError:
801 pass
802 handlers.append(_BasicAuthHandler(mgr))
803 handlers.append(_DigestAuthHandler(mgr))
804 if kerberos:
805 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700806
Gavin Makea2e3302023-03-11 06:46:20 +0000807 if "http_proxy" in os.environ:
808 url = os.environ["http_proxy"]
809 handlers.append(
810 urllib.request.ProxyHandler({"http": url, "https": url})
811 )
812 if "REPO_CURL_VERBOSE" in os.environ:
813 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
814 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
815 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700816
David Pursehouse819827a2020-02-12 15:20:19 +0900817
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700818def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000819 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400820
Gavin Makea2e3302023-03-11 06:46:20 +0000821 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
822 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
823 opt.add_option(
824 "--wrapper-version",
825 dest="wrapper_version",
826 help="version of the wrapper script",
827 )
828 opt.add_option(
829 "--wrapper-path",
830 dest="wrapper_path",
831 help="location of the wrapper script",
832 )
833 _PruneOptions(argv, opt)
834 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700835
Gavin Makea2e3302023-03-11 06:46:20 +0000836 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
837 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700838
Gavin Makea2e3302023-03-11 06:46:20 +0000839 Version.wrapper_version = opt.wrapper_version
840 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800841
Gavin Makea2e3302023-03-11 06:46:20 +0000842 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400843
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700844 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000845 init_http()
846 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400847
Gavin Makea2e3302023-03-11 06:46:20 +0000848 if gopts.trace:
849 SetTrace()
850
851 if gopts.trace_to_stderr:
852 SetTraceToStderr()
853
854 result = repo._Run(name, gopts, argv) or 0
Jason Chang32b59562023-07-14 16:45:35 -0700855 except RepoExitError as e:
Jason Chang1a3612f2023-08-08 14:12:53 -0700856 if not isinstance(e, SilentRepoExitError):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000857 logger.log_aggregated_errors(e)
Jason Chang32b59562023-07-14 16:45:35 -0700858 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000859 except KeyboardInterrupt:
860 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700861 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000862 except RepoChangedException as rce:
863 # If repo changed, re-exec ourselves.
Gavin Makea2e3302023-03-11 06:46:20 +0000864 argv = list(sys.argv)
865 argv.extend(rce.extra_args)
866 try:
Gavin Makf1ddaaa2023-08-04 21:13:38 +0000867 os.execv(sys.executable, [sys.executable, __file__] + argv)
Gavin Makea2e3302023-03-11 06:46:20 +0000868 except OSError as e:
869 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
870 print("fatal: %s" % e, file=sys.stderr)
871 result = 128
872
873 TerminatePager()
874 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700875
David Pursehouse819827a2020-02-12 15:20:19 +0900876
Gavin Makea2e3302023-03-11 06:46:20 +0000877if __name__ == "__main__":
878 _Main(sys.argv[1:])