blob: a7c3c684b12a1d7555c3ac0de8b978b02f89964c [file] [log] [blame]
Mike Frysingera488af52020-09-06 13:33:45 -04001#!/usr/bin/env python3
Mike Frysingerf6013762019-06-13 02:30:51 -04002# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003#
4# Copyright (C) 2008 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
Mike Frysinger87fb5a12019-06-13 01:54:46 -040018"""The repo tool.
19
20People shouldn't run this directly; instead, they should use the `repo` wrapper
21which takes care of execing this entry point.
22"""
23
Sarah Owenscecd1d82012-11-01 22:59:27 -070024from __future__ import print_function
JoonCheol Parke9860722012-10-11 02:31:44 +090025import getpass
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070026import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027import optparse
28import os
Mike Frysinger949bc342020-02-18 21:37:00 -050029import shlex
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050031import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070032import time
David Pursehouse59bbb582013-05-17 10:49:33 +090033
34from pyversion import is_python3
35if is_python3():
Sarah Owens1f7627f2012-10-31 09:21:55 -070036 import urllib.request
37else:
Rashed Abdel-Tawab2058c632019-10-05 00:18:41 -040038 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +090039 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -070040 urllib = imp.new_module('urllib')
41 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
Carlos Aguado1242e602014-02-03 13:48:47 +010043try:
44 import kerberos
45except ImportError:
46 kerberos = None
47
Mike Frysinger902665b2014-12-22 15:17:59 -050048from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070049import event_log
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040050from repo_trace import SetTrace
David Pursehouse9090e802020-02-12 11:25:13 +090051from git_command import user_agent
Mike Frysinger949bc342020-02-18 21:37:00 -050052from git_config import init_ssh, close_ssh, RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080053from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080054from command import InteractiveCommand
55from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070056from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080057from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070058from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070059from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070060from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080061from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090062from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080063from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070064from error import NoSuchProjectError
65from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070066import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040067from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070068from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080069from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070070
David Pursehouse5c6eeac2012-10-11 16:44:48 +090071from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070072
David Pursehouse59bbb582013-05-17 10:49:33 +090073if not is_python3():
David Pursehousea46bf7d2020-02-15 12:45:53 +090074 input = raw_input # noqa: F821
Chirayu Desai217ea7d2013-03-01 19:14:38 +053075
Mike Frysinger37f28f12020-02-16 15:15:53 -050076# NB: These do not need to be kept in sync with the repo launcher script.
77# These may be much newer as it allows the repo launcher to roll between
78# different repo releases while source versions might require a newer python.
79#
80# The soft version is when we start warning users that the version is old and
81# we'll be dropping support for it. We'll refuse to work with versions older
82# than the hard version.
83#
84# python-3.6 is in Ubuntu Bionic.
85MIN_PYTHON_VERSION_SOFT = (3, 6)
86MIN_PYTHON_VERSION_HARD = (3, 4)
87
88if sys.version_info.major < 3:
Mike Frysingera488af52020-09-06 13:33:45 -040089 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050090 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
91 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040092 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050093else:
94 if sys.version_info < MIN_PYTHON_VERSION_HARD:
95 print('repo: error: Python 3 version is too old; '
96 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
97 file=sys.stderr)
98 sys.exit(1)
99 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
100 print('repo: warning: your Python 3 version is no longer supported; '
101 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
102 file=sys.stderr)
103
104
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -0500106 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
107 add_help_option=False)
108global_options.add_option('-h', '--help', action='store_true',
109 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110global_options.add_option('-p', '--paginate',
111 dest='pager', action='store_true',
112 help='display command output in the pager')
113global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500114 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500116global_options.add_option('--color',
117 choices=('auto', 'always', 'never'), default=None,
118 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700119global_options.add_option('--trace',
120 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400121 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400122global_options.add_option('--trace-python',
123 dest='trace_python', action='store_true',
124 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700125global_options.add_option('--time',
126 dest='time', action='store_true',
127 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800128global_options.add_option('--version',
129 dest='show_version', action='store_true',
130 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700131global_options.add_option('--event-log',
132 dest='event_log', action='store',
133 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800134global_options.add_option('--git-trace2-event-log', action='store',
135 help='directory to write git trace2 event log to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136
David Pursehouse819827a2020-02-12 15:20:19 +0900137
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138class _Repo(object):
139 def __init__(self, repodir):
140 self.repodir = repodir
141 self.commands = all_commands
142
Mike Frysinger3fc15722019-08-27 00:36:46 -0400143 def _ParseArgs(self, argv):
144 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700145 name = None
146 glob = []
147
Sarah Owensa6053d52012-11-01 13:36:50 -0700148 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149 if not argv[i].startswith('-'):
150 name = argv[i]
151 if i > 0:
152 glob = argv[:i]
153 argv = argv[i + 1:]
154 break
155 if not name:
156 glob = argv
157 name = 'help'
158 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900159 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160
Mike Frysinger949bc342020-02-18 21:37:00 -0500161 name, alias_args = self._ExpandAlias(name)
162 argv = alias_args + argv
163
Mike Frysinger7c321f12019-12-02 16:49:44 -0500164 if gopts.help:
165 global_options.print_help()
166 commands = ' '.join(sorted(self.commands))
167 wrapped_commands = textwrap.wrap(commands, width=77)
168 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
169 print('\nRun `repo help <command>` for command-specific details.')
170 global_options.exit()
171
Mike Frysinger3fc15722019-08-27 00:36:46 -0400172 return (name, gopts, argv)
173
Mike Frysinger949bc342020-02-18 21:37:00 -0500174 def _ExpandAlias(self, name):
175 """Look up user registered aliases."""
176 # We don't resolve aliases for existing subcommands. This matches git.
177 if name in self.commands:
178 return name, []
179
180 key = 'alias.%s' % (name,)
181 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
182 if alias is None:
183 alias = RepoConfig.ForUser().GetString(key)
184 if alias is None:
185 return name, []
186
187 args = alias.strip().split(' ', 1)
188 name = args[0]
189 if len(args) == 2:
190 args = shlex.split(args[1])
191 else:
192 args = []
193 return name, args
194
Mike Frysinger3fc15722019-08-27 00:36:46 -0400195 def _Run(self, name, gopts, argv):
196 """Execute the requested subcommand."""
197 result = 0
198
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700199 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700200 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800201 if gopts.show_version:
202 if name == 'help':
203 name = 'version'
204 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700205 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400206 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800207
Mike Frysinger902665b2014-12-22 15:17:59 -0500208 SetDefaultColoring(gopts.color)
209
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700210 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500211 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700212 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700213 print("repo: '%s' is not a repo command. See 'repo help'." % name,
214 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400215 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800217 git_trace2_event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218 cmd.repodir = self.repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400219 cmd.client = RepoClient(cmd.repodir)
220 cmd.manifest = cmd.client.manifest
Simran Basib9a1b732015-08-20 12:19:28 -0700221 cmd.gitc_manifest = None
222 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
223 if gitc_client_name:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400224 cmd.gitc_manifest = GitcClient(cmd.repodir, gitc_client_name)
225 cmd.client.isGitcClient = True
Simran Basib9a1b732015-08-20 12:19:28 -0700226
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400227 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800229 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700230 print("fatal: '%s' requires a working directory" % name,
231 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400232 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800233
Dan Willemsen79360642015-08-31 15:45:06 -0700234 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700235 print("fatal: '%s' requires GITC to be available" % name,
236 file=sys.stderr)
237 return 1
238
Dan Willemsen79360642015-08-31 15:45:06 -0700239 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
240 print("fatal: '%s' requires a GITC client" % name,
241 file=sys.stderr)
242 return 1
243
Dan Sandler53e902a2014-03-09 13:20:02 -0400244 try:
245 copts, cargs = cmd.OptionParser.parse_args(argv)
246 copts = cmd.ReadEnvironmentOptions(copts)
247 except NoManifestException as e:
248 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900249 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400250 print('error: manifest missing or unreadable -- please run init',
251 file=sys.stderr)
252 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700253
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500254 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400255 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 if gopts.pager:
257 use_pager = True
258 else:
259 use_pager = config.GetBoolean('pager.%s' % name)
260 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700261 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700262 if use_pager:
263 RunPager(config)
264
Conley Owens7ba25be2012-11-14 14:18:06 -0800265 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700266 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
267 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800268 git_trace2_event_log.StartEvent()
269
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400271 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800272 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400273 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900274 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400275 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900276 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400277 if isinstance(e, NoManifestException):
278 print('error: manifest missing or unreadable -- please run init',
279 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800280 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700281 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700283 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700284 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700285 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800286 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700287 except InvalidProjectGroupsError as e:
288 if e.name:
289 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
290 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900291 print('error: project group must be enabled for the project in the current directory',
292 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700293 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700294 except SystemExit as e:
295 if e.code:
296 result = e.code
297 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800298 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700299 finish = time.time()
300 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800301 hours, remainder = divmod(elapsed, 3600)
302 minutes, seconds = divmod(remainder, 60)
303 if gopts.time:
304 if hours == 0:
305 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
306 else:
307 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
308 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400309
David Rileye0684ad2017-04-05 00:02:59 -0700310 cmd.event_log.FinishEvent(cmd_event, finish,
311 result is None or result == 0)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800312 git_trace2_event_log.ExitEvent(result)
313
David Rileye0684ad2017-04-05 00:02:59 -0700314 if gopts.event_log:
315 cmd.event_log.Write(os.path.abspath(
316 os.path.expanduser(gopts.event_log)))
317
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800318 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400319 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320
Conley Owens094cdbe2014-01-30 15:09:59 -0800321
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500322def _CheckWrapperVersion(ver_str, repo_path):
323 """Verify the repo launcher is new enough for this checkout.
324
325 Args:
326 ver_str: The version string passed from the repo launcher when it ran us.
327 repo_path: The path to the repo launcher that loaded us.
328 """
329 # Refuse to work with really old wrapper versions. We don't test these,
330 # so might as well require a somewhat recent sane version.
331 # v1.15 of the repo launcher was released in ~Mar 2012.
332 MIN_REPO_VERSION = (1, 15)
333 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
334
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700335 if not repo_path:
336 repo_path = '~/bin/repo'
337
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500338 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700339 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900340 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700341
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500342 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800343 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500344 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700345
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900346 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500347 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700348 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500349repo: error:
350!!! Your version of repo %s is too old.
351!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900352!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500353!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700354
355 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500356""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357 sys.exit(1)
358
359 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500360 print('\n... A new version of repo (%s) is available.' % (exp_str,),
361 file=sys.stderr)
362 if os.access(repo_path, os.W_OK):
363 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700365 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500366""" % (WrapperPath(), repo_path), file=sys.stderr)
367 else:
368 print("""\
369... New version is available at: %s
370... The launcher is run from: %s
371!!! The launcher is not writable. Please talk to your sysadmin or distro
372!!! to get an update installed.
373""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700374
David Pursehouse819827a2020-02-12 15:20:19 +0900375
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200376def _CheckRepoDir(repo_dir):
377 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700378 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900379 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700380
David Pursehouse819827a2020-02-12 15:20:19 +0900381
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700382def _PruneOptions(argv, opt):
383 i = 0
384 while i < len(argv):
385 a = argv[i]
386 if a == '--':
387 break
388 if a.startswith('--'):
389 eq = a.find('=')
390 if eq > 0:
391 a = a[0:eq]
392 if not opt.has_option(a):
393 del argv[i]
394 continue
395 i += 1
396
David Pursehouse819827a2020-02-12 15:20:19 +0900397
Sarah Owens1f7627f2012-10-31 09:21:55 -0700398class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700399 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400400 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700401 return req
402
403 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400404 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700405 return req
406
David Pursehouse819827a2020-02-12 15:20:19 +0900407
JoonCheol Parke9860722012-10-11 02:31:44 +0900408def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900409 # If repo could not find auth info from netrc, try to get it from user input
410 url = req.get_full_url()
411 user, password = handler.passwd.find_user_password(None, url)
412 if user is None:
413 print(msg)
414 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530415 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900416 password = getpass.getpass()
417 except KeyboardInterrupt:
418 return
419 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900420
David Pursehouse819827a2020-02-12 15:20:19 +0900421
Sarah Owens1f7627f2012-10-31 09:21:55 -0700422class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900423 def http_error_401(self, req, fp, code, msg, headers):
424 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700425 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900426 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900427
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700428 def http_error_auth_reqed(self, authreq, host, req, headers):
429 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700430 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900431
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700432 def _add_header(name, val):
433 val = val.replace('\n', '')
434 old_add_header(name, val)
435 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700436 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900437 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900438 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700439 reset = getattr(self, 'reset_retry_count', None)
440 if reset is not None:
441 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700442 elif getattr(self, 'retried', None):
443 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700444 raise
445
David Pursehouse819827a2020-02-12 15:20:19 +0900446
Sarah Owens1f7627f2012-10-31 09:21:55 -0700447class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900448 def http_error_401(self, req, fp, code, msg, headers):
449 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700450 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900451 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900452
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800453 def http_error_auth_reqed(self, auth_header, host, req, headers):
454 try:
455 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900456
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800457 def _add_header(name, val):
458 val = val.replace('\n', '')
459 old_add_header(name, val)
460 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700461 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900462 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900463 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800464 reset = getattr(self, 'reset_retry_count', None)
465 if reset is not None:
466 reset()
467 elif getattr(self, 'retried', None):
468 self.retried = 0
469 raise
470
David Pursehouse819827a2020-02-12 15:20:19 +0900471
Carlos Aguado1242e602014-02-03 13:48:47 +0100472class _KerberosAuthHandler(urllib.request.BaseHandler):
473 def __init__(self):
474 self.retried = 0
475 self.context = None
476 self.handler_order = urllib.request.BaseHandler.handler_order - 50
477
David Pursehouse65b0ba52018-06-24 16:21:51 +0900478 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100479 host = req.get_host()
480 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
481 return retry
482
483 def http_error_auth_reqed(self, auth_header, host, req, headers):
484 try:
485 spn = "HTTP@%s" % host
486 authdata = self._negotiate_get_authdata(auth_header, headers)
487
488 if self.retried > 3:
489 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900490 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100491 else:
492 self.retried += 1
493
494 neghdr = self._negotiate_get_svctk(spn, authdata)
495 if neghdr is None:
496 return None
497
498 req.add_unredirected_header('Authorization', neghdr)
499 response = self.parent.open(req)
500
501 srvauth = self._negotiate_get_authdata(auth_header, response.info())
502 if self._validate_response(srvauth):
503 return response
504 except kerberos.GSSError:
505 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900506 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100507 self.reset_retry_count()
508 raise
509 finally:
510 self._clean_context()
511
512 def reset_retry_count(self):
513 self.retried = 0
514
515 def _negotiate_get_authdata(self, auth_header, headers):
516 authhdr = headers.get(auth_header, None)
517 if authhdr is not None:
518 for mech_tuple in authhdr.split(","):
519 mech, __, authdata = mech_tuple.strip().partition(" ")
520 if mech.lower() == "negotiate":
521 return authdata.strip()
522 return None
523
524 def _negotiate_get_svctk(self, spn, authdata):
525 if authdata is None:
526 return None
527
528 result, self.context = kerberos.authGSSClientInit(spn)
529 if result < kerberos.AUTH_GSS_COMPLETE:
530 return None
531
532 result = kerberos.authGSSClientStep(self.context, authdata)
533 if result < kerberos.AUTH_GSS_CONTINUE:
534 return None
535
536 response = kerberos.authGSSClientResponse(self.context)
537 return "Negotiate %s" % response
538
539 def _validate_response(self, authdata):
540 if authdata is None:
541 return None
542 result = kerberos.authGSSClientStep(self.context, authdata)
543 if result == kerberos.AUTH_GSS_COMPLETE:
544 return True
545 return None
546
547 def _clean_context(self):
548 if self.context is not None:
549 kerberos.authGSSClientClean(self.context)
550 self.context = None
551
David Pursehouse819827a2020-02-12 15:20:19 +0900552
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700553def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700554 handlers = [_UserAgentHandler()]
555
Sarah Owens1f7627f2012-10-31 09:21:55 -0700556 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700557 try:
558 n = netrc.netrc()
559 for host in n.hosts:
560 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900561 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800562 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700563 except netrc.NetrcParseError:
564 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700565 except IOError:
566 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700567 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800568 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100569 if kerberos:
570 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700571
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700572 if 'http_proxy' in os.environ:
573 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700574 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700575 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700576 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
577 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
578 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700579
David Pursehouse819827a2020-02-12 15:20:19 +0900580
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700581def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400582 result = 0
583
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700584 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
585 opt.add_option("--repo-dir", dest="repodir",
586 help="path to .repo/")
587 opt.add_option("--wrapper-version", dest="wrapper_version",
588 help="version of the wrapper script")
589 opt.add_option("--wrapper-path", dest="wrapper_path",
590 help="location of the wrapper script")
591 _PruneOptions(argv, opt)
592 opt, argv = opt.parse_args(argv)
593
594 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
595 _CheckRepoDir(opt.repodir)
596
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800597 Version.wrapper_version = opt.wrapper_version
598 Version.wrapper_path = opt.wrapper_path
599
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700600 repo = _Repo(opt.repodir)
601 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700602 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800603 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700604 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400605 name, gopts, argv = repo._ParseArgs(argv)
606 run = lambda: repo._Run(name, gopts, argv) or 0
607 if gopts.trace_python:
608 import trace
609 tracer = trace.Trace(count=False, trace=True, timing=True,
610 ignoredirs=set(sys.path[1:]))
611 result = tracer.runfunc(run)
612 else:
613 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700614 finally:
615 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700616 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700617 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400618 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900619 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700620 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900621 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700622 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800623 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700624 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800625 argv = list(sys.argv)
626 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700627 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400628 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700629 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700630 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
631 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400632 result = 128
633
Renaud Paquaye8595e92016-11-01 15:51:59 -0700634 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400635 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700636
David Pursehouse819827a2020-02-12 15:20:19 +0900637
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700638if __name__ == '__main__':
639 _Main(sys.argv[1:])