blob: 8aba2ec2b6586b03d85304f6264c541ae937136e [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 Frysinger949bc342020-02-18 21:37:00 -050042from git_config import init_ssh, close_ssh, RepoConfig
Ian Kasprzak30bc3542020-12-23 10:08:20 -080043from git_trace2_event_log import EventLog
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080044from command import InteractiveCommand
45from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070046from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080047from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070048from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070049from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070050from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080051from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090052from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080053from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070054from error import NoSuchProjectError
55from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070056import gitc_utils
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -040057from manifest_xml import GitcClient, RepoClient
Renaud Paquaye8595e92016-11-01 15:51:59 -070058from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080059from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070060
David Pursehouse5c6eeac2012-10-11 16:44:48 +090061from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070062
Chirayu Desai217ea7d2013-03-01 19:14:38 +053063
Mike Frysinger37f28f12020-02-16 15:15:53 -050064# NB: These do not need to be kept in sync with the repo launcher script.
65# These may be much newer as it allows the repo launcher to roll between
66# different repo releases while source versions might require a newer python.
67#
68# The soft version is when we start warning users that the version is old and
69# we'll be dropping support for it. We'll refuse to work with versions older
70# than the hard version.
71#
72# python-3.6 is in Ubuntu Bionic.
73MIN_PYTHON_VERSION_SOFT = (3, 6)
Mike Frysinger128f34e2020-12-14 18:28:04 -050074MIN_PYTHON_VERSION_HARD = (3, 5)
Mike Frysinger37f28f12020-02-16 15:15:53 -050075
76if sys.version_info.major < 3:
Mike Frysingera488af52020-09-06 13:33:45 -040077 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050078 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
79 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040080 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050081else:
82 if sys.version_info < MIN_PYTHON_VERSION_HARD:
83 print('repo: error: Python 3 version is too old; '
84 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
85 file=sys.stderr)
86 sys.exit(1)
87 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
88 print('repo: warning: your Python 3 version is no longer supported; '
89 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
90 file=sys.stderr)
91
92
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070093global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -050094 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
95 add_help_option=False)
96global_options.add_option('-h', '--help', action='store_true',
97 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070098global_options.add_option('-p', '--paginate',
99 dest='pager', action='store_true',
100 help='display command output in the pager')
101global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500102 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500104global_options.add_option('--color',
105 choices=('auto', 'always', 'never'), default=None,
106 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700107global_options.add_option('--trace',
108 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400109 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400110global_options.add_option('--trace-python',
111 dest='trace_python', action='store_true',
112 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700113global_options.add_option('--time',
114 dest='time', action='store_true',
115 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800116global_options.add_option('--version',
117 dest='show_version', action='store_true',
118 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700119global_options.add_option('--event-log',
120 dest='event_log', action='store',
121 help='filename of event log to append timeline to')
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800122global_options.add_option('--git-trace2-event-log', action='store',
123 help='directory to write git trace2 event log to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124
David Pursehouse819827a2020-02-12 15:20:19 +0900125
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126class _Repo(object):
127 def __init__(self, repodir):
128 self.repodir = repodir
129 self.commands = all_commands
130
Mike Frysinger3fc15722019-08-27 00:36:46 -0400131 def _ParseArgs(self, argv):
132 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133 name = None
134 glob = []
135
Sarah Owensa6053d52012-11-01 13:36:50 -0700136 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137 if not argv[i].startswith('-'):
138 name = argv[i]
139 if i > 0:
140 glob = argv[:i]
141 argv = argv[i + 1:]
142 break
143 if not name:
144 glob = argv
145 name = 'help'
146 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900147 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700148
Mike Frysinger949bc342020-02-18 21:37:00 -0500149 name, alias_args = self._ExpandAlias(name)
150 argv = alias_args + argv
151
Mike Frysinger7c321f12019-12-02 16:49:44 -0500152 if gopts.help:
153 global_options.print_help()
154 commands = ' '.join(sorted(self.commands))
155 wrapped_commands = textwrap.wrap(commands, width=77)
156 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
157 print('\nRun `repo help <command>` for command-specific details.')
158 global_options.exit()
159
Mike Frysinger3fc15722019-08-27 00:36:46 -0400160 return (name, gopts, argv)
161
Mike Frysinger949bc342020-02-18 21:37:00 -0500162 def _ExpandAlias(self, name):
163 """Look up user registered aliases."""
164 # We don't resolve aliases for existing subcommands. This matches git.
165 if name in self.commands:
166 return name, []
167
168 key = 'alias.%s' % (name,)
169 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
170 if alias is None:
171 alias = RepoConfig.ForUser().GetString(key)
172 if alias is None:
173 return name, []
174
175 args = alias.strip().split(' ', 1)
176 name = args[0]
177 if len(args) == 2:
178 args = shlex.split(args[1])
179 else:
180 args = []
181 return name, args
182
Mike Frysinger3fc15722019-08-27 00:36:46 -0400183 def _Run(self, name, gopts, argv):
184 """Execute the requested subcommand."""
185 result = 0
186
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700187 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700188 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800189 if gopts.show_version:
190 if name == 'help':
191 name = 'version'
192 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700193 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400194 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800195
Mike Frysinger902665b2014-12-22 15:17:59 -0500196 SetDefaultColoring(gopts.color)
197
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500199 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700201 print("repo: '%s' is not a repo command. See 'repo help'." % name,
202 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400203 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800205 git_trace2_event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206 cmd.repodir = self.repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400207 cmd.client = RepoClient(cmd.repodir)
208 cmd.manifest = cmd.client.manifest
Simran Basib9a1b732015-08-20 12:19:28 -0700209 cmd.gitc_manifest = None
210 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
211 if gitc_client_name:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400212 cmd.gitc_manifest = GitcClient(cmd.repodir, gitc_client_name)
213 cmd.client.isGitcClient = True
Simran Basib9a1b732015-08-20 12:19:28 -0700214
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400215 Editor.globalConfig = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800217 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700218 print("fatal: '%s' requires a working directory" % name,
219 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400220 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800221
Dan Willemsen79360642015-08-31 15:45:06 -0700222 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700223 print("fatal: '%s' requires GITC to be available" % name,
224 file=sys.stderr)
225 return 1
226
Dan Willemsen79360642015-08-31 15:45:06 -0700227 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
228 print("fatal: '%s' requires a GITC client" % name,
229 file=sys.stderr)
230 return 1
231
Dan Sandler53e902a2014-03-09 13:20:02 -0400232 try:
233 copts, cargs = cmd.OptionParser.parse_args(argv)
234 copts = cmd.ReadEnvironmentOptions(copts)
235 except NoManifestException as e:
236 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900237 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400238 print('error: manifest missing or unreadable -- please run init',
239 file=sys.stderr)
240 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700241
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500242 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400243 config = cmd.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700244 if gopts.pager:
245 use_pager = True
246 else:
247 use_pager = config.GetBoolean('pager.%s' % name)
248 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700249 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700250 if use_pager:
251 RunPager(config)
252
Conley Owens7ba25be2012-11-14 14:18:06 -0800253 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700254 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
255 cmd.event_log.SetParent(cmd_event)
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800256 git_trace2_event_log.StartEvent()
Raman Tennetia5b40a22021-03-16 14:24:14 -0700257 git_trace2_event_log.CommandEvent(name='repo', subcommands=[name])
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800258
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700259 try:
Mike Frysinger9180a072021-04-13 14:57:40 -0400260 cmd.CommonValidateOptions(copts, cargs)
Mike Frysingerae6cb082019-08-27 01:10:59 -0400261 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800262 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400263 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900264 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400265 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900266 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400267 if isinstance(e, NoManifestException):
268 print('error: manifest missing or unreadable -- please run init',
269 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800270 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700271 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700273 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700275 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800276 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700277 except InvalidProjectGroupsError as e:
278 if e.name:
279 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
280 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900281 print('error: project group must be enabled for the project in the current directory',
282 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700283 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700284 except SystemExit as e:
285 if e.code:
286 result = e.code
287 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800288 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700289 finish = time.time()
290 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800291 hours, remainder = divmod(elapsed, 3600)
292 minutes, seconds = divmod(remainder, 60)
293 if gopts.time:
294 if hours == 0:
295 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
296 else:
297 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
298 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400299
David Rileye0684ad2017-04-05 00:02:59 -0700300 cmd.event_log.FinishEvent(cmd_event, finish,
301 result is None or result == 0)
Ian Kasprzak835a34b2021-03-05 11:04:49 -0800302 git_trace2_event_log.DefParamRepoEvents(
303 cmd.manifest.manifestProject.config.DumpConfigDict())
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800304 git_trace2_event_log.ExitEvent(result)
305
David Rileye0684ad2017-04-05 00:02:59 -0700306 if gopts.event_log:
307 cmd.event_log.Write(os.path.abspath(
308 os.path.expanduser(gopts.event_log)))
309
Ian Kasprzak30bc3542020-12-23 10:08:20 -0800310 git_trace2_event_log.Write(gopts.git_trace2_event_log)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400311 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700312
Conley Owens094cdbe2014-01-30 15:09:59 -0800313
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500314def _CheckWrapperVersion(ver_str, repo_path):
315 """Verify the repo launcher is new enough for this checkout.
316
317 Args:
318 ver_str: The version string passed from the repo launcher when it ran us.
319 repo_path: The path to the repo launcher that loaded us.
320 """
321 # Refuse to work with really old wrapper versions. We don't test these,
322 # so might as well require a somewhat recent sane version.
323 # v1.15 of the repo launcher was released in ~Mar 2012.
324 MIN_REPO_VERSION = (1, 15)
325 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
326
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700327 if not repo_path:
328 repo_path = '~/bin/repo'
329
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500330 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700331 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900332 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700333
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500334 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800335 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500336 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900338 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500339 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700340 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500341repo: error:
342!!! Your version of repo %s is too old.
343!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900344!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500345!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700346
347 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500348""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349 sys.exit(1)
350
351 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500352 print('\n... A new version of repo (%s) is available.' % (exp_str,),
353 file=sys.stderr)
354 if os.access(repo_path, os.W_OK):
355 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700356... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500358""" % (WrapperPath(), repo_path), file=sys.stderr)
359 else:
360 print("""\
361... New version is available at: %s
362... The launcher is run from: %s
363!!! The launcher is not writable. Please talk to your sysadmin or distro
364!!! to get an update installed.
365""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700366
David Pursehouse819827a2020-02-12 15:20:19 +0900367
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200368def _CheckRepoDir(repo_dir):
369 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700370 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900371 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372
David Pursehouse819827a2020-02-12 15:20:19 +0900373
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700374def _PruneOptions(argv, opt):
375 i = 0
376 while i < len(argv):
377 a = argv[i]
378 if a == '--':
379 break
380 if a.startswith('--'):
381 eq = a.find('=')
382 if eq > 0:
383 a = a[0:eq]
384 if not opt.has_option(a):
385 del argv[i]
386 continue
387 i += 1
388
David Pursehouse819827a2020-02-12 15:20:19 +0900389
Sarah Owens1f7627f2012-10-31 09:21:55 -0700390class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700391 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400392 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700393 return req
394
395 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400396 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700397 return req
398
David Pursehouse819827a2020-02-12 15:20:19 +0900399
JoonCheol Parke9860722012-10-11 02:31:44 +0900400def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900401 # If repo could not find auth info from netrc, try to get it from user input
402 url = req.get_full_url()
403 user, password = handler.passwd.find_user_password(None, url)
404 if user is None:
405 print(msg)
406 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530407 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900408 password = getpass.getpass()
409 except KeyboardInterrupt:
410 return
411 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900412
David Pursehouse819827a2020-02-12 15:20:19 +0900413
Sarah Owens1f7627f2012-10-31 09:21:55 -0700414class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900415 def http_error_401(self, req, fp, code, msg, headers):
416 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700417 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900418 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900419
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700420 def http_error_auth_reqed(self, authreq, host, req, headers):
421 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700422 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900423
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700424 def _add_header(name, val):
425 val = val.replace('\n', '')
426 old_add_header(name, val)
427 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700428 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900429 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900430 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700431 reset = getattr(self, 'reset_retry_count', None)
432 if reset is not None:
433 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700434 elif getattr(self, 'retried', None):
435 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700436 raise
437
David Pursehouse819827a2020-02-12 15:20:19 +0900438
Sarah Owens1f7627f2012-10-31 09:21:55 -0700439class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900440 def http_error_401(self, req, fp, code, msg, headers):
441 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700442 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900443 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900444
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800445 def http_error_auth_reqed(self, auth_header, host, req, headers):
446 try:
447 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900448
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800449 def _add_header(name, val):
450 val = val.replace('\n', '')
451 old_add_header(name, val)
452 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700453 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900454 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900455 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800456 reset = getattr(self, 'reset_retry_count', None)
457 if reset is not None:
458 reset()
459 elif getattr(self, 'retried', None):
460 self.retried = 0
461 raise
462
David Pursehouse819827a2020-02-12 15:20:19 +0900463
Carlos Aguado1242e602014-02-03 13:48:47 +0100464class _KerberosAuthHandler(urllib.request.BaseHandler):
465 def __init__(self):
466 self.retried = 0
467 self.context = None
468 self.handler_order = urllib.request.BaseHandler.handler_order - 50
469
David Pursehouse65b0ba52018-06-24 16:21:51 +0900470 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100471 host = req.get_host()
472 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
473 return retry
474
475 def http_error_auth_reqed(self, auth_header, host, req, headers):
476 try:
477 spn = "HTTP@%s" % host
478 authdata = self._negotiate_get_authdata(auth_header, headers)
479
480 if self.retried > 3:
481 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900482 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100483 else:
484 self.retried += 1
485
486 neghdr = self._negotiate_get_svctk(spn, authdata)
487 if neghdr is None:
488 return None
489
490 req.add_unredirected_header('Authorization', neghdr)
491 response = self.parent.open(req)
492
493 srvauth = self._negotiate_get_authdata(auth_header, response.info())
494 if self._validate_response(srvauth):
495 return response
496 except kerberos.GSSError:
497 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900498 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100499 self.reset_retry_count()
500 raise
501 finally:
502 self._clean_context()
503
504 def reset_retry_count(self):
505 self.retried = 0
506
507 def _negotiate_get_authdata(self, auth_header, headers):
508 authhdr = headers.get(auth_header, None)
509 if authhdr is not None:
510 for mech_tuple in authhdr.split(","):
511 mech, __, authdata = mech_tuple.strip().partition(" ")
512 if mech.lower() == "negotiate":
513 return authdata.strip()
514 return None
515
516 def _negotiate_get_svctk(self, spn, authdata):
517 if authdata is None:
518 return None
519
520 result, self.context = kerberos.authGSSClientInit(spn)
521 if result < kerberos.AUTH_GSS_COMPLETE:
522 return None
523
524 result = kerberos.authGSSClientStep(self.context, authdata)
525 if result < kerberos.AUTH_GSS_CONTINUE:
526 return None
527
528 response = kerberos.authGSSClientResponse(self.context)
529 return "Negotiate %s" % response
530
531 def _validate_response(self, authdata):
532 if authdata is None:
533 return None
534 result = kerberos.authGSSClientStep(self.context, authdata)
535 if result == kerberos.AUTH_GSS_COMPLETE:
536 return True
537 return None
538
539 def _clean_context(self):
540 if self.context is not None:
541 kerberos.authGSSClientClean(self.context)
542 self.context = None
543
David Pursehouse819827a2020-02-12 15:20:19 +0900544
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700545def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700546 handlers = [_UserAgentHandler()]
547
Sarah Owens1f7627f2012-10-31 09:21:55 -0700548 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700549 try:
550 n = netrc.netrc()
551 for host in n.hosts:
552 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900553 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800554 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700555 except netrc.NetrcParseError:
556 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700557 except IOError:
558 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700559 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800560 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100561 if kerberos:
562 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700563
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700564 if 'http_proxy' in os.environ:
565 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700566 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700567 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700568 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
569 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
570 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700571
David Pursehouse819827a2020-02-12 15:20:19 +0900572
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700573def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400574 result = 0
575
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700576 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
577 opt.add_option("--repo-dir", dest="repodir",
578 help="path to .repo/")
579 opt.add_option("--wrapper-version", dest="wrapper_version",
580 help="version of the wrapper script")
581 opt.add_option("--wrapper-path", dest="wrapper_path",
582 help="location of the wrapper script")
583 _PruneOptions(argv, opt)
584 opt, argv = opt.parse_args(argv)
585
586 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
587 _CheckRepoDir(opt.repodir)
588
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800589 Version.wrapper_version = opt.wrapper_version
590 Version.wrapper_path = opt.wrapper_path
591
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700592 repo = _Repo(opt.repodir)
593 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700594 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800595 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700596 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400597 name, gopts, argv = repo._ParseArgs(argv)
598 run = lambda: repo._Run(name, gopts, argv) or 0
599 if gopts.trace_python:
600 import trace
601 tracer = trace.Trace(count=False, trace=True, timing=True,
602 ignoredirs=set(sys.path[1:]))
603 result = tracer.runfunc(run)
604 else:
605 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700606 finally:
607 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700608 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700609 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400610 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900611 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700612 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900613 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700614 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800615 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700616 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800617 argv = list(sys.argv)
618 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700619 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400620 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700621 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700622 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
623 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400624 result = 128
625
Renaud Paquaye8595e92016-11-01 15:51:59 -0700626 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400627 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700628
David Pursehouse819827a2020-02-12 15:20:19 +0900629
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630if __name__ == '__main__':
631 _Main(sys.argv[1:])