blob: 229cb729df3b6ee6a1a1fc0b540d7130754094ca [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')
David Rileye0684ad2017-04-05 00:02:59 -0700121global_options.add_option('--event-log',
122 dest='event_log', action='store',
123 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800124global_options.add_option('--git-trace2-event-log', action='store',
125 help='directory to write git trace2 event log to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126
David Pursehouse819827a2020-02-12 15:20:19 +0900127
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128class _Repo(object):
129 def __init__(self, repodir):
130 self.repodir = repodir
131 self.commands = all_commands
132
Mike Frysinger56345c32021-07-26 23:46:32 -0400133 def _PrintHelp(self, short: bool = False, all_commands: bool = False):
134 """Show --help screen."""
135 global_options.print_help()
136 print()
137 if short:
138 commands = ' '.join(sorted(self.commands))
139 wrapped_commands = textwrap.wrap(commands, width=77)
140 print('Available commands:\n %s' % ('\n '.join(wrapped_commands),))
141 print('\nRun `repo help <command>` for command-specific details.')
142 print('Bug reports:', Wrapper().BUG_URL)
143 else:
144 cmd = self.commands['help']()
145 if all_commands:
146 cmd.PrintAllCommandsBody()
147 else:
148 cmd.PrintCommonCommandsBody()
149
Mike Frysinger3fc15722019-08-27 00:36:46 -0400150 def _ParseArgs(self, argv):
151 """Parse the main `repo` command line options."""
Mike Frysinger968d6462021-07-26 23:20:29 -0400152 for i, arg in enumerate(argv):
153 if not arg.startswith('-'):
154 name = arg
155 glob = argv[:i]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700156 argv = argv[i + 1:]
157 break
Mike Frysinger968d6462021-07-26 23:20:29 -0400158 else:
159 name = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160 glob = argv
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700161 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900162 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700163
Mike Frysinger968d6462021-07-26 23:20:29 -0400164 if name:
165 name, alias_args = self._ExpandAlias(name)
166 argv = alias_args + argv
Mike Frysinger7c321f12019-12-02 16:49:44 -0500167
Mike Frysinger3fc15722019-08-27 00:36:46 -0400168 return (name, gopts, argv)
169
Mike Frysinger949bc342020-02-18 21:37:00 -0500170 def _ExpandAlias(self, name):
171 """Look up user registered aliases."""
172 # We don't resolve aliases for existing subcommands. This matches git.
173 if name in self.commands:
174 return name, []
175
176 key = 'alias.%s' % (name,)
177 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
178 if alias is None:
179 alias = RepoConfig.ForUser().GetString(key)
180 if alias is None:
181 return name, []
182
183 args = alias.strip().split(' ', 1)
184 name = args[0]
185 if len(args) == 2:
186 args = shlex.split(args[1])
187 else:
188 args = []
189 return name, args
190
Mike Frysinger3fc15722019-08-27 00:36:46 -0400191 def _Run(self, name, gopts, argv):
192 """Execute the requested subcommand."""
193 result = 0
194
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700195 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700196 SetTrace()
Mike Frysinger968d6462021-07-26 23:20:29 -0400197
198 # Handle options that terminate quickly first.
Mike Frysinger56345c32021-07-26 23:46:32 -0400199 if gopts.help or gopts.help_all:
200 self._PrintHelp(short=False, all_commands=gopts.help_all)
Mike Frysinger968d6462021-07-26 23:20:29 -0400201 return 0
202 elif gopts.show_version:
Mike Frysingera024bd32021-07-26 23:31:06 -0400203 # Always allow global --version regardless of subcommand validity.
Mike Frysinger968d6462021-07-26 23:20:29 -0400204 name = 'version'
205 elif not name:
206 # No subcommand specified, so show the help/subcommand.
Mike Frysinger56345c32021-07-26 23:46:32 -0400207 self._PrintHelp(short=True)
208 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800209
Mike Frysinger902665b2014-12-22 15:17:59 -0500210 SetDefaultColoring(gopts.color)
211
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400212 git_trace2_event_log = EventLog()
213 repo_client = RepoClient(self.repodir)
214 gitc_manifest = None
215 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
216 if gitc_client_name:
217 gitc_manifest = GitcClient(self.repodir, gitc_client_name)
218 repo_client.isGitcClient = True
219
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220 try:
Mike Frysingerd58d0dd2021-06-14 16:17:27 -0400221 cmd = self.commands[name](
222 repodir=self.repodir,
223 client=repo_client,
224 manifest=repo_client.manifest,
Raman Tenneti784e16f2021-06-11 17:29:45 -0700225 gitc_manifest=gitc_manifest,
226 git_event_log=git_trace2_event_log)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700228 print("repo: '%s' is not a repo command. See 'repo help'." % name,
229 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400230 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700231
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400232 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800234 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700235 print("fatal: '%s' requires a working directory" % name,
236 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400237 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800238
Dan Willemsen79360642015-08-31 15:45:06 -0700239 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700240 print("fatal: '%s' requires GITC to be available" % name,
241 file=sys.stderr)
242 return 1
243
Dan Willemsen79360642015-08-31 15:45:06 -0700244 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
245 print("fatal: '%s' requires a GITC client" % name,
246 file=sys.stderr)
247 return 1
248
Dan Sandler53e902a2014-03-09 13:20:02 -0400249 try:
250 copts, cargs = cmd.OptionParser.parse_args(argv)
251 copts = cmd.ReadEnvironmentOptions(copts)
252 except NoManifestException as e:
253 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900254 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400255 print('error: manifest missing or unreadable -- please run init',
256 file=sys.stderr)
257 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700258
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500259 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400260 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700261 if gopts.pager:
262 use_pager = True
263 else:
264 use_pager = config.GetBoolean('pager.%s' % name)
265 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700266 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267 if use_pager:
268 RunPager(config)
269
Conley Owens7ba25be2012-11-14 14:18:06 -0800270 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700271 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
272 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800273 git_trace2_event_log.StartEvent()
Raman Tennetia5b40a22021-03-16 14:24:14 -0700274 git_trace2_event_log.CommandEvent(name='repo', subcommands=[name])
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800275
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700276 try:
Mike Frysinger9180a072021-04-13 14:57:40 -0400277 cmd.CommonValidateOptions(copts, cargs)
Mike Frysingerae6cb082019-08-27 01:10:59 -0400278 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800279 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400280 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900281 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400282 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900283 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400284 if isinstance(e, NoManifestException):
285 print('error: manifest missing or unreadable -- please run init',
286 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800287 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700288 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700289 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700290 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700291 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700292 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800293 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700294 except InvalidProjectGroupsError as e:
295 if e.name:
296 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
297 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900298 print('error: project group must be enabled for the project in the current directory',
299 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700300 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700301 except SystemExit as e:
302 if e.code:
303 result = e.code
304 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800305 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700306 finish = time.time()
307 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800308 hours, remainder = divmod(elapsed, 3600)
309 minutes, seconds = divmod(remainder, 60)
310 if gopts.time:
311 if hours == 0:
312 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
313 else:
314 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
315 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400316
David Rileye0684ad2017-04-05 00:02:59 -0700317 cmd.event_log.FinishEvent(cmd_event, finish,
318 result is None or result == 0)
Ian Kasprzak835a34b2021-03-05 11:04:49 -0800319 git_trace2_event_log.DefParamRepoEvents(
320 cmd.manifest.manifestProject.config.DumpConfigDict())
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800321 git_trace2_event_log.ExitEvent(result)
322
David Rileye0684ad2017-04-05 00:02:59 -0700323 if gopts.event_log:
324 cmd.event_log.Write(os.path.abspath(
325 os.path.expanduser(gopts.event_log)))
326
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800327 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400328 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329
Conley Owens094cdbe2014-01-30 15:09:59 -0800330
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500331def _CheckWrapperVersion(ver_str, repo_path):
332 """Verify the repo launcher is new enough for this checkout.
333
334 Args:
335 ver_str: The version string passed from the repo launcher when it ran us.
336 repo_path: The path to the repo launcher that loaded us.
337 """
338 # Refuse to work with really old wrapper versions. We don't test these,
339 # so might as well require a somewhat recent sane version.
340 # v1.15 of the repo launcher was released in ~Mar 2012.
341 MIN_REPO_VERSION = (1, 15)
342 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
343
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344 if not repo_path:
345 repo_path = '~/bin/repo'
346
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500347 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700348 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900349 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700350
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500351 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800352 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500353 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700354
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900355 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500356 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700357 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500358repo: error:
359!!! Your version of repo %s is too old.
360!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900361!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500362!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363
364 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500365""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700366 sys.exit(1)
367
368 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500369 print('\n... A new version of repo (%s) is available.' % (exp_str,),
370 file=sys.stderr)
371 if os.access(repo_path, os.W_OK):
372 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700373... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700374 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500375""" % (WrapperPath(), repo_path), file=sys.stderr)
376 else:
377 print("""\
378... New version is available at: %s
379... The launcher is run from: %s
380!!! The launcher is not writable. Please talk to your sysadmin or distro
381!!! to get an update installed.
382""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383
David Pursehouse819827a2020-02-12 15:20:19 +0900384
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200385def _CheckRepoDir(repo_dir):
386 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700387 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900388 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700389
David Pursehouse819827a2020-02-12 15:20:19 +0900390
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700391def _PruneOptions(argv, opt):
392 i = 0
393 while i < len(argv):
394 a = argv[i]
395 if a == '--':
396 break
397 if a.startswith('--'):
398 eq = a.find('=')
399 if eq > 0:
400 a = a[0:eq]
401 if not opt.has_option(a):
402 del argv[i]
403 continue
404 i += 1
405
David Pursehouse819827a2020-02-12 15:20:19 +0900406
Sarah Owens1f7627f2012-10-31 09:21:55 -0700407class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700408 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400409 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700410 return req
411
412 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400413 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700414 return req
415
David Pursehouse819827a2020-02-12 15:20:19 +0900416
JoonCheol Parke9860722012-10-11 02:31:44 +0900417def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900418 # If repo could not find auth info from netrc, try to get it from user input
419 url = req.get_full_url()
420 user, password = handler.passwd.find_user_password(None, url)
421 if user is None:
422 print(msg)
423 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530424 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900425 password = getpass.getpass()
426 except KeyboardInterrupt:
427 return
428 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900429
David Pursehouse819827a2020-02-12 15:20:19 +0900430
Sarah Owens1f7627f2012-10-31 09:21:55 -0700431class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900432 def http_error_401(self, req, fp, code, msg, headers):
433 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700434 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900435 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900436
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700437 def http_error_auth_reqed(self, authreq, host, req, headers):
438 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700439 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900440
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700441 def _add_header(name, val):
442 val = val.replace('\n', '')
443 old_add_header(name, val)
444 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700445 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900446 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900447 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700448 reset = getattr(self, 'reset_retry_count', None)
449 if reset is not None:
450 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700451 elif getattr(self, 'retried', None):
452 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700453 raise
454
David Pursehouse819827a2020-02-12 15:20:19 +0900455
Sarah Owens1f7627f2012-10-31 09:21:55 -0700456class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900457 def http_error_401(self, req, fp, code, msg, headers):
458 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700459 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900460 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900461
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800462 def http_error_auth_reqed(self, auth_header, host, req, headers):
463 try:
464 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900465
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800466 def _add_header(name, val):
467 val = val.replace('\n', '')
468 old_add_header(name, val)
469 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700470 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900471 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900472 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800473 reset = getattr(self, 'reset_retry_count', None)
474 if reset is not None:
475 reset()
476 elif getattr(self, 'retried', None):
477 self.retried = 0
478 raise
479
David Pursehouse819827a2020-02-12 15:20:19 +0900480
Carlos Aguado1242e602014-02-03 13:48:47 +0100481class _KerberosAuthHandler(urllib.request.BaseHandler):
482 def __init__(self):
483 self.retried = 0
484 self.context = None
485 self.handler_order = urllib.request.BaseHandler.handler_order - 50
486
David Pursehouse65b0ba52018-06-24 16:21:51 +0900487 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100488 host = req.get_host()
489 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
490 return retry
491
492 def http_error_auth_reqed(self, auth_header, host, req, headers):
493 try:
494 spn = "HTTP@%s" % host
495 authdata = self._negotiate_get_authdata(auth_header, headers)
496
497 if self.retried > 3:
498 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900499 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100500 else:
501 self.retried += 1
502
503 neghdr = self._negotiate_get_svctk(spn, authdata)
504 if neghdr is None:
505 return None
506
507 req.add_unredirected_header('Authorization', neghdr)
508 response = self.parent.open(req)
509
510 srvauth = self._negotiate_get_authdata(auth_header, response.info())
511 if self._validate_response(srvauth):
512 return response
513 except kerberos.GSSError:
514 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900515 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100516 self.reset_retry_count()
517 raise
518 finally:
519 self._clean_context()
520
521 def reset_retry_count(self):
522 self.retried = 0
523
524 def _negotiate_get_authdata(self, auth_header, headers):
525 authhdr = headers.get(auth_header, None)
526 if authhdr is not None:
527 for mech_tuple in authhdr.split(","):
528 mech, __, authdata = mech_tuple.strip().partition(" ")
529 if mech.lower() == "negotiate":
530 return authdata.strip()
531 return None
532
533 def _negotiate_get_svctk(self, spn, authdata):
534 if authdata is None:
535 return None
536
537 result, self.context = kerberos.authGSSClientInit(spn)
538 if result < kerberos.AUTH_GSS_COMPLETE:
539 return None
540
541 result = kerberos.authGSSClientStep(self.context, authdata)
542 if result < kerberos.AUTH_GSS_CONTINUE:
543 return None
544
545 response = kerberos.authGSSClientResponse(self.context)
546 return "Negotiate %s" % response
547
548 def _validate_response(self, authdata):
549 if authdata is None:
550 return None
551 result = kerberos.authGSSClientStep(self.context, authdata)
552 if result == kerberos.AUTH_GSS_COMPLETE:
553 return True
554 return None
555
556 def _clean_context(self):
557 if self.context is not None:
558 kerberos.authGSSClientClean(self.context)
559 self.context = None
560
David Pursehouse819827a2020-02-12 15:20:19 +0900561
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700562def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700563 handlers = [_UserAgentHandler()]
564
Sarah Owens1f7627f2012-10-31 09:21:55 -0700565 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700566 try:
567 n = netrc.netrc()
568 for host in n.hosts:
569 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900570 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800571 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700572 except netrc.NetrcParseError:
573 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700574 except IOError:
575 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700576 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800577 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100578 if kerberos:
579 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700580
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700581 if 'http_proxy' in os.environ:
582 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700583 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700584 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700585 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
586 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
587 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700588
David Pursehouse819827a2020-02-12 15:20:19 +0900589
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700590def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400591 result = 0
592
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700593 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
594 opt.add_option("--repo-dir", dest="repodir",
595 help="path to .repo/")
596 opt.add_option("--wrapper-version", dest="wrapper_version",
597 help="version of the wrapper script")
598 opt.add_option("--wrapper-path", dest="wrapper_path",
599 help="location of the wrapper script")
600 _PruneOptions(argv, opt)
601 opt, argv = opt.parse_args(argv)
602
603 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
604 _CheckRepoDir(opt.repodir)
605
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800606 Version.wrapper_version = opt.wrapper_version
607 Version.wrapper_path = opt.wrapper_path
608
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609 repo = _Repo(opt.repodir)
610 try:
Mike Frysinger19e409c2021-05-05 19:44:35 -0400611 init_http()
612 name, gopts, argv = repo._ParseArgs(argv)
613 run = lambda: repo._Run(name, gopts, argv) or 0
614 if gopts.trace_python:
615 import trace
616 tracer = trace.Trace(count=False, trace=True, timing=True,
617 ignoredirs=set(sys.path[1:]))
618 result = tracer.runfunc(run)
619 else:
620 result = run()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700621 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700622 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400623 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900624 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700625 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900626 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700627 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800628 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700629 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800630 argv = list(sys.argv)
631 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700632 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400633 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700634 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700635 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
636 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400637 result = 128
638
Renaud Paquaye8595e92016-11-01 15:51:59 -0700639 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400640 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700641
David Pursehouse819827a2020-02-12 15:20:19 +0900642
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700643if __name__ == '__main__':
644 _Main(sys.argv[1:])