blob: cd0b8620c05a45bb9fd4d0248563256ca0cc0296 [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
David Pursehouse59bbb582013-05-17 10:49:33 +090031
32from pyversion import is_python3
33if is_python3():
Sarah Owens1f7627f2012-10-31 09:21:55 -070034 import urllib.request
35else:
Rashed Abdel-Tawab2058c632019-10-05 00:18:41 -040036 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +090037 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -070038 urllib = imp.new_module('urllib')
39 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070040
Carlos Aguado1242e602014-02-03 13:48:47 +010041try:
42 import kerberos
43except ImportError:
44 kerberos = None
45
Mike Frysinger902665b2014-12-22 15:17:59 -050046from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070047import event_log
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040048from repo_trace import SetTrace
David Pursehouse9090e802020-02-12 11:25:13 +090049from git_command import user_agent
Mike Frysinger949bc342020-02-18 21:37:00 -050050from git_config import init_ssh, close_ssh, RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080051from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080052from command import InteractiveCommand
53from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070054from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080055from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070056from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070057from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070058from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080059from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090060from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080061from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070062from error import NoSuchProjectError
63from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070064import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040065from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070066from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080067from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070068
David Pursehouse5c6eeac2012-10-11 16:44:48 +090069from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070070
David Pursehouse59bbb582013-05-17 10:49:33 +090071if not is_python3():
David Pursehousea46bf7d2020-02-15 12:45:53 +090072 input = raw_input # noqa: F821
Chirayu Desai217ea7d2013-03-01 19:14:38 +053073
Mike Frysinger37f28f12020-02-16 15:15:53 -050074# NB: These do not need to be kept in sync with the repo launcher script.
75# These may be much newer as it allows the repo launcher to roll between
76# different repo releases while source versions might require a newer python.
77#
78# The soft version is when we start warning users that the version is old and
79# we'll be dropping support for it. We'll refuse to work with versions older
80# than the hard version.
81#
82# python-3.6 is in Ubuntu Bionic.
83MIN_PYTHON_VERSION_SOFT = (3, 6)
Mike Frysinger128f34e2020-12-14 18:28:04 -050084MIN_PYTHON_VERSION_HARD = (3, 5)
Mike Frysinger37f28f12020-02-16 15:15:53 -050085
86if sys.version_info.major < 3:
Mike Frysingera488af52020-09-06 13:33:45 -040087 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050088 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
89 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040090 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050091else:
92 if sys.version_info < MIN_PYTHON_VERSION_HARD:
93 print('repo: error: Python 3 version is too old; '
94 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
95 file=sys.stderr)
96 sys.exit(1)
97 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
98 print('repo: warning: your Python 3 version is no longer supported; '
99 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
100 file=sys.stderr)
101
102
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -0500104 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
105 add_help_option=False)
106global_options.add_option('-h', '--help', action='store_true',
107 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700108global_options.add_option('-p', '--paginate',
109 dest='pager', action='store_true',
110 help='display command output in the pager')
111global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500112 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700113 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500114global_options.add_option('--color',
115 choices=('auto', 'always', 'never'), default=None,
116 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700117global_options.add_option('--trace',
118 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400119 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400120global_options.add_option('--trace-python',
121 dest='trace_python', action='store_true',
122 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700123global_options.add_option('--time',
124 dest='time', action='store_true',
125 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800126global_options.add_option('--version',
127 dest='show_version', action='store_true',
128 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700129global_options.add_option('--event-log',
130 dest='event_log', action='store',
131 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800132global_options.add_option('--git-trace2-event-log', action='store',
133 help='directory to write git trace2 event log to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134
David Pursehouse819827a2020-02-12 15:20:19 +0900135
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136class _Repo(object):
137 def __init__(self, repodir):
138 self.repodir = repodir
139 self.commands = all_commands
140
Mike Frysinger3fc15722019-08-27 00:36:46 -0400141 def _ParseArgs(self, argv):
142 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700143 name = None
144 glob = []
145
Sarah Owensa6053d52012-11-01 13:36:50 -0700146 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147 if not argv[i].startswith('-'):
148 name = argv[i]
149 if i > 0:
150 glob = argv[:i]
151 argv = argv[i + 1:]
152 break
153 if not name:
154 glob = argv
155 name = 'help'
156 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900157 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158
Mike Frysinger949bc342020-02-18 21:37:00 -0500159 name, alias_args = self._ExpandAlias(name)
160 argv = alias_args + argv
161
Mike Frysinger7c321f12019-12-02 16:49:44 -0500162 if gopts.help:
163 global_options.print_help()
164 commands = ' '.join(sorted(self.commands))
165 wrapped_commands = textwrap.wrap(commands, width=77)
166 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
167 print('\nRun `repo help <command>` for command-specific details.')
168 global_options.exit()
169
Mike Frysinger3fc15722019-08-27 00:36:46 -0400170 return (name, gopts, argv)
171
Mike Frysinger949bc342020-02-18 21:37:00 -0500172 def _ExpandAlias(self, name):
173 """Look up user registered aliases."""
174 # We don't resolve aliases for existing subcommands. This matches git.
175 if name in self.commands:
176 return name, []
177
178 key = 'alias.%s' % (name,)
179 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
180 if alias is None:
181 alias = RepoConfig.ForUser().GetString(key)
182 if alias is None:
183 return name, []
184
185 args = alias.strip().split(' ', 1)
186 name = args[0]
187 if len(args) == 2:
188 args = shlex.split(args[1])
189 else:
190 args = []
191 return name, args
192
Mike Frysinger3fc15722019-08-27 00:36:46 -0400193 def _Run(self, name, gopts, argv):
194 """Execute the requested subcommand."""
195 result = 0
196
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700197 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700198 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800199 if gopts.show_version:
200 if name == 'help':
201 name = 'version'
202 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700203 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400204 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800205
Mike Frysinger902665b2014-12-22 15:17:59 -0500206 SetDefaultColoring(gopts.color)
207
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700208 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500209 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700210 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700211 print("repo: '%s' is not a repo command. See 'repo help'." % name,
212 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400213 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800215 git_trace2_event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216 cmd.repodir = self.repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400217 cmd.client = RepoClient(cmd.repodir)
218 cmd.manifest = cmd.client.manifest
Simran Basib9a1b732015-08-20 12:19:28 -0700219 cmd.gitc_manifest = None
220 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
221 if gitc_client_name:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400222 cmd.gitc_manifest = GitcClient(cmd.repodir, gitc_client_name)
223 cmd.client.isGitcClient = True
Simran Basib9a1b732015-08-20 12:19:28 -0700224
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400225 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700226
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800227 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700228 print("fatal: '%s' requires a working directory" % name,
229 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400230 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800231
Dan Willemsen79360642015-08-31 15:45:06 -0700232 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700233 print("fatal: '%s' requires GITC to be available" % name,
234 file=sys.stderr)
235 return 1
236
Dan Willemsen79360642015-08-31 15:45:06 -0700237 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
238 print("fatal: '%s' requires a GITC client" % name,
239 file=sys.stderr)
240 return 1
241
Dan Sandler53e902a2014-03-09 13:20:02 -0400242 try:
243 copts, cargs = cmd.OptionParser.parse_args(argv)
244 copts = cmd.ReadEnvironmentOptions(copts)
245 except NoManifestException as e:
246 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900247 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400248 print('error: manifest missing or unreadable -- please run init',
249 file=sys.stderr)
250 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700251
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500252 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400253 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700254 if gopts.pager:
255 use_pager = True
256 else:
257 use_pager = config.GetBoolean('pager.%s' % name)
258 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700259 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700260 if use_pager:
261 RunPager(config)
262
Conley Owens7ba25be2012-11-14 14:18:06 -0800263 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700264 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
265 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800266 git_trace2_event_log.StartEvent()
267
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700268 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400269 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800270 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400271 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900272 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400273 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900274 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400275 if isinstance(e, NoManifestException):
276 print('error: manifest missing or unreadable -- please run init',
277 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800278 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700279 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700280 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700281 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700283 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800284 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700285 except InvalidProjectGroupsError as e:
286 if e.name:
287 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
288 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900289 print('error: project group must be enabled for the project in the current directory',
290 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700291 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700292 except SystemExit as e:
293 if e.code:
294 result = e.code
295 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800296 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700297 finish = time.time()
298 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800299 hours, remainder = divmod(elapsed, 3600)
300 minutes, seconds = divmod(remainder, 60)
301 if gopts.time:
302 if hours == 0:
303 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
304 else:
305 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
306 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400307
David Rileye0684ad2017-04-05 00:02:59 -0700308 cmd.event_log.FinishEvent(cmd_event, finish,
309 result is None or result == 0)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800310 git_trace2_event_log.ExitEvent(result)
311
David Rileye0684ad2017-04-05 00:02:59 -0700312 if gopts.event_log:
313 cmd.event_log.Write(os.path.abspath(
314 os.path.expanduser(gopts.event_log)))
315
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800316 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400317 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700318
Conley Owens094cdbe2014-01-30 15:09:59 -0800319
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500320def _CheckWrapperVersion(ver_str, repo_path):
321 """Verify the repo launcher is new enough for this checkout.
322
323 Args:
324 ver_str: The version string passed from the repo launcher when it ran us.
325 repo_path: The path to the repo launcher that loaded us.
326 """
327 # Refuse to work with really old wrapper versions. We don't test these,
328 # so might as well require a somewhat recent sane version.
329 # v1.15 of the repo launcher was released in ~Mar 2012.
330 MIN_REPO_VERSION = (1, 15)
331 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
332
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700333 if not repo_path:
334 repo_path = '~/bin/repo'
335
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500336 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700337 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900338 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700339
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500340 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800341 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500342 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700343
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900344 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500345 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700346 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500347repo: error:
348!!! Your version of repo %s is too old.
349!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900350!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500351!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700352
353 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500354""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700355 sys.exit(1)
356
357 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500358 print('\n... A new version of repo (%s) is available.' % (exp_str,),
359 file=sys.stderr)
360 if os.access(repo_path, os.W_OK):
361 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700362... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500364""" % (WrapperPath(), repo_path), file=sys.stderr)
365 else:
366 print("""\
367... New version is available at: %s
368... The launcher is run from: %s
369!!! The launcher is not writable. Please talk to your sysadmin or distro
370!!! to get an update installed.
371""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372
David Pursehouse819827a2020-02-12 15:20:19 +0900373
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200374def _CheckRepoDir(repo_dir):
375 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700376 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900377 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700378
David Pursehouse819827a2020-02-12 15:20:19 +0900379
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700380def _PruneOptions(argv, opt):
381 i = 0
382 while i < len(argv):
383 a = argv[i]
384 if a == '--':
385 break
386 if a.startswith('--'):
387 eq = a.find('=')
388 if eq > 0:
389 a = a[0:eq]
390 if not opt.has_option(a):
391 del argv[i]
392 continue
393 i += 1
394
David Pursehouse819827a2020-02-12 15:20:19 +0900395
Sarah Owens1f7627f2012-10-31 09:21:55 -0700396class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700397 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400398 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700399 return req
400
401 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400402 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700403 return req
404
David Pursehouse819827a2020-02-12 15:20:19 +0900405
JoonCheol Parke9860722012-10-11 02:31:44 +0900406def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900407 # If repo could not find auth info from netrc, try to get it from user input
408 url = req.get_full_url()
409 user, password = handler.passwd.find_user_password(None, url)
410 if user is None:
411 print(msg)
412 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530413 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900414 password = getpass.getpass()
415 except KeyboardInterrupt:
416 return
417 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900418
David Pursehouse819827a2020-02-12 15:20:19 +0900419
Sarah Owens1f7627f2012-10-31 09:21:55 -0700420class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900421 def http_error_401(self, req, fp, code, msg, headers):
422 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700423 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900424 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900425
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700426 def http_error_auth_reqed(self, authreq, host, req, headers):
427 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700428 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900429
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700430 def _add_header(name, val):
431 val = val.replace('\n', '')
432 old_add_header(name, val)
433 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700434 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900435 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900436 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700437 reset = getattr(self, 'reset_retry_count', None)
438 if reset is not None:
439 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700440 elif getattr(self, 'retried', None):
441 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700442 raise
443
David Pursehouse819827a2020-02-12 15:20:19 +0900444
Sarah Owens1f7627f2012-10-31 09:21:55 -0700445class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900446 def http_error_401(self, req, fp, code, msg, headers):
447 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700448 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900449 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900450
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800451 def http_error_auth_reqed(self, auth_header, host, req, headers):
452 try:
453 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900454
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800455 def _add_header(name, val):
456 val = val.replace('\n', '')
457 old_add_header(name, val)
458 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700459 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900460 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900461 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800462 reset = getattr(self, 'reset_retry_count', None)
463 if reset is not None:
464 reset()
465 elif getattr(self, 'retried', None):
466 self.retried = 0
467 raise
468
David Pursehouse819827a2020-02-12 15:20:19 +0900469
Carlos Aguado1242e602014-02-03 13:48:47 +0100470class _KerberosAuthHandler(urllib.request.BaseHandler):
471 def __init__(self):
472 self.retried = 0
473 self.context = None
474 self.handler_order = urllib.request.BaseHandler.handler_order - 50
475
David Pursehouse65b0ba52018-06-24 16:21:51 +0900476 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100477 host = req.get_host()
478 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
479 return retry
480
481 def http_error_auth_reqed(self, auth_header, host, req, headers):
482 try:
483 spn = "HTTP@%s" % host
484 authdata = self._negotiate_get_authdata(auth_header, headers)
485
486 if self.retried > 3:
487 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900488 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100489 else:
490 self.retried += 1
491
492 neghdr = self._negotiate_get_svctk(spn, authdata)
493 if neghdr is None:
494 return None
495
496 req.add_unredirected_header('Authorization', neghdr)
497 response = self.parent.open(req)
498
499 srvauth = self._negotiate_get_authdata(auth_header, response.info())
500 if self._validate_response(srvauth):
501 return response
502 except kerberos.GSSError:
503 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900504 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100505 self.reset_retry_count()
506 raise
507 finally:
508 self._clean_context()
509
510 def reset_retry_count(self):
511 self.retried = 0
512
513 def _negotiate_get_authdata(self, auth_header, headers):
514 authhdr = headers.get(auth_header, None)
515 if authhdr is not None:
516 for mech_tuple in authhdr.split(","):
517 mech, __, authdata = mech_tuple.strip().partition(" ")
518 if mech.lower() == "negotiate":
519 return authdata.strip()
520 return None
521
522 def _negotiate_get_svctk(self, spn, authdata):
523 if authdata is None:
524 return None
525
526 result, self.context = kerberos.authGSSClientInit(spn)
527 if result < kerberos.AUTH_GSS_COMPLETE:
528 return None
529
530 result = kerberos.authGSSClientStep(self.context, authdata)
531 if result < kerberos.AUTH_GSS_CONTINUE:
532 return None
533
534 response = kerberos.authGSSClientResponse(self.context)
535 return "Negotiate %s" % response
536
537 def _validate_response(self, authdata):
538 if authdata is None:
539 return None
540 result = kerberos.authGSSClientStep(self.context, authdata)
541 if result == kerberos.AUTH_GSS_COMPLETE:
542 return True
543 return None
544
545 def _clean_context(self):
546 if self.context is not None:
547 kerberos.authGSSClientClean(self.context)
548 self.context = None
549
David Pursehouse819827a2020-02-12 15:20:19 +0900550
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700551def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700552 handlers = [_UserAgentHandler()]
553
Sarah Owens1f7627f2012-10-31 09:21:55 -0700554 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700555 try:
556 n = netrc.netrc()
557 for host in n.hosts:
558 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900559 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800560 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700561 except netrc.NetrcParseError:
562 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700563 except IOError:
564 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700565 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800566 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100567 if kerberos:
568 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700569
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700570 if 'http_proxy' in os.environ:
571 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700572 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700573 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700574 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
575 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
576 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700577
David Pursehouse819827a2020-02-12 15:20:19 +0900578
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700579def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400580 result = 0
581
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700582 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
583 opt.add_option("--repo-dir", dest="repodir",
584 help="path to .repo/")
585 opt.add_option("--wrapper-version", dest="wrapper_version",
586 help="version of the wrapper script")
587 opt.add_option("--wrapper-path", dest="wrapper_path",
588 help="location of the wrapper script")
589 _PruneOptions(argv, opt)
590 opt, argv = opt.parse_args(argv)
591
592 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
593 _CheckRepoDir(opt.repodir)
594
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800595 Version.wrapper_version = opt.wrapper_version
596 Version.wrapper_path = opt.wrapper_path
597
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700598 repo = _Repo(opt.repodir)
599 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700600 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800601 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700602 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400603 name, gopts, argv = repo._ParseArgs(argv)
604 run = lambda: repo._Run(name, gopts, argv) or 0
605 if gopts.trace_python:
606 import trace
607 tracer = trace.Trace(count=False, trace=True, timing=True,
608 ignoredirs=set(sys.path[1:]))
609 result = tracer.runfunc(run)
610 else:
611 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700612 finally:
613 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700614 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700615 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400616 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900617 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700618 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900619 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700620 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800621 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700622 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800623 argv = list(sys.argv)
624 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400626 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700627 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700628 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
629 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400630 result = 128
631
Renaud Paquaye8595e92016-11-01 15:51:59 -0700632 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400633 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700634
David Pursehouse819827a2020-02-12 15:20:19 +0900635
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700636if __name__ == '__main__':
637 _Main(sys.argv[1:])