blob: f4b6e7ac95cd53da88b9165b2e9514d74efd5ab6 [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
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070024import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025import optparse
26import os
Mike Frysinger949bc342020-02-18 21:37:00 -050027import shlex
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050029import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070030import time
Mike Frysingeracf63b22019-06-13 02:24:21 -040031import urllib.request
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
Carlos Aguado1242e602014-02-03 13:48:47 +010033try:
34 import kerberos
35except ImportError:
36 kerberos = None
37
Mike Frysinger902665b2014-12-22 15:17:59 -050038from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070039import event_log
Joanna Wanga6c52f52022-11-03 16:51:19 -040040from repo_trace import SetTrace, Trace, SetTraceToStderr
David Pursehouse9090e802020-02-12 11:25:13 +090041from git_command import user_agent
Mike Frysinger5291eaf2021-05-05 15:53:03 -040042from git_config import RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080043from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080044from command import InteractiveCommand
45from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070046from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080047from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070048from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070049from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070050from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080051from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090052from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080053from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070054from error import NoSuchProjectError
55from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070056import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040057from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070058from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080059from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070060
David Pursehouse5c6eeac2012-10-11 16:44:48 +090061from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070062
Chirayu Desai217ea7d2013-03-01 19:14:38 +053063
Mike Frysinger37f28f12020-02-16 15:15:53 -050064# NB: These do not need to be kept in sync with the repo launcher script.
65# These may be much newer as it allows the repo launcher to roll between
66# different repo releases while source versions might require a newer python.
67#
68# The soft version is when we start warning users that the version is old and
69# we'll be dropping support for it. We'll refuse to work with versions older
70# than the hard version.
71#
72# python-3.6 is in Ubuntu Bionic.
73MIN_PYTHON_VERSION_SOFT = (3, 6)
Peter Kjellerstedta3b2edf2021-04-15 01:32:40 +020074MIN_PYTHON_VERSION_HARD = (3, 6)
Mike Frysinger37f28f12020-02-16 15:15:53 -050075
76if sys.version_info.major < 3:
Mike Frysingera488af52020-09-06 13:33:45 -040077 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050078 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
79 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040080 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050081else:
82 if sys.version_info < MIN_PYTHON_VERSION_HARD:
83 print('repo: error: Python 3 version is too old; '
84 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
85 file=sys.stderr)
86 sys.exit(1)
87 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
88 print('repo: warning: your Python 3 version is no longer supported; '
89 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
90 file=sys.stderr)
91
92
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070093global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -050094 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
95 add_help_option=False)
96global_options.add_option('-h', '--help', action='store_true',
97 help='show this help message and exit')
Mike Frysinger56345c32021-07-26 23:46:32 -040098global_options.add_option('--help-all', action='store_true',
99 help='show this help message with all subcommands and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100global_options.add_option('-p', '--paginate',
101 dest='pager', action='store_true',
102 help='display command output in the pager')
103global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500104 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500106global_options.add_option('--color',
107 choices=('auto', 'always', 'never'), default=None,
108 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700109global_options.add_option('--trace',
110 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400111 help='trace git command execution (REPO_TRACE=1)')
Joanna Wang24c63142022-11-08 18:56:52 -0500112global_options.add_option('--trace-to-stderr',
Joanna Wanga6c52f52022-11-03 16:51:19 -0400113 dest='trace_to_stderr', action='store_true',
114 help='trace outputs go to stderr in addition to .repo/TRACE_FILE')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400115global_options.add_option('--trace-python',
116 dest='trace_python', action='store_true',
117 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700118global_options.add_option('--time',
119 dest='time', action='store_true',
120 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800121global_options.add_option('--version',
122 dest='show_version', action='store_true',
123 help='display this version of repo')
Mike Frysinger73c43b82021-07-26 15:42:59 -0400124global_options.add_option('--show-toplevel',
125 action='store_true',
126 help='display the path of the top-level directory of '
127 'the repo client checkout')
David Rileye0684ad2017-04-05 00:02:59 -0700128global_options.add_option('--event-log',
129 dest='event_log', action='store',
130 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800131global_options.add_option('--git-trace2-event-log', action='store',
132 help='directory to write git trace2 event log to')
LaMont Jonescc879a92021-11-18 22:40:18 +0000133global_options.add_option('--submanifest-path', action='store',
134 metavar='REL_PATH', help='submanifest path')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135
David Pursehouse819827a2020-02-12 15:20:19 +0900136
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137class _Repo(object):
138 def __init__(self, repodir):
139 self.repodir = repodir
140 self.commands = all_commands
141
Mike Frysinger56345c32021-07-26 23:46:32 -0400142 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
143 """Show --help screen."""
144 global_options.print_help()
145 print()
146 if short:
147 commands = ' '.join(sorted(self.commands))
148 wrapped_commands = textwrap.wrap(commands, width=77)
149 print('Available commands:\n %s' % ('\n '.join(wrapped_commands),))
150 print('\nRun `repo help <command>` for command-specific details.')
151 print('Bug reports:', Wrapper().BUG_URL)
152 else:
153 cmd = self.commands['help']()
154 if all_commands:
155 cmd.PrintAllCommandsBody()
156 else:
157 cmd.PrintCommonCommandsBody()
158
Mike Frysinger3fc15722019-08-27 00:36:46 -0400159 def _ParseArgs(self, argv):
160 """Parse the main `repo` command line options."""
Mike Frysinger968d6462021-07-26 23:20:29 -0400161 for i, arg in enumerate(argv):
162 if not arg.startswith('-'):
163 name = arg
164 glob = argv[:i]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700165 argv = argv[i + 1:]
166 break
Mike Frysinger968d6462021-07-26 23:20:29 -0400167 else:
168 name = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169 glob = argv
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700170 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900171 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700172
Mike Frysinger968d6462021-07-26 23:20:29 -0400173 if name:
174 name, alias_args = self._ExpandAlias(name)
175 argv = alias_args + argv
Mike Frysinger7c321f12019-12-02 16:49:44 -0500176
Mike Frysinger3fc15722019-08-27 00:36:46 -0400177 return (name, gopts, argv)
178
Mike Frysinger949bc342020-02-18 21:37:00 -0500179 def _ExpandAlias(self, name):
180 """Look up user registered aliases."""
181 # We don't resolve aliases for existing subcommands. This matches git.
182 if name in self.commands:
183 return name, []
184
185 key = 'alias.%s' % (name,)
186 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
187 if alias is None:
188 alias = RepoConfig.ForUser().GetString(key)
189 if alias is None:
190 return name, []
191
192 args = alias.strip().split(' ', 1)
193 name = args[0]
194 if len(args) == 2:
195 args = shlex.split(args[1])
196 else:
197 args = []
198 return name, args
199
Mike Frysinger3fc15722019-08-27 00:36:46 -0400200 def _Run(self, name, gopts, argv):
201 """Execute the requested subcommand."""
202 result = 0
203
Mike Frysinger968d6462021-07-26 23:20:29 -0400204 # Handle options that terminate quickly first.
Mike Frysinger56345c32021-07-26 23:46:32 -0400205 if gopts.help or gopts.help_all:
206 self._PrintHelp(short=False, all_commands=gopts.help_all)
Mike Frysinger968d6462021-07-26 23:20:29 -0400207 return 0
208 elif gopts.show_version:
Mike Frysingera024bd32021-07-26 23:31:06 -0400209 # Always allow global --version regardless of subcommand validity.
Mike Frysinger968d6462021-07-26 23:20:29 -0400210 name = 'version'
Mike Frysinger73c43b82021-07-26 15:42:59 -0400211 elif gopts.show_toplevel:
212 print(os.path.dirname(self.repodir))
213 return 0
Mike Frysinger968d6462021-07-26 23:20:29 -0400214 elif not name:
215 # No subcommand specified, so show the help/subcommand.
Mike Frysinger56345c32021-07-26 23:46:32 -0400216 self._PrintHelp(short=True)
217 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800218
LaMont Jonesa3ff64c2022-11-07 23:19:14 +0000219 run = lambda: self._RunLong(name, gopts, argv) or 0
220 with Trace('starting new command: %s', ', '.join([name] + argv),
221 first_trace=True):
222 if gopts.trace_python:
223 import trace
224 tracer = trace.Trace(count=False, trace=True, timing=True,
225 ignoredirs=set(sys.path[1:]))
226 result = tracer.runfunc(run)
227 else:
228 result = run()
229 return result
230
231 def _RunLong(self, name, gopts, argv):
232 """Execute the (longer running) requested subcommand."""
233 result = 0
Mike Frysinger902665b2014-12-22 15:17:59 -0500234 SetDefaultColoring(gopts.color)
235
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400236 git_trace2_event_log = EventLog()
LaMont Jonescc879a92021-11-18 22:40:18 +0000237 outer_client = RepoClient(self.repodir)
238 repo_client = outer_client
239 if gopts.submanifest_path:
240 repo_client = RepoClient(self.repodir,
241 submanifest_path=gopts.submanifest_path,
242 outer_client=outer_client)
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400243 gitc_manifest = None
244 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
245 if gitc_client_name:
246 gitc_manifest = GitcClient(self.repodir, gitc_client_name)
247 repo_client.isGitcClient = True
248
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249 try:
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400250 cmd = self.commands[name](
251 repodir=self.repodir,
252 client=repo_client,
253 manifest=repo_client.manifest,
LaMont Jonescc879a92021-11-18 22:40:18 +0000254 outer_client=outer_client,
255 outer_manifest=outer_client.manifest,
Raman Tenneti784e16f2021-06-11 17:29:45 -0700256 gitc_manifest=gitc_manifest,
257 git_event_log=git_trace2_event_log)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700259 print("repo: '%s' is not a repo command. See 'repo help'." % name,
260 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400261 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700262
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400263 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700264
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800265 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700266 print("fatal: '%s' requires a working directory" % name,
267 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400268 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800269
Dan Willemsen79360642015-08-31 15:45:06 -0700270 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700271 print("fatal: '%s' requires GITC to be available" % name,
272 file=sys.stderr)
273 return 1
274
Dan Willemsen79360642015-08-31 15:45:06 -0700275 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
276 print("fatal: '%s' requires a GITC client" % name,
277 file=sys.stderr)
278 return 1
279
Dan Sandler53e902a2014-03-09 13:20:02 -0400280 try:
281 copts, cargs = cmd.OptionParser.parse_args(argv)
282 copts = cmd.ReadEnvironmentOptions(copts)
283 except NoManifestException as e:
284 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900285 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400286 print('error: manifest missing or unreadable -- please run init',
287 file=sys.stderr)
288 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700289
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500290 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400291 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700292 if gopts.pager:
293 use_pager = True
294 else:
295 use_pager = config.GetBoolean('pager.%s' % name)
296 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700297 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700298 if use_pager:
299 RunPager(config)
300
Conley Owens7ba25be2012-11-14 14:18:06 -0800301 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700302 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
303 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800304 git_trace2_event_log.StartEvent()
Raman Tennetia5b40a22021-03-16 14:24:14 -0700305 git_trace2_event_log.CommandEvent(name='repo', subcommands=[name])
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800306
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700307 try:
Mike Frysinger9180a072021-04-13 14:57:40 -0400308 cmd.CommonValidateOptions(copts, cargs)
Mike Frysingerae6cb082019-08-27 01:10:59 -0400309 cmd.ValidateOptions(copts, cargs)
LaMont Jonescc879a92021-11-18 22:40:18 +0000310
311 this_manifest_only = copts.this_manifest_only
LaMont Jonesbdcba7d2022-04-11 22:50:11 +0000312 outer_manifest = copts.outer_manifest
LaMont Jonescc879a92021-11-18 22:40:18 +0000313 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
314 result = cmd.Execute(copts, cargs)
315 elif outer_manifest and repo_client.manifest.is_submanifest:
316 # The command does not support multi-manifest, we are using a
317 # submanifest, and the command line is for the outermost manifest.
318 # Re-run using the outermost manifest, which will recurse through the
319 # submanifests.
320 gopts.submanifest_path = ''
321 result = self._Run(name, gopts, argv)
322 else:
323 # No multi-manifest support. Run the command in the current
324 # (sub)manifest, and then any child submanifests.
325 result = cmd.Execute(copts, cargs)
326 for submanifest in repo_client.manifest.submanifests.values():
LaMont Jonesb90a4222022-04-14 15:00:09 +0000327 spec = submanifest.ToSubmanifestSpec()
LaMont Jonescc879a92021-11-18 22:40:18 +0000328 gopts.submanifest_path = submanifest.repo_client.path_prefix
329 child_argv = argv[:]
330 child_argv.append('--no-outer-manifest')
331 # Not all subcommands support the 3 manifest options, so only add them
332 # if the original command includes them.
333 if hasattr(copts, 'manifest_url'):
334 child_argv.extend(['--manifest-url', spec.manifestUrl])
335 if hasattr(copts, 'manifest_name'):
336 child_argv.extend(['--manifest-name', spec.manifestName])
337 if hasattr(copts, 'manifest_branch'):
338 child_argv.extend(['--manifest-branch', spec.revision])
339 result = self._Run(name, gopts, child_argv) or result
Dan Sandler53e902a2014-03-09 13:20:02 -0400340 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900341 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400342 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900343 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400344 if isinstance(e, NoManifestException):
345 print('error: manifest missing or unreadable -- please run init',
346 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800347 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700348 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700350 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700351 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700352 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800353 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700354 except InvalidProjectGroupsError as e:
355 if e.name:
356 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
357 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900358 print('error: project group must be enabled for the project in the current directory',
359 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700360 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700361 except SystemExit as e:
362 if e.code:
363 result = e.code
364 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800365 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700366 finish = time.time()
367 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800368 hours, remainder = divmod(elapsed, 3600)
369 minutes, seconds = divmod(remainder, 60)
370 if gopts.time:
371 if hours == 0:
372 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
373 else:
374 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
375 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400376
David Rileye0684ad2017-04-05 00:02:59 -0700377 cmd.event_log.FinishEvent(cmd_event, finish,
378 result is None or result == 0)
Ian Kasprzak835a34b2021-03-05 11:04:49 -0800379 git_trace2_event_log.DefParamRepoEvents(
380 cmd.manifest.manifestProject.config.DumpConfigDict())
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800381 git_trace2_event_log.ExitEvent(result)
382
David Rileye0684ad2017-04-05 00:02:59 -0700383 if gopts.event_log:
384 cmd.event_log.Write(os.path.abspath(
385 os.path.expanduser(gopts.event_log)))
386
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800387 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400388 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700389
Conley Owens094cdbe2014-01-30 15:09:59 -0800390
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500391def _CheckWrapperVersion(ver_str, repo_path):
392 """Verify the repo launcher is new enough for this checkout.
393
394 Args:
395 ver_str: The version string passed from the repo launcher when it ran us.
396 repo_path: The path to the repo launcher that loaded us.
397 """
398 # Refuse to work with really old wrapper versions. We don't test these,
399 # so might as well require a somewhat recent sane version.
400 # v1.15 of the repo launcher was released in ~Mar 2012.
401 MIN_REPO_VERSION = (1, 15)
402 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
403
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700404 if not repo_path:
405 repo_path = '~/bin/repo'
406
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500407 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700408 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900409 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500411 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800412 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500413 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700414
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900415 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500416 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700417 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500418repo: error:
419!!! Your version of repo %s is too old.
420!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900421!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500422!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700423
424 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500425""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700426 sys.exit(1)
427
428 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500429 print('\n... A new version of repo (%s) is available.' % (exp_str,),
430 file=sys.stderr)
431 if os.access(repo_path, os.W_OK):
432 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700433... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700434 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500435""" % (WrapperPath(), repo_path), file=sys.stderr)
436 else:
437 print("""\
438... New version is available at: %s
439... The launcher is run from: %s
440!!! The launcher is not writable. Please talk to your sysadmin or distro
441!!! to get an update installed.
442""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700443
David Pursehouse819827a2020-02-12 15:20:19 +0900444
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200445def _CheckRepoDir(repo_dir):
446 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700447 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900448 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700449
David Pursehouse819827a2020-02-12 15:20:19 +0900450
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700451def _PruneOptions(argv, opt):
452 i = 0
453 while i < len(argv):
454 a = argv[i]
455 if a == '--':
456 break
457 if a.startswith('--'):
458 eq = a.find('=')
459 if eq > 0:
460 a = a[0:eq]
461 if not opt.has_option(a):
462 del argv[i]
463 continue
464 i += 1
465
David Pursehouse819827a2020-02-12 15:20:19 +0900466
Sarah Owens1f7627f2012-10-31 09:21:55 -0700467class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700468 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400469 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700470 return req
471
472 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400473 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700474 return req
475
David Pursehouse819827a2020-02-12 15:20:19 +0900476
JoonCheol Parke9860722012-10-11 02:31:44 +0900477def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900478 # If repo could not find auth info from netrc, try to get it from user input
479 url = req.get_full_url()
480 user, password = handler.passwd.find_user_password(None, url)
481 if user is None:
482 print(msg)
483 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530484 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900485 password = getpass.getpass()
486 except KeyboardInterrupt:
487 return
488 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900489
David Pursehouse819827a2020-02-12 15:20:19 +0900490
Sarah Owens1f7627f2012-10-31 09:21:55 -0700491class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900492 def http_error_401(self, req, fp, code, msg, headers):
493 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700494 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900495 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900496
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700497 def http_error_auth_reqed(self, authreq, host, req, headers):
498 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700499 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900500
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700501 def _add_header(name, val):
502 val = val.replace('\n', '')
503 old_add_header(name, val)
504 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700505 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900506 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900507 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700508 reset = getattr(self, 'reset_retry_count', None)
509 if reset is not None:
510 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700511 elif getattr(self, 'retried', None):
512 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700513 raise
514
David Pursehouse819827a2020-02-12 15:20:19 +0900515
Sarah Owens1f7627f2012-10-31 09:21:55 -0700516class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900517 def http_error_401(self, req, fp, code, msg, headers):
518 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700519 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900520 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900521
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800522 def http_error_auth_reqed(self, auth_header, host, req, headers):
523 try:
524 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900525
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800526 def _add_header(name, val):
527 val = val.replace('\n', '')
528 old_add_header(name, val)
529 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700530 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900531 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900532 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800533 reset = getattr(self, 'reset_retry_count', None)
534 if reset is not None:
535 reset()
536 elif getattr(self, 'retried', None):
537 self.retried = 0
538 raise
539
David Pursehouse819827a2020-02-12 15:20:19 +0900540
Carlos Aguado1242e602014-02-03 13:48:47 +0100541class _KerberosAuthHandler(urllib.request.BaseHandler):
542 def __init__(self):
543 self.retried = 0
544 self.context = None
545 self.handler_order = urllib.request.BaseHandler.handler_order - 50
546
David Pursehouse65b0ba52018-06-24 16:21:51 +0900547 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100548 host = req.get_host()
549 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
550 return retry
551
552 def http_error_auth_reqed(self, auth_header, host, req, headers):
553 try:
554 spn = "HTTP@%s" % host
555 authdata = self._negotiate_get_authdata(auth_header, headers)
556
557 if self.retried > 3:
558 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900559 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100560 else:
561 self.retried += 1
562
563 neghdr = self._negotiate_get_svctk(spn, authdata)
564 if neghdr is None:
565 return None
566
567 req.add_unredirected_header('Authorization', neghdr)
568 response = self.parent.open(req)
569
570 srvauth = self._negotiate_get_authdata(auth_header, response.info())
571 if self._validate_response(srvauth):
572 return response
573 except kerberos.GSSError:
574 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900575 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100576 self.reset_retry_count()
577 raise
578 finally:
579 self._clean_context()
580
581 def reset_retry_count(self):
582 self.retried = 0
583
584 def _negotiate_get_authdata(self, auth_header, headers):
585 authhdr = headers.get(auth_header, None)
586 if authhdr is not None:
587 for mech_tuple in authhdr.split(","):
588 mech, __, authdata = mech_tuple.strip().partition(" ")
589 if mech.lower() == "negotiate":
590 return authdata.strip()
591 return None
592
593 def _negotiate_get_svctk(self, spn, authdata):
594 if authdata is None:
595 return None
596
597 result, self.context = kerberos.authGSSClientInit(spn)
598 if result < kerberos.AUTH_GSS_COMPLETE:
599 return None
600
601 result = kerberos.authGSSClientStep(self.context, authdata)
602 if result < kerberos.AUTH_GSS_CONTINUE:
603 return None
604
605 response = kerberos.authGSSClientResponse(self.context)
606 return "Negotiate %s" % response
607
608 def _validate_response(self, authdata):
609 if authdata is None:
610 return None
611 result = kerberos.authGSSClientStep(self.context, authdata)
612 if result == kerberos.AUTH_GSS_COMPLETE:
613 return True
614 return None
615
616 def _clean_context(self):
617 if self.context is not None:
618 kerberos.authGSSClientClean(self.context)
619 self.context = None
620
David Pursehouse819827a2020-02-12 15:20:19 +0900621
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700622def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700623 handlers = [_UserAgentHandler()]
624
Sarah Owens1f7627f2012-10-31 09:21:55 -0700625 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700626 try:
627 n = netrc.netrc()
628 for host in n.hosts:
629 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900630 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800631 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700632 except netrc.NetrcParseError:
633 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700634 except IOError:
635 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700636 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800637 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100638 if kerberos:
639 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700640
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700641 if 'http_proxy' in os.environ:
642 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700643 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700644 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700645 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
646 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
647 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700648
David Pursehouse819827a2020-02-12 15:20:19 +0900649
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700650def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400651 result = 0
652
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700653 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
654 opt.add_option("--repo-dir", dest="repodir",
655 help="path to .repo/")
656 opt.add_option("--wrapper-version", dest="wrapper_version",
657 help="version of the wrapper script")
658 opt.add_option("--wrapper-path", dest="wrapper_path",
659 help="location of the wrapper script")
660 _PruneOptions(argv, opt)
661 opt, argv = opt.parse_args(argv)
662
663 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
664 _CheckRepoDir(opt.repodir)
665
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800666 Version.wrapper_version = opt.wrapper_version
667 Version.wrapper_path = opt.wrapper_path
668
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700669 repo = _Repo(opt.repodir)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400670
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700671 try:
Mike Frysinger19e409c2021-05-05 19:44:35 -0400672 init_http()
673 name, gopts, argv = repo._ParseArgs(argv)
Joanna Wanga6c52f52022-11-03 16:51:19 -0400674
675 if gopts.trace:
676 SetTrace()
677
678 if gopts.trace_to_stderr:
679 SetTraceToStderr()
680
LaMont Jonesa3ff64c2022-11-07 23:19:14 +0000681 result = repo._Run(name, gopts, argv) or 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700682 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700683 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400684 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900685 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700686 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900687 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700688 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800689 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700690 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800691 argv = list(sys.argv)
692 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700693 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400694 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700695 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700696 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
697 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400698 result = 128
699
Renaud Paquaye8595e92016-11-01 15:51:59 -0700700 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400701 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700702
David Pursehouse819827a2020-02-12 15:20:19 +0900703
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700704if __name__ == '__main__':
705 _Main(sys.argv[1:])