blob: 96744335eb0c6dd2ffbf7d8faa5b88423365d636 [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
Mike Frysinger5291eaf2021-05-05 15:53:03 -040059import ssh
Conley Owens094cdbe2014-01-30 15:09:59 -080060from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061
David Pursehouse5c6eeac2012-10-11 16:44:48 +090062from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063
Chirayu Desai217ea7d2013-03-01 19:14:38 +053064
Mike Frysinger37f28f12020-02-16 15:15:53 -050065# NB: These do not need to be kept in sync with the repo launcher script.
66# These may be much newer as it allows the repo launcher to roll between
67# different repo releases while source versions might require a newer python.
68#
69# The soft version is when we start warning users that the version is old and
70# we'll be dropping support for it. We'll refuse to work with versions older
71# than the hard version.
72#
73# python-3.6 is in Ubuntu Bionic.
74MIN_PYTHON_VERSION_SOFT = (3, 6)
Mike Frysinger128f34e2020-12-14 18:28:04 -050075MIN_PYTHON_VERSION_HARD = (3, 5)
Mike Frysinger37f28f12020-02-16 15:15:53 -050076
77if sys.version_info.major < 3:
Mike Frysingera488af52020-09-06 13:33:45 -040078 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050079 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
80 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040081 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050082else:
83 if sys.version_info < MIN_PYTHON_VERSION_HARD:
84 print('repo: error: Python 3 version is too old; '
85 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
86 file=sys.stderr)
87 sys.exit(1)
88 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
89 print('repo: warning: your Python 3 version is no longer supported; '
90 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
91 file=sys.stderr)
92
93
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070094global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -050095 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
96 add_help_option=False)
97global_options.add_option('-h', '--help', action='store_true',
98 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070099global_options.add_option('-p', '--paginate',
100 dest='pager', action='store_true',
101 help='display command output in the pager')
102global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500103 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500105global_options.add_option('--color',
106 choices=('auto', 'always', 'never'), default=None,
107 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700108global_options.add_option('--trace',
109 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400110 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400111global_options.add_option('--trace-python',
112 dest='trace_python', action='store_true',
113 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700114global_options.add_option('--time',
115 dest='time', action='store_true',
116 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800117global_options.add_option('--version',
118 dest='show_version', action='store_true',
119 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700120global_options.add_option('--event-log',
121 dest='event_log', action='store',
122 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800123global_options.add_option('--git-trace2-event-log', action='store',
124 help='directory to write git trace2 event log to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125
David Pursehouse819827a2020-02-12 15:20:19 +0900126
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127class _Repo(object):
128 def __init__(self, repodir):
129 self.repodir = repodir
130 self.commands = all_commands
131
Mike Frysinger3fc15722019-08-27 00:36:46 -0400132 def _ParseArgs(self, argv):
133 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134 name = None
135 glob = []
136
Sarah Owensa6053d52012-11-01 13:36:50 -0700137 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138 if not argv[i].startswith('-'):
139 name = argv[i]
140 if i > 0:
141 glob = argv[:i]
142 argv = argv[i + 1:]
143 break
144 if not name:
145 glob = argv
146 name = 'help'
147 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900148 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149
Mike Frysinger949bc342020-02-18 21:37:00 -0500150 name, alias_args = self._ExpandAlias(name)
151 argv = alias_args + argv
152
Mike Frysinger7c321f12019-12-02 16:49:44 -0500153 if gopts.help:
154 global_options.print_help()
155 commands = ' '.join(sorted(self.commands))
156 wrapped_commands = textwrap.wrap(commands, width=77)
157 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
158 print('\nRun `repo help <command>` for command-specific details.')
159 global_options.exit()
160
Mike Frysinger3fc15722019-08-27 00:36:46 -0400161 return (name, gopts, argv)
162
Mike Frysinger949bc342020-02-18 21:37:00 -0500163 def _ExpandAlias(self, name):
164 """Look up user registered aliases."""
165 # We don't resolve aliases for existing subcommands. This matches git.
166 if name in self.commands:
167 return name, []
168
169 key = 'alias.%s' % (name,)
170 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
171 if alias is None:
172 alias = RepoConfig.ForUser().GetString(key)
173 if alias is None:
174 return name, []
175
176 args = alias.strip().split(' ', 1)
177 name = args[0]
178 if len(args) == 2:
179 args = shlex.split(args[1])
180 else:
181 args = []
182 return name, args
183
Mike Frysinger3fc15722019-08-27 00:36:46 -0400184 def _Run(self, name, gopts, argv):
185 """Execute the requested subcommand."""
186 result = 0
187
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700188 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700189 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800190 if gopts.show_version:
191 if name == 'help':
192 name = 'version'
193 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700194 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400195 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800196
Mike Frysinger902665b2014-12-22 15:17:59 -0500197 SetDefaultColoring(gopts.color)
198
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500200 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700202 print("repo: '%s' is not a repo command. See 'repo help'." % name,
203 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400204 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800206 git_trace2_event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207 cmd.repodir = self.repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400208 cmd.client = RepoClient(cmd.repodir)
209 cmd.manifest = cmd.client.manifest
Simran Basib9a1b732015-08-20 12:19:28 -0700210 cmd.gitc_manifest = None
211 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
212 if gitc_client_name:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400213 cmd.gitc_manifest = GitcClient(cmd.repodir, gitc_client_name)
214 cmd.client.isGitcClient = True
Simran Basib9a1b732015-08-20 12:19:28 -0700215
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400216 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800218 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700219 print("fatal: '%s' requires a working directory" % name,
220 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400221 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800222
Dan Willemsen79360642015-08-31 15:45:06 -0700223 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700224 print("fatal: '%s' requires GITC to be available" % name,
225 file=sys.stderr)
226 return 1
227
Dan Willemsen79360642015-08-31 15:45:06 -0700228 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
229 print("fatal: '%s' requires a GITC client" % name,
230 file=sys.stderr)
231 return 1
232
Dan Sandler53e902a2014-03-09 13:20:02 -0400233 try:
234 copts, cargs = cmd.OptionParser.parse_args(argv)
235 copts = cmd.ReadEnvironmentOptions(copts)
236 except NoManifestException as e:
237 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900238 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400239 print('error: manifest missing or unreadable -- please run init',
240 file=sys.stderr)
241 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700242
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500243 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400244 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700245 if gopts.pager:
246 use_pager = True
247 else:
248 use_pager = config.GetBoolean('pager.%s' % name)
249 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700250 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251 if use_pager:
252 RunPager(config)
253
Conley Owens7ba25be2012-11-14 14:18:06 -0800254 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700255 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
256 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800257 git_trace2_event_log.StartEvent()
Raman Tennetia5b40a22021-03-16 14:24:14 -0700258 git_trace2_event_log.CommandEvent(name='repo', subcommands=[name])
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800259
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700260 try:
Mike Frysinger9180a072021-04-13 14:57:40 -0400261 cmd.CommonValidateOptions(copts, cargs)
Mike Frysingerae6cb082019-08-27 01:10:59 -0400262 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800263 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400264 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900265 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400266 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900267 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400268 if isinstance(e, NoManifestException):
269 print('error: manifest missing or unreadable -- please run init',
270 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800271 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700272 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700273 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700274 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700275 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700276 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800277 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700278 except InvalidProjectGroupsError as e:
279 if e.name:
280 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
281 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900282 print('error: project group must be enabled for the project in the current directory',
283 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700284 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700285 except SystemExit as e:
286 if e.code:
287 result = e.code
288 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800289 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700290 finish = time.time()
291 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800292 hours, remainder = divmod(elapsed, 3600)
293 minutes, seconds = divmod(remainder, 60)
294 if gopts.time:
295 if hours == 0:
296 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
297 else:
298 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
299 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400300
David Rileye0684ad2017-04-05 00:02:59 -0700301 cmd.event_log.FinishEvent(cmd_event, finish,
302 result is None or result == 0)
Ian Kasprzak835a34b2021-03-05 11:04:49 -0800303 git_trace2_event_log.DefParamRepoEvents(
304 cmd.manifest.manifestProject.config.DumpConfigDict())
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800305 git_trace2_event_log.ExitEvent(result)
306
David Rileye0684ad2017-04-05 00:02:59 -0700307 if gopts.event_log:
308 cmd.event_log.Write(os.path.abspath(
309 os.path.expanduser(gopts.event_log)))
310
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800311 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400312 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700313
Conley Owens094cdbe2014-01-30 15:09:59 -0800314
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500315def _CheckWrapperVersion(ver_str, repo_path):
316 """Verify the repo launcher is new enough for this checkout.
317
318 Args:
319 ver_str: The version string passed from the repo launcher when it ran us.
320 repo_path: The path to the repo launcher that loaded us.
321 """
322 # Refuse to work with really old wrapper versions. We don't test these,
323 # so might as well require a somewhat recent sane version.
324 # v1.15 of the repo launcher was released in ~Mar 2012.
325 MIN_REPO_VERSION = (1, 15)
326 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
327
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700328 if not repo_path:
329 repo_path = '~/bin/repo'
330
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500331 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700332 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900333 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700334
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500335 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800336 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500337 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700338
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900339 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500340 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700341 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500342repo: error:
343!!! Your version of repo %s is too old.
344!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900345!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500346!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347
348 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500349""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700350 sys.exit(1)
351
352 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500353 print('\n... A new version of repo (%s) is available.' % (exp_str,),
354 file=sys.stderr)
355 if os.access(repo_path, os.W_OK):
356 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700358 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500359""" % (WrapperPath(), repo_path), file=sys.stderr)
360 else:
361 print("""\
362... New version is available at: %s
363... The launcher is run from: %s
364!!! The launcher is not writable. Please talk to your sysadmin or distro
365!!! to get an update installed.
366""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700367
David Pursehouse819827a2020-02-12 15:20:19 +0900368
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200369def _CheckRepoDir(repo_dir):
370 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700371 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900372 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700373
David Pursehouse819827a2020-02-12 15:20:19 +0900374
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700375def _PruneOptions(argv, opt):
376 i = 0
377 while i < len(argv):
378 a = argv[i]
379 if a == '--':
380 break
381 if a.startswith('--'):
382 eq = a.find('=')
383 if eq > 0:
384 a = a[0:eq]
385 if not opt.has_option(a):
386 del argv[i]
387 continue
388 i += 1
389
David Pursehouse819827a2020-02-12 15:20:19 +0900390
Sarah Owens1f7627f2012-10-31 09:21:55 -0700391class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700392 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400393 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700394 return req
395
396 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400397 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700398 return req
399
David Pursehouse819827a2020-02-12 15:20:19 +0900400
JoonCheol Parke9860722012-10-11 02:31:44 +0900401def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900402 # If repo could not find auth info from netrc, try to get it from user input
403 url = req.get_full_url()
404 user, password = handler.passwd.find_user_password(None, url)
405 if user is None:
406 print(msg)
407 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530408 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900409 password = getpass.getpass()
410 except KeyboardInterrupt:
411 return
412 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900413
David Pursehouse819827a2020-02-12 15:20:19 +0900414
Sarah Owens1f7627f2012-10-31 09:21:55 -0700415class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900416 def http_error_401(self, req, fp, code, msg, headers):
417 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700418 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900419 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900420
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700421 def http_error_auth_reqed(self, authreq, host, req, headers):
422 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700423 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900424
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700425 def _add_header(name, val):
426 val = val.replace('\n', '')
427 old_add_header(name, val)
428 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700429 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900430 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900431 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700432 reset = getattr(self, 'reset_retry_count', None)
433 if reset is not None:
434 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700435 elif getattr(self, 'retried', None):
436 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700437 raise
438
David Pursehouse819827a2020-02-12 15:20:19 +0900439
Sarah Owens1f7627f2012-10-31 09:21:55 -0700440class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900441 def http_error_401(self, req, fp, code, msg, headers):
442 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700443 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900444 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900445
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800446 def http_error_auth_reqed(self, auth_header, host, req, headers):
447 try:
448 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900449
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800450 def _add_header(name, val):
451 val = val.replace('\n', '')
452 old_add_header(name, val)
453 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700454 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900455 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900456 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800457 reset = getattr(self, 'reset_retry_count', None)
458 if reset is not None:
459 reset()
460 elif getattr(self, 'retried', None):
461 self.retried = 0
462 raise
463
David Pursehouse819827a2020-02-12 15:20:19 +0900464
Carlos Aguado1242e602014-02-03 13:48:47 +0100465class _KerberosAuthHandler(urllib.request.BaseHandler):
466 def __init__(self):
467 self.retried = 0
468 self.context = None
469 self.handler_order = urllib.request.BaseHandler.handler_order - 50
470
David Pursehouse65b0ba52018-06-24 16:21:51 +0900471 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100472 host = req.get_host()
473 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
474 return retry
475
476 def http_error_auth_reqed(self, auth_header, host, req, headers):
477 try:
478 spn = "HTTP@%s" % host
479 authdata = self._negotiate_get_authdata(auth_header, headers)
480
481 if self.retried > 3:
482 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900483 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100484 else:
485 self.retried += 1
486
487 neghdr = self._negotiate_get_svctk(spn, authdata)
488 if neghdr is None:
489 return None
490
491 req.add_unredirected_header('Authorization', neghdr)
492 response = self.parent.open(req)
493
494 srvauth = self._negotiate_get_authdata(auth_header, response.info())
495 if self._validate_response(srvauth):
496 return response
497 except kerberos.GSSError:
498 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900499 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100500 self.reset_retry_count()
501 raise
502 finally:
503 self._clean_context()
504
505 def reset_retry_count(self):
506 self.retried = 0
507
508 def _negotiate_get_authdata(self, auth_header, headers):
509 authhdr = headers.get(auth_header, None)
510 if authhdr is not None:
511 for mech_tuple in authhdr.split(","):
512 mech, __, authdata = mech_tuple.strip().partition(" ")
513 if mech.lower() == "negotiate":
514 return authdata.strip()
515 return None
516
517 def _negotiate_get_svctk(self, spn, authdata):
518 if authdata is None:
519 return None
520
521 result, self.context = kerberos.authGSSClientInit(spn)
522 if result < kerberos.AUTH_GSS_COMPLETE:
523 return None
524
525 result = kerberos.authGSSClientStep(self.context, authdata)
526 if result < kerberos.AUTH_GSS_CONTINUE:
527 return None
528
529 response = kerberos.authGSSClientResponse(self.context)
530 return "Negotiate %s" % response
531
532 def _validate_response(self, authdata):
533 if authdata is None:
534 return None
535 result = kerberos.authGSSClientStep(self.context, authdata)
536 if result == kerberos.AUTH_GSS_COMPLETE:
537 return True
538 return None
539
540 def _clean_context(self):
541 if self.context is not None:
542 kerberos.authGSSClientClean(self.context)
543 self.context = None
544
David Pursehouse819827a2020-02-12 15:20:19 +0900545
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700546def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700547 handlers = [_UserAgentHandler()]
548
Sarah Owens1f7627f2012-10-31 09:21:55 -0700549 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700550 try:
551 n = netrc.netrc()
552 for host in n.hosts:
553 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900554 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800555 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700556 except netrc.NetrcParseError:
557 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700558 except IOError:
559 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700560 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800561 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100562 if kerberos:
563 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700564
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700565 if 'http_proxy' in os.environ:
566 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700567 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700568 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700569 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
570 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
571 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700572
David Pursehouse819827a2020-02-12 15:20:19 +0900573
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400575 result = 0
576
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700577 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
578 opt.add_option("--repo-dir", dest="repodir",
579 help="path to .repo/")
580 opt.add_option("--wrapper-version", dest="wrapper_version",
581 help="version of the wrapper script")
582 opt.add_option("--wrapper-path", dest="wrapper_path",
583 help="location of the wrapper script")
584 _PruneOptions(argv, opt)
585 opt, argv = opt.parse_args(argv)
586
587 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
588 _CheckRepoDir(opt.repodir)
589
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800590 Version.wrapper_version = opt.wrapper_version
591 Version.wrapper_path = opt.wrapper_path
592
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700593 repo = _Repo(opt.repodir)
594 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700595 try:
Mike Frysinger5291eaf2021-05-05 15:53:03 -0400596 ssh.init()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700597 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400598 name, gopts, argv = repo._ParseArgs(argv)
599 run = lambda: repo._Run(name, gopts, argv) or 0
600 if gopts.trace_python:
601 import trace
602 tracer = trace.Trace(count=False, trace=True, timing=True,
603 ignoredirs=set(sys.path[1:]))
604 result = tracer.runfunc(run)
605 else:
606 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700607 finally:
Mike Frysinger5291eaf2021-05-05 15:53:03 -0400608 ssh.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700609 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700610 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400611 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900612 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700613 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900614 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700615 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800616 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700617 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800618 argv = list(sys.argv)
619 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700620 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400621 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700622 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700623 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
624 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400625 result = 128
626
Renaud Paquaye8595e92016-11-01 15:51:59 -0700627 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400628 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700629
David Pursehouse819827a2020-02-12 15:20:19 +0900630
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700631if __name__ == '__main__':
632 _Main(sys.argv[1:])