blob: 34dfb7774d2c10b4f43d8ad40c874766a8e42532 [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
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040040from repo_trace import SetTrace
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)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400112global_options.add_option('--trace-python',
113 dest='trace_python', action='store_true',
114 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700115global_options.add_option('--time',
116 dest='time', action='store_true',
117 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800118global_options.add_option('--version',
119 dest='show_version', action='store_true',
120 help='display this version of repo')
Mike Frysinger73c43b82021-07-26 15:42:59 -0400121global_options.add_option('--show-toplevel',
122 action='store_true',
123 help='display the path of the top-level directory of '
124 'the repo client checkout')
David Rileye0684ad2017-04-05 00:02:59 -0700125global_options.add_option('--event-log',
126 dest='event_log', action='store',
127 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800128global_options.add_option('--git-trace2-event-log', action='store',
129 help='directory to write git trace2 event log to')
LaMont Jonescc879a92021-11-18 22:40:18 +0000130global_options.add_option('--submanifest-path', action='store',
131 metavar='REL_PATH', help='submanifest path')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700132
David Pursehouse819827a2020-02-12 15:20:19 +0900133
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134class _Repo(object):
135 def __init__(self, repodir):
136 self.repodir = repodir
137 self.commands = all_commands
138
Mike Frysinger56345c32021-07-26 23:46:32 -0400139 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
140 """Show --help screen."""
141 global_options.print_help()
142 print()
143 if short:
144 commands = ' '.join(sorted(self.commands))
145 wrapped_commands = textwrap.wrap(commands, width=77)
146 print('Available commands:\n %s' % ('\n '.join(wrapped_commands),))
147 print('\nRun `repo help <command>` for command-specific details.')
148 print('Bug reports:', Wrapper().BUG_URL)
149 else:
150 cmd = self.commands['help']()
151 if all_commands:
152 cmd.PrintAllCommandsBody()
153 else:
154 cmd.PrintCommonCommandsBody()
155
Mike Frysinger3fc15722019-08-27 00:36:46 -0400156 def _ParseArgs(self, argv):
157 """Parse the main `repo` command line options."""
Mike Frysinger968d6462021-07-26 23:20:29 -0400158 for i, arg in enumerate(argv):
159 if not arg.startswith('-'):
160 name = arg
161 glob = argv[:i]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700162 argv = argv[i + 1:]
163 break
Mike Frysinger968d6462021-07-26 23:20:29 -0400164 else:
165 name = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700166 glob = argv
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700167 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900168 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169
Mike Frysinger968d6462021-07-26 23:20:29 -0400170 if name:
171 name, alias_args = self._ExpandAlias(name)
172 argv = alias_args + argv
Mike Frysinger7c321f12019-12-02 16:49:44 -0500173
Mike Frysinger3fc15722019-08-27 00:36:46 -0400174 return (name, gopts, argv)
175
Mike Frysinger949bc342020-02-18 21:37:00 -0500176 def _ExpandAlias(self, name):
177 """Look up user registered aliases."""
178 # We don't resolve aliases for existing subcommands. This matches git.
179 if name in self.commands:
180 return name, []
181
182 key = 'alias.%s' % (name,)
183 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
184 if alias is None:
185 alias = RepoConfig.ForUser().GetString(key)
186 if alias is None:
187 return name, []
188
189 args = alias.strip().split(' ', 1)
190 name = args[0]
191 if len(args) == 2:
192 args = shlex.split(args[1])
193 else:
194 args = []
195 return name, args
196
Mike Frysinger3fc15722019-08-27 00:36:46 -0400197 def _Run(self, name, gopts, argv):
198 """Execute the requested subcommand."""
199 result = 0
200
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700201 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700202 SetTrace()
Mike Frysinger968d6462021-07-26 23:20:29 -0400203
204 # 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
Mike Frysinger902665b2014-12-22 15:17:59 -0500219 SetDefaultColoring(gopts.color)
220
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400221 git_trace2_event_log = EventLog()
LaMont Jonescc879a92021-11-18 22:40:18 +0000222 outer_client = RepoClient(self.repodir)
223 repo_client = outer_client
224 if gopts.submanifest_path:
225 repo_client = RepoClient(self.repodir,
226 submanifest_path=gopts.submanifest_path,
227 outer_client=outer_client)
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400228 gitc_manifest = None
229 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
230 if gitc_client_name:
231 gitc_manifest = GitcClient(self.repodir, gitc_client_name)
232 repo_client.isGitcClient = True
233
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234 try:
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400235 cmd = self.commands[name](
236 repodir=self.repodir,
237 client=repo_client,
238 manifest=repo_client.manifest,
LaMont Jonescc879a92021-11-18 22:40:18 +0000239 outer_client=outer_client,
240 outer_manifest=outer_client.manifest,
Raman Tenneti784e16f2021-06-11 17:29:45 -0700241 gitc_manifest=gitc_manifest,
242 git_event_log=git_trace2_event_log)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700243 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700244 print("repo: '%s' is not a repo command. See 'repo help'." % name,
245 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400246 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700247
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400248 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800250 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700251 print("fatal: '%s' requires a working directory" % name,
252 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400253 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800254
Dan Willemsen79360642015-08-31 15:45:06 -0700255 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700256 print("fatal: '%s' requires GITC to be available" % name,
257 file=sys.stderr)
258 return 1
259
Dan Willemsen79360642015-08-31 15:45:06 -0700260 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
261 print("fatal: '%s' requires a GITC client" % name,
262 file=sys.stderr)
263 return 1
264
Dan Sandler53e902a2014-03-09 13:20:02 -0400265 try:
266 copts, cargs = cmd.OptionParser.parse_args(argv)
267 copts = cmd.ReadEnvironmentOptions(copts)
268 except NoManifestException as e:
269 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900270 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400271 print('error: manifest missing or unreadable -- please run init',
272 file=sys.stderr)
273 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700274
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500275 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400276 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700277 if gopts.pager:
278 use_pager = True
279 else:
280 use_pager = config.GetBoolean('pager.%s' % name)
281 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700282 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700283 if use_pager:
284 RunPager(config)
285
Conley Owens7ba25be2012-11-14 14:18:06 -0800286 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700287 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
288 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800289 git_trace2_event_log.StartEvent()
Raman Tennetia5b40a22021-03-16 14:24:14 -0700290 git_trace2_event_log.CommandEvent(name='repo', subcommands=[name])
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800291
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700292 try:
Mike Frysinger9180a072021-04-13 14:57:40 -0400293 cmd.CommonValidateOptions(copts, cargs)
Mike Frysingerae6cb082019-08-27 01:10:59 -0400294 cmd.ValidateOptions(copts, cargs)
LaMont Jonescc879a92021-11-18 22:40:18 +0000295
296 this_manifest_only = copts.this_manifest_only
297 # If not specified, default to using the outer manifest.
298 outer_manifest = copts.outer_manifest is not False
299 if cmd.MULTI_MANIFEST_SUPPORT or this_manifest_only:
300 result = cmd.Execute(copts, cargs)
301 elif outer_manifest and repo_client.manifest.is_submanifest:
302 # The command does not support multi-manifest, we are using a
303 # submanifest, and the command line is for the outermost manifest.
304 # Re-run using the outermost manifest, which will recurse through the
305 # submanifests.
306 gopts.submanifest_path = ''
307 result = self._Run(name, gopts, argv)
308 else:
309 # No multi-manifest support. Run the command in the current
310 # (sub)manifest, and then any child submanifests.
311 result = cmd.Execute(copts, cargs)
312 for submanifest in repo_client.manifest.submanifests.values():
LaMont Jonesb90a4222022-04-14 15:00:09 +0000313 spec = submanifest.ToSubmanifestSpec()
LaMont Jonescc879a92021-11-18 22:40:18 +0000314 gopts.submanifest_path = submanifest.repo_client.path_prefix
315 child_argv = argv[:]
316 child_argv.append('--no-outer-manifest')
317 # Not all subcommands support the 3 manifest options, so only add them
318 # if the original command includes them.
319 if hasattr(copts, 'manifest_url'):
320 child_argv.extend(['--manifest-url', spec.manifestUrl])
321 if hasattr(copts, 'manifest_name'):
322 child_argv.extend(['--manifest-name', spec.manifestName])
323 if hasattr(copts, 'manifest_branch'):
324 child_argv.extend(['--manifest-branch', spec.revision])
325 result = self._Run(name, gopts, child_argv) or result
Dan Sandler53e902a2014-03-09 13:20:02 -0400326 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900327 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400328 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900329 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400330 if isinstance(e, NoManifestException):
331 print('error: manifest missing or unreadable -- please run init',
332 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800333 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700334 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700335 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700336 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700338 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800339 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700340 except InvalidProjectGroupsError as e:
341 if e.name:
342 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
343 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900344 print('error: project group must be enabled for the project in the current directory',
345 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700346 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700347 except SystemExit as e:
348 if e.code:
349 result = e.code
350 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800351 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700352 finish = time.time()
353 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800354 hours, remainder = divmod(elapsed, 3600)
355 minutes, seconds = divmod(remainder, 60)
356 if gopts.time:
357 if hours == 0:
358 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
359 else:
360 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
361 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400362
David Rileye0684ad2017-04-05 00:02:59 -0700363 cmd.event_log.FinishEvent(cmd_event, finish,
364 result is None or result == 0)
Ian Kasprzak835a34b2021-03-05 11:04:49 -0800365 git_trace2_event_log.DefParamRepoEvents(
366 cmd.manifest.manifestProject.config.DumpConfigDict())
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800367 git_trace2_event_log.ExitEvent(result)
368
David Rileye0684ad2017-04-05 00:02:59 -0700369 if gopts.event_log:
370 cmd.event_log.Write(os.path.abspath(
371 os.path.expanduser(gopts.event_log)))
372
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800373 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400374 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700375
Conley Owens094cdbe2014-01-30 15:09:59 -0800376
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500377def _CheckWrapperVersion(ver_str, repo_path):
378 """Verify the repo launcher is new enough for this checkout.
379
380 Args:
381 ver_str: The version string passed from the repo launcher when it ran us.
382 repo_path: The path to the repo launcher that loaded us.
383 """
384 # Refuse to work with really old wrapper versions. We don't test these,
385 # so might as well require a somewhat recent sane version.
386 # v1.15 of the repo launcher was released in ~Mar 2012.
387 MIN_REPO_VERSION = (1, 15)
388 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
389
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700390 if not repo_path:
391 repo_path = '~/bin/repo'
392
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500393 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700394 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900395 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700396
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500397 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800398 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500399 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700400
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900401 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500402 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700403 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500404repo: error:
405!!! Your version of repo %s is too old.
406!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900407!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500408!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700409
410 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500411""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700412 sys.exit(1)
413
414 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500415 print('\n... A new version of repo (%s) is available.' % (exp_str,),
416 file=sys.stderr)
417 if os.access(repo_path, os.W_OK):
418 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700419... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700420 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500421""" % (WrapperPath(), repo_path), file=sys.stderr)
422 else:
423 print("""\
424... New version is available at: %s
425... The launcher is run from: %s
426!!! The launcher is not writable. Please talk to your sysadmin or distro
427!!! to get an update installed.
428""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700429
David Pursehouse819827a2020-02-12 15:20:19 +0900430
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200431def _CheckRepoDir(repo_dir):
432 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700433 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900434 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700435
David Pursehouse819827a2020-02-12 15:20:19 +0900436
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700437def _PruneOptions(argv, opt):
438 i = 0
439 while i < len(argv):
440 a = argv[i]
441 if a == '--':
442 break
443 if a.startswith('--'):
444 eq = a.find('=')
445 if eq > 0:
446 a = a[0:eq]
447 if not opt.has_option(a):
448 del argv[i]
449 continue
450 i += 1
451
David Pursehouse819827a2020-02-12 15:20:19 +0900452
Sarah Owens1f7627f2012-10-31 09:21:55 -0700453class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700454 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400455 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700456 return req
457
458 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400459 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700460 return req
461
David Pursehouse819827a2020-02-12 15:20:19 +0900462
JoonCheol Parke9860722012-10-11 02:31:44 +0900463def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900464 # If repo could not find auth info from netrc, try to get it from user input
465 url = req.get_full_url()
466 user, password = handler.passwd.find_user_password(None, url)
467 if user is None:
468 print(msg)
469 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530470 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900471 password = getpass.getpass()
472 except KeyboardInterrupt:
473 return
474 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900475
David Pursehouse819827a2020-02-12 15:20:19 +0900476
Sarah Owens1f7627f2012-10-31 09:21:55 -0700477class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900478 def http_error_401(self, req, fp, code, msg, headers):
479 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700480 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900481 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900482
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700483 def http_error_auth_reqed(self, authreq, host, req, headers):
484 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700485 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900486
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700487 def _add_header(name, val):
488 val = val.replace('\n', '')
489 old_add_header(name, val)
490 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700491 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900492 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900493 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700494 reset = getattr(self, 'reset_retry_count', None)
495 if reset is not None:
496 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700497 elif getattr(self, 'retried', None):
498 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700499 raise
500
David Pursehouse819827a2020-02-12 15:20:19 +0900501
Sarah Owens1f7627f2012-10-31 09:21:55 -0700502class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900503 def http_error_401(self, req, fp, code, msg, headers):
504 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700505 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900506 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900507
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800508 def http_error_auth_reqed(self, auth_header, host, req, headers):
509 try:
510 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900511
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800512 def _add_header(name, val):
513 val = val.replace('\n', '')
514 old_add_header(name, val)
515 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700516 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900517 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900518 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800519 reset = getattr(self, 'reset_retry_count', None)
520 if reset is not None:
521 reset()
522 elif getattr(self, 'retried', None):
523 self.retried = 0
524 raise
525
David Pursehouse819827a2020-02-12 15:20:19 +0900526
Carlos Aguado1242e602014-02-03 13:48:47 +0100527class _KerberosAuthHandler(urllib.request.BaseHandler):
528 def __init__(self):
529 self.retried = 0
530 self.context = None
531 self.handler_order = urllib.request.BaseHandler.handler_order - 50
532
David Pursehouse65b0ba52018-06-24 16:21:51 +0900533 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100534 host = req.get_host()
535 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
536 return retry
537
538 def http_error_auth_reqed(self, auth_header, host, req, headers):
539 try:
540 spn = "HTTP@%s" % host
541 authdata = self._negotiate_get_authdata(auth_header, headers)
542
543 if self.retried > 3:
544 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900545 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100546 else:
547 self.retried += 1
548
549 neghdr = self._negotiate_get_svctk(spn, authdata)
550 if neghdr is None:
551 return None
552
553 req.add_unredirected_header('Authorization', neghdr)
554 response = self.parent.open(req)
555
556 srvauth = self._negotiate_get_authdata(auth_header, response.info())
557 if self._validate_response(srvauth):
558 return response
559 except kerberos.GSSError:
560 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900561 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100562 self.reset_retry_count()
563 raise
564 finally:
565 self._clean_context()
566
567 def reset_retry_count(self):
568 self.retried = 0
569
570 def _negotiate_get_authdata(self, auth_header, headers):
571 authhdr = headers.get(auth_header, None)
572 if authhdr is not None:
573 for mech_tuple in authhdr.split(","):
574 mech, __, authdata = mech_tuple.strip().partition(" ")
575 if mech.lower() == "negotiate":
576 return authdata.strip()
577 return None
578
579 def _negotiate_get_svctk(self, spn, authdata):
580 if authdata is None:
581 return None
582
583 result, self.context = kerberos.authGSSClientInit(spn)
584 if result < kerberos.AUTH_GSS_COMPLETE:
585 return None
586
587 result = kerberos.authGSSClientStep(self.context, authdata)
588 if result < kerberos.AUTH_GSS_CONTINUE:
589 return None
590
591 response = kerberos.authGSSClientResponse(self.context)
592 return "Negotiate %s" % response
593
594 def _validate_response(self, authdata):
595 if authdata is None:
596 return None
597 result = kerberos.authGSSClientStep(self.context, authdata)
598 if result == kerberos.AUTH_GSS_COMPLETE:
599 return True
600 return None
601
602 def _clean_context(self):
603 if self.context is not None:
604 kerberos.authGSSClientClean(self.context)
605 self.context = None
606
David Pursehouse819827a2020-02-12 15:20:19 +0900607
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700608def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700609 handlers = [_UserAgentHandler()]
610
Sarah Owens1f7627f2012-10-31 09:21:55 -0700611 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700612 try:
613 n = netrc.netrc()
614 for host in n.hosts:
615 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900616 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800617 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700618 except netrc.NetrcParseError:
619 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700620 except IOError:
621 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700622 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800623 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100624 if kerberos:
625 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700626
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700627 if 'http_proxy' in os.environ:
628 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700629 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700630 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700631 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
632 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
633 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700634
David Pursehouse819827a2020-02-12 15:20:19 +0900635
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700636def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400637 result = 0
638
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700639 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
640 opt.add_option("--repo-dir", dest="repodir",
641 help="path to .repo/")
642 opt.add_option("--wrapper-version", dest="wrapper_version",
643 help="version of the wrapper script")
644 opt.add_option("--wrapper-path", dest="wrapper_path",
645 help="location of the wrapper script")
646 _PruneOptions(argv, opt)
647 opt, argv = opt.parse_args(argv)
648
649 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
650 _CheckRepoDir(opt.repodir)
651
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800652 Version.wrapper_version = opt.wrapper_version
653 Version.wrapper_path = opt.wrapper_path
654
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700655 repo = _Repo(opt.repodir)
656 try:
Mike Frysinger19e409c2021-05-05 19:44:35 -0400657 init_http()
658 name, gopts, argv = repo._ParseArgs(argv)
659 run = lambda: repo._Run(name, gopts, argv) or 0
660 if gopts.trace_python:
661 import trace
662 tracer = trace.Trace(count=False, trace=True, timing=True,
663 ignoredirs=set(sys.path[1:]))
664 result = tracer.runfunc(run)
665 else:
666 result = run()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700667 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700668 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400669 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900670 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700671 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900672 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700673 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800674 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700675 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800676 argv = list(sys.argv)
677 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700678 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400679 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700680 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700681 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
682 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400683 result = 128
684
Renaud Paquaye8595e92016-11-01 15:51:59 -0700685 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400686 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700687
David Pursehouse819827a2020-02-12 15:20:19 +0900688
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700689if __name__ == '__main__':
690 _Main(sys.argv[1:])