blob: 07c360f4a76611e4ec50bdea68c6ce81d9bf62f5 [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
Mike Frysinger8f4f9852023-10-14 01:10:29 +054589if sys.version_info < MIN_PYTHON_VERSION_HARD:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +000090 logger.error(
Mike Frysinger8f4f9852023-10-14 01:10:29 +054591 "repo: error: Python version is too old; "
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)
Mike Frysinger8f4f9852023-10-14 01:10:29 +054596elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
97 logger.error(
98 "repo: warning: your Python version is no longer supported; "
99 "Please upgrade to Python %d.%d+.",
100 *MIN_PYTHON_VERSION_SOFT,
101 )
Mike Frysinger37f28f12020-02-16 15:15:53 -0500102
Jason Changc6578442023-06-22 15:04:06 -0700103KEYBOARD_INTERRUPT_EXIT = 128 + signal.SIGINT
Jason Chang32b59562023-07-14 16:45:35 -0700104MAX_PRINT_ERRORS = 5
Mike Frysinger37f28f12020-02-16 15:15:53 -0500105
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700106global_options = optparse.OptionParser(
Gavin Makea2e3302023-03-11 06:46:20 +0000107 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]",
108 add_help_option=False,
109)
110global_options.add_option(
111 "-h", "--help", action="store_true", help="show this help message and exit"
112)
113global_options.add_option(
114 "--help-all",
115 action="store_true",
116 help="show this help message with all subcommands and exit",
117)
118global_options.add_option(
119 "-p",
120 "--paginate",
121 dest="pager",
122 action="store_true",
123 help="display command output in the pager",
124)
125global_options.add_option(
126 "--no-pager", dest="pager", action="store_false", help="disable the pager"
127)
128global_options.add_option(
129 "--color",
130 choices=("auto", "always", "never"),
131 default=None,
132 help="control color usage: auto, always, never",
133)
134global_options.add_option(
135 "--trace",
136 dest="trace",
137 action="store_true",
138 help="trace git command execution (REPO_TRACE=1)",
139)
140global_options.add_option(
141 "--trace-to-stderr",
142 dest="trace_to_stderr",
143 action="store_true",
144 help="trace outputs go to stderr in addition to .repo/TRACE_FILE",
145)
146global_options.add_option(
147 "--trace-python",
148 dest="trace_python",
149 action="store_true",
150 help="trace python command execution",
151)
152global_options.add_option(
153 "--time",
154 dest="time",
155 action="store_true",
156 help="time repo command execution",
157)
158global_options.add_option(
159 "--version",
160 dest="show_version",
161 action="store_true",
162 help="display this version of repo",
163)
164global_options.add_option(
165 "--show-toplevel",
166 action="store_true",
167 help="display the path of the top-level directory of "
168 "the repo client checkout",
169)
170global_options.add_option(
171 "--event-log",
172 dest="event_log",
173 action="store",
174 help="filename of event log to append timeline to",
175)
176global_options.add_option(
177 "--git-trace2-event-log",
178 action="store",
179 help="directory to write git trace2 event log to",
180)
181global_options.add_option(
182 "--submanifest-path",
183 action="store",
184 metavar="REL_PATH",
185 help="submanifest path",
186)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700187
David Pursehouse819827a2020-02-12 15:20:19 +0900188
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700189class _Repo(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000190 def __init__(self, repodir):
191 self.repodir = repodir
192 self.commands = all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193
Gavin Makea2e3302023-03-11 06:46:20 +0000194 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
195 """Show --help screen."""
196 global_options.print_help()
197 print()
198 if short:
199 commands = " ".join(sorted(self.commands))
200 wrapped_commands = textwrap.wrap(commands, width=77)
201 print(
202 "Available commands:\n %s" % ("\n ".join(wrapped_commands),)
203 )
204 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
239 key = "alias.%s" % (name,)
240 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
241 if alias is None:
242 alias = RepoConfig.ForUser().GetString(key)
243 if alias is None:
244 return name, []
245
246 args = alias.strip().split(" ", 1)
247 name = args[0]
248 if len(args) == 2:
249 args = shlex.split(args[1])
250 else:
251 args = []
252 return name, args
253
254 def _Run(self, name, gopts, argv):
255 """Execute the requested subcommand."""
256 result = 0
257
258 # Handle options that terminate quickly first.
259 if gopts.help or gopts.help_all:
260 self._PrintHelp(short=False, all_commands=gopts.help_all)
261 return 0
262 elif gopts.show_version:
263 # Always allow global --version regardless of subcommand validity.
264 name = "version"
265 elif gopts.show_toplevel:
266 print(os.path.dirname(self.repodir))
267 return 0
268 elif not name:
269 # No subcommand specified, so show the help/subcommand.
270 self._PrintHelp(short=True)
271 return 1
272
273 run = lambda: self._RunLong(name, gopts, argv) or 0
274 with Trace(
275 "starting new command: %s",
276 ", ".join([name] + argv),
277 first_trace=True,
278 ):
279 if gopts.trace_python:
280 import trace
281
282 tracer = trace.Trace(
283 count=False,
284 trace=True,
285 timing=True,
286 ignoredirs=set(sys.path[1:]),
287 )
288 result = tracer.runfunc(run)
289 else:
290 result = run()
291 return result
292
293 def _RunLong(self, name, gopts, argv):
294 """Execute the (longer running) requested subcommand."""
295 result = 0
296 SetDefaultColoring(gopts.color)
297
298 git_trace2_event_log = EventLog()
299 outer_client = RepoClient(self.repodir)
300 repo_client = outer_client
301 if gopts.submanifest_path:
302 repo_client = RepoClient(
303 self.repodir,
304 submanifest_path=gopts.submanifest_path,
305 outer_client=outer_client,
306 )
Jason Chang8914b1f2023-05-26 12:44:50 -0700307
308 if Wrapper().gitc_parse_clientdir(os.getcwd()):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000309 logger.error("GITC is not supported.")
Jason Chang8914b1f2023-05-26 12:44:50 -0700310 raise GitcUnsupportedError()
Gavin Makea2e3302023-03-11 06:46:20 +0000311
312 try:
313 cmd = self.commands[name](
314 repodir=self.repodir,
315 client=repo_client,
316 manifest=repo_client.manifest,
317 outer_client=outer_client,
318 outer_manifest=outer_client.manifest,
Gavin Makea2e3302023-03-11 06:46:20 +0000319 git_event_log=git_trace2_event_log,
320 )
321 except KeyError:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000322 logger.error(
323 "repo: '%s' is not a repo command. See 'repo help'.", name
Gavin Makea2e3302023-03-11 06:46:20 +0000324 )
325 return 1
326
327 Editor.globalConfig = cmd.client.globalConfig
328
329 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000330 logger.error("fatal: '%s' requires a working directory", name)
Gavin Makea2e3302023-03-11 06:46:20 +0000331 return 1
332
Gavin Makea2e3302023-03-11 06:46:20 +0000333 try:
334 copts, cargs = cmd.OptionParser.parse_args(argv)
335 copts = cmd.ReadEnvironmentOptions(copts)
336 except NoManifestException as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000337 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
338 logger.error(
339 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000340 )
341 return 1
342
343 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
344 config = cmd.client.globalConfig
345 if gopts.pager:
346 use_pager = True
347 else:
348 use_pager = config.GetBoolean("pager.%s" % name)
349 if use_pager is None:
350 use_pager = cmd.WantPager(copts)
351 if use_pager:
352 RunPager(config)
353
354 start = time.time()
355 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
356 cmd.event_log.SetParent(cmd_event)
357 git_trace2_event_log.StartEvent()
358 git_trace2_event_log.CommandEvent(name="repo", subcommands=[name])
359
Jason Changc6578442023-06-22 15:04:06 -0700360 def execute_command_helper():
361 """
362 Execute the subcommand.
363 """
364 nonlocal result
Gavin Makea2e3302023-03-11 06:46:20 +0000365 cmd.CommonValidateOptions(copts, cargs)
366 cmd.ValidateOptions(copts, cargs)
367
368 this_manifest_only = copts.this_manifest_only
369 outer_manifest = copts.outer_manifest
370 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
371 result = cmd.Execute(copts, cargs)
372 elif outer_manifest and repo_client.manifest.is_submanifest:
373 # The command does not support multi-manifest, we are using a
374 # submanifest, and the command line is for the outermost
375 # manifest. Re-run using the outermost manifest, which will
376 # recurse through the submanifests.
377 gopts.submanifest_path = ""
378 result = self._Run(name, gopts, argv)
379 else:
380 # No multi-manifest support. Run the command in the current
381 # (sub)manifest, and then any child submanifests.
382 result = cmd.Execute(copts, cargs)
383 for submanifest in repo_client.manifest.submanifests.values():
384 spec = submanifest.ToSubmanifestSpec()
385 gopts.submanifest_path = submanifest.repo_client.path_prefix
386 child_argv = argv[:]
387 child_argv.append("--no-outer-manifest")
388 # Not all subcommands support the 3 manifest options, so
389 # only add them if the original command includes them.
390 if hasattr(copts, "manifest_url"):
391 child_argv.extend(["--manifest-url", spec.manifestUrl])
392 if hasattr(copts, "manifest_name"):
393 child_argv.extend(
394 ["--manifest-name", spec.manifestName]
395 )
396 if hasattr(copts, "manifest_branch"):
397 child_argv.extend(["--manifest-branch", spec.revision])
398 result = self._Run(name, gopts, child_argv) or result
Jason Changc6578442023-06-22 15:04:06 -0700399
400 def execute_command():
401 """
402 Execute the command and log uncaught exceptions.
403 """
404 try:
405 execute_command_helper()
Jason Chang32b59562023-07-14 16:45:35 -0700406 except (
407 KeyboardInterrupt,
408 SystemExit,
409 Exception,
410 RepoExitError,
411 ) as e:
Jason Changc6578442023-06-22 15:04:06 -0700412 ok = isinstance(e, SystemExit) and not e.code
Jason Chang32b59562023-07-14 16:45:35 -0700413 exception_name = type(e).__name__
414 if isinstance(e, RepoUnhandledExceptionError):
415 exception_name = type(e.error).__name__
416 if isinstance(e, RepoExitError):
417 aggregated_errors = e.aggregate_errors or []
418 for error in aggregated_errors:
419 project = None
420 if isinstance(error, RepoError):
421 project = error.project
422 error_info = json.dumps(
423 {
424 "ErrorType": type(error).__name__,
425 "Project": project,
426 "Message": str(error),
427 }
428 )
429 git_trace2_event_log.ErrorEvent(
430 f"AggregateExitError:{error_info}"
431 )
Jason Changc6578442023-06-22 15:04:06 -0700432 if not ok:
Jason Changc6578442023-06-22 15:04:06 -0700433 git_trace2_event_log.ErrorEvent(
Gavin Mak1d2e99d2023-07-22 02:56:44 +0000434 f"RepoExitError:{exception_name}"
435 )
Jason Changc6578442023-06-22 15:04:06 -0700436 raise
437
438 try:
439 execute_command()
Gavin Makea2e3302023-03-11 06:46:20 +0000440 except (
441 DownloadError,
442 ManifestInvalidRevisionError,
443 NoManifestException,
444 ) as e:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000445 logger.error("error: in `%s`: %s", " ".join([name] + argv), e)
Gavin Makea2e3302023-03-11 06:46:20 +0000446 if isinstance(e, NoManifestException):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000447 logger.error(
448 "error: manifest missing or unreadable -- please run init"
Gavin Makea2e3302023-03-11 06:46:20 +0000449 )
Jason Chang32b59562023-07-14 16:45:35 -0700450 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000451 except NoSuchProjectError as e:
452 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000453 logger.error("error: project %s not found", e.name)
Gavin Makea2e3302023-03-11 06:46:20 +0000454 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000455 logger.error("error: no project in current directory")
Jason Chang32b59562023-07-14 16:45:35 -0700456 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000457 except InvalidProjectGroupsError as e:
458 if e.name:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000459 logger.error(
460 "error: project group must be enabled for project %s",
461 e.name,
Gavin Makea2e3302023-03-11 06:46:20 +0000462 )
463 else:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000464 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000465 "error: project group must be enabled for the project in "
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000466 "the current directory"
Gavin Makea2e3302023-03-11 06:46:20 +0000467 )
Jason Chang32b59562023-07-14 16:45:35 -0700468 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000469 except SystemExit as e:
470 if e.code:
471 result = e.code
472 raise
Jason Changc6578442023-06-22 15:04:06 -0700473 except KeyboardInterrupt:
474 result = KEYBOARD_INTERRUPT_EXIT
475 raise
Jason Chang32b59562023-07-14 16:45:35 -0700476 except RepoExitError as e:
477 result = e.exit_code
478 raise
Jason Changc6578442023-06-22 15:04:06 -0700479 except Exception:
480 result = 1
481 raise
Gavin Makea2e3302023-03-11 06:46:20 +0000482 finally:
483 finish = time.time()
484 elapsed = finish - start
485 hours, remainder = divmod(elapsed, 3600)
486 minutes, seconds = divmod(remainder, 60)
487 if gopts.time:
488 if hours == 0:
489 print(
490 "real\t%dm%.3fs" % (minutes, seconds), file=sys.stderr
491 )
492 else:
493 print(
494 "real\t%dh%dm%.3fs" % (hours, minutes, seconds),
495 file=sys.stderr,
496 )
497
498 cmd.event_log.FinishEvent(
499 cmd_event, finish, result is None or result == 0
500 )
501 git_trace2_event_log.DefParamRepoEvents(
502 cmd.manifest.manifestProject.config.DumpConfigDict()
503 )
504 git_trace2_event_log.ExitEvent(result)
505
506 if gopts.event_log:
507 cmd.event_log.Write(
508 os.path.abspath(os.path.expanduser(gopts.event_log))
509 )
510
511 git_trace2_event_log.Write(gopts.git_trace2_event_log)
512 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700513
Conley Owens094cdbe2014-01-30 15:09:59 -0800514
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500515def _CheckWrapperVersion(ver_str, repo_path):
Gavin Makea2e3302023-03-11 06:46:20 +0000516 """Verify the repo launcher is new enough for this checkout.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500517
Gavin Makea2e3302023-03-11 06:46:20 +0000518 Args:
519 ver_str: The version string passed from the repo launcher when it ran
520 us.
521 repo_path: The path to the repo launcher that loaded us.
522 """
523 # Refuse to work with really old wrapper versions. We don't test these,
524 # so might as well require a somewhat recent sane version.
525 # v1.15 of the repo launcher was released in ~Mar 2012.
526 MIN_REPO_VERSION = (1, 15)
527 min_str = ".".join(str(x) for x in MIN_REPO_VERSION)
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500528
Gavin Makea2e3302023-03-11 06:46:20 +0000529 if not repo_path:
530 repo_path = "~/bin/repo"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700531
Gavin Makea2e3302023-03-11 06:46:20 +0000532 if not ver_str:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000533 logger.error("no --wrapper-version argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000534 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700535
Gavin Makea2e3302023-03-11 06:46:20 +0000536 # Pull out the version of the repo launcher we know about to compare.
537 exp = Wrapper().VERSION
538 ver = tuple(map(int, ver_str.split(".")))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539
Gavin Makea2e3302023-03-11 06:46:20 +0000540 exp_str = ".".join(map(str, exp))
541 if ver < MIN_REPO_VERSION:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000542 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000543 """
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500544repo: error:
545!!! Your version of repo %s is too old.
546!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900547!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500548!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700549
550 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000551""",
552 ver_str,
553 min_str,
554 exp_str,
555 WrapperPath(),
556 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000557 )
558 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700559
Gavin Makea2e3302023-03-11 06:46:20 +0000560 if exp > ver:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000561 logger.warning(
562 "\n... A new version of repo (%s) is available.", exp_str
563 )
Gavin Makea2e3302023-03-11 06:46:20 +0000564 if os.access(repo_path, os.W_OK):
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000565 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000566 """\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700567... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700568 cp %s %s
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000569""",
570 WrapperPath(),
571 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000572 )
573 else:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +0000574 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +0000575 """\
Mike Frysingereea23b42020-02-26 16:21:08 -0500576... New version is available at: %s
577... The launcher is run from: %s
578!!! The launcher is not writable. Please talk to your sysadmin or distro
579!!! to get an update installed.
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000580""",
581 WrapperPath(),
582 repo_path,
Gavin Makea2e3302023-03-11 06:46:20 +0000583 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700584
David Pursehouse819827a2020-02-12 15:20:19 +0900585
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200586def _CheckRepoDir(repo_dir):
Gavin Makea2e3302023-03-11 06:46:20 +0000587 if not repo_dir:
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000588 logger.error("no --repo-dir argument")
Gavin Makea2e3302023-03-11 06:46:20 +0000589 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700590
David Pursehouse819827a2020-02-12 15:20:19 +0900591
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700592def _PruneOptions(argv, opt):
Gavin Makea2e3302023-03-11 06:46:20 +0000593 i = 0
594 while i < len(argv):
595 a = argv[i]
596 if a == "--":
597 break
598 if a.startswith("--"):
599 eq = a.find("=")
600 if eq > 0:
601 a = a[0:eq]
602 if not opt.has_option(a):
603 del argv[i]
604 continue
605 i += 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700606
David Pursehouse819827a2020-02-12 15:20:19 +0900607
Sarah Owens1f7627f2012-10-31 09:21:55 -0700608class _UserAgentHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000609 def http_request(self, req):
610 req.add_header("User-Agent", user_agent.repo)
611 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700612
Gavin Makea2e3302023-03-11 06:46:20 +0000613 def https_request(self, req):
614 req.add_header("User-Agent", user_agent.repo)
615 return req
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700616
David Pursehouse819827a2020-02-12 15:20:19 +0900617
JoonCheol Parke9860722012-10-11 02:31:44 +0900618def _AddPasswordFromUserInput(handler, msg, req):
Gavin Makea2e3302023-03-11 06:46:20 +0000619 # If repo could not find auth info from netrc, try to get it from user input
620 url = req.get_full_url()
621 user, password = handler.passwd.find_user_password(None, url)
622 if user is None:
623 print(msg)
624 try:
625 user = input("User: ")
626 password = getpass.getpass()
627 except KeyboardInterrupt:
628 return
629 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900630
David Pursehouse819827a2020-02-12 15:20:19 +0900631
Sarah Owens1f7627f2012-10-31 09:21:55 -0700632class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000633 def http_error_401(self, req, fp, code, msg, headers):
634 _AddPasswordFromUserInput(self, msg, req)
635 return urllib.request.HTTPBasicAuthHandler.http_error_401(
636 self, req, fp, code, msg, headers
637 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900638
Gavin Makea2e3302023-03-11 06:46:20 +0000639 def http_error_auth_reqed(self, authreq, host, req, headers):
640 try:
641 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900642
Gavin Makea2e3302023-03-11 06:46:20 +0000643 def _add_header(name, val):
644 val = val.replace("\n", "")
645 old_add_header(name, val)
646
647 req.add_header = _add_header
648 return (
649 urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
650 self, authreq, host, req, headers
651 )
652 )
653 except Exception:
654 reset = getattr(self, "reset_retry_count", None)
655 if reset is not None:
656 reset()
657 elif getattr(self, "retried", None):
658 self.retried = 0
659 raise
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700660
David Pursehouse819827a2020-02-12 15:20:19 +0900661
Sarah Owens1f7627f2012-10-31 09:21:55 -0700662class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000663 def http_error_401(self, req, fp, code, msg, headers):
664 _AddPasswordFromUserInput(self, msg, req)
665 return urllib.request.HTTPDigestAuthHandler.http_error_401(
666 self, req, fp, code, msg, headers
667 )
JoonCheol Parke9860722012-10-11 02:31:44 +0900668
Gavin Makea2e3302023-03-11 06:46:20 +0000669 def http_error_auth_reqed(self, auth_header, host, req, headers):
670 try:
671 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900672
Gavin Makea2e3302023-03-11 06:46:20 +0000673 def _add_header(name, val):
674 val = val.replace("\n", "")
675 old_add_header(name, val)
676
677 req.add_header = _add_header
678 return (
679 urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
680 self, auth_header, host, req, headers
681 )
682 )
683 except Exception:
684 reset = getattr(self, "reset_retry_count", None)
685 if reset is not None:
686 reset()
687 elif getattr(self, "retried", None):
688 self.retried = 0
689 raise
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800690
David Pursehouse819827a2020-02-12 15:20:19 +0900691
Carlos Aguado1242e602014-02-03 13:48:47 +0100692class _KerberosAuthHandler(urllib.request.BaseHandler):
Gavin Makea2e3302023-03-11 06:46:20 +0000693 def __init__(self):
694 self.retried = 0
695 self.context = None
696 self.handler_order = urllib.request.BaseHandler.handler_order - 50
Carlos Aguado1242e602014-02-03 13:48:47 +0100697
Gavin Makea2e3302023-03-11 06:46:20 +0000698 def http_error_401(self, req, fp, code, msg, headers):
699 host = req.get_host()
700 retry = self.http_error_auth_reqed(
701 "www-authenticate", host, req, headers
702 )
703 return retry
Carlos Aguado1242e602014-02-03 13:48:47 +0100704
Gavin Makea2e3302023-03-11 06:46:20 +0000705 def http_error_auth_reqed(self, auth_header, host, req, headers):
706 try:
707 spn = "HTTP@%s" % host
708 authdata = self._negotiate_get_authdata(auth_header, headers)
Carlos Aguado1242e602014-02-03 13:48:47 +0100709
Gavin Makea2e3302023-03-11 06:46:20 +0000710 if self.retried > 3:
711 raise urllib.request.HTTPError(
712 req.get_full_url(),
713 401,
714 "Negotiate auth failed",
715 headers,
716 None,
717 )
718 else:
719 self.retried += 1
Carlos Aguado1242e602014-02-03 13:48:47 +0100720
Gavin Makea2e3302023-03-11 06:46:20 +0000721 neghdr = self._negotiate_get_svctk(spn, authdata)
722 if neghdr is None:
723 return None
724
725 req.add_unredirected_header("Authorization", neghdr)
726 response = self.parent.open(req)
727
728 srvauth = self._negotiate_get_authdata(auth_header, response.info())
729 if self._validate_response(srvauth):
730 return response
731 except kerberos.GSSError:
732 return None
733 except Exception:
734 self.reset_retry_count()
735 raise
736 finally:
737 self._clean_context()
738
739 def reset_retry_count(self):
740 self.retried = 0
741
742 def _negotiate_get_authdata(self, auth_header, headers):
743 authhdr = headers.get(auth_header, None)
744 if authhdr is not None:
745 for mech_tuple in authhdr.split(","):
746 mech, __, authdata = mech_tuple.strip().partition(" ")
747 if mech.lower() == "negotiate":
748 return authdata.strip()
Carlos Aguado1242e602014-02-03 13:48:47 +0100749 return None
750
Gavin Makea2e3302023-03-11 06:46:20 +0000751 def _negotiate_get_svctk(self, spn, authdata):
752 if authdata is None:
753 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100754
Gavin Makea2e3302023-03-11 06:46:20 +0000755 result, self.context = kerberos.authGSSClientInit(spn)
756 if result < kerberos.AUTH_GSS_COMPLETE:
757 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100758
Gavin Makea2e3302023-03-11 06:46:20 +0000759 result = kerberos.authGSSClientStep(self.context, authdata)
760 if result < kerberos.AUTH_GSS_CONTINUE:
761 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100762
Gavin Makea2e3302023-03-11 06:46:20 +0000763 response = kerberos.authGSSClientResponse(self.context)
764 return "Negotiate %s" % response
Carlos Aguado1242e602014-02-03 13:48:47 +0100765
Gavin Makea2e3302023-03-11 06:46:20 +0000766 def _validate_response(self, authdata):
767 if authdata is None:
768 return None
769 result = kerberos.authGSSClientStep(self.context, authdata)
770 if result == kerberos.AUTH_GSS_COMPLETE:
771 return True
772 return None
Carlos Aguado1242e602014-02-03 13:48:47 +0100773
Gavin Makea2e3302023-03-11 06:46:20 +0000774 def _clean_context(self):
775 if self.context is not None:
776 kerberos.authGSSClientClean(self.context)
777 self.context = None
Carlos Aguado1242e602014-02-03 13:48:47 +0100778
David Pursehouse819827a2020-02-12 15:20:19 +0900779
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700780def init_http():
Gavin Makea2e3302023-03-11 06:46:20 +0000781 handlers = [_UserAgentHandler()]
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700782
Gavin Makea2e3302023-03-11 06:46:20 +0000783 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
784 try:
785 n = netrc.netrc()
786 for host in n.hosts:
787 p = n.hosts[host]
788 mgr.add_password(p[1], "http://%s/" % host, p[0], p[2])
789 mgr.add_password(p[1], "https://%s/" % host, p[0], p[2])
790 except netrc.NetrcParseError:
791 pass
792 except IOError:
793 pass
794 handlers.append(_BasicAuthHandler(mgr))
795 handlers.append(_DigestAuthHandler(mgr))
796 if kerberos:
797 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700798
Gavin Makea2e3302023-03-11 06:46:20 +0000799 if "http_proxy" in os.environ:
800 url = os.environ["http_proxy"]
801 handlers.append(
802 urllib.request.ProxyHandler({"http": url, "https": url})
803 )
804 if "REPO_CURL_VERBOSE" in os.environ:
805 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
806 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
807 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700808
David Pursehouse819827a2020-02-12 15:20:19 +0900809
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700810def _Main(argv):
Gavin Makea2e3302023-03-11 06:46:20 +0000811 result = 0
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400812
Gavin Makea2e3302023-03-11 06:46:20 +0000813 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
814 opt.add_option("--repo-dir", dest="repodir", help="path to .repo/")
815 opt.add_option(
816 "--wrapper-version",
817 dest="wrapper_version",
818 help="version of the wrapper script",
819 )
820 opt.add_option(
821 "--wrapper-path",
822 dest="wrapper_path",
823 help="location of the wrapper script",
824 )
825 _PruneOptions(argv, opt)
826 opt, argv = opt.parse_args(argv)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700827
Gavin Makea2e3302023-03-11 06:46:20 +0000828 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
829 _CheckRepoDir(opt.repodir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700830
Gavin Makea2e3302023-03-11 06:46:20 +0000831 Version.wrapper_version = opt.wrapper_version
832 Version.wrapper_path = opt.wrapper_path
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800833
Gavin Makea2e3302023-03-11 06:46:20 +0000834 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400835
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700836 try:
Gavin Makea2e3302023-03-11 06:46:20 +0000837 init_http()
838 name, gopts, argv = repo._ParseArgs(argv)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400839
Gavin Makea2e3302023-03-11 06:46:20 +0000840 if gopts.trace:
841 SetTrace()
842
843 if gopts.trace_to_stderr:
844 SetTraceToStderr()
845
846 result = repo._Run(name, gopts, argv) or 0
Jason Chang32b59562023-07-14 16:45:35 -0700847 except RepoExitError as e:
Jason Chang1a3612f2023-08-08 14:12:53 -0700848 if not isinstance(e, SilentRepoExitError):
Aravind Vasudevanb8fd1922023-09-14 22:54:04 +0000849 logger.log_aggregated_errors(e)
Jason Chang32b59562023-07-14 16:45:35 -0700850 result = e.exit_code
Gavin Makea2e3302023-03-11 06:46:20 +0000851 except KeyboardInterrupt:
852 print("aborted by user", file=sys.stderr)
Jason Changc6578442023-06-22 15:04:06 -0700853 result = KEYBOARD_INTERRUPT_EXIT
Gavin Makea2e3302023-03-11 06:46:20 +0000854 except RepoChangedException as rce:
855 # If repo changed, re-exec ourselves.
Gavin Makea2e3302023-03-11 06:46:20 +0000856 argv = list(sys.argv)
857 argv.extend(rce.extra_args)
858 try:
Gavin Makf1ddaaa2023-08-04 21:13:38 +0000859 os.execv(sys.executable, [sys.executable, __file__] + argv)
Gavin Makea2e3302023-03-11 06:46:20 +0000860 except OSError as e:
861 print("fatal: cannot restart repo after upgrade", file=sys.stderr)
862 print("fatal: %s" % e, file=sys.stderr)
863 result = 128
864
865 TerminatePager()
866 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700867
David Pursehouse819827a2020-02-12 15:20:19 +0900868
Gavin Makea2e3302023-03-11 06:46:20 +0000869if __name__ == "__main__":
870 _Main(sys.argv[1:])