blob: 1d73fce33ebb69ca5213ad7961735c4f12ce22f0 [file] [log] [blame]
David Pursehouse8898e2f2012-11-14 07:51:03 +09001#!/usr/bin/env python
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
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080053from command import InteractiveCommand
54from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070055from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080056from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070057from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070058from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070059from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080060from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090061from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080062from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063from error import NoSuchProjectError
64from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070065import gitc_utils
66from manifest_xml import GitcManifest, XmlManifest
Renaud Paquaye8595e92016-11-01 15:51:59 -070067from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080068from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070069
David Pursehouse5c6eeac2012-10-11 16:44:48 +090070from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070071
David Pursehouse59bbb582013-05-17 10:49:33 +090072if not is_python3():
David Pursehousea46bf7d2020-02-15 12:45:53 +090073 input = raw_input # noqa: F821
Chirayu Desai217ea7d2013-03-01 19:14:38 +053074
Mike Frysinger37f28f12020-02-16 15:15:53 -050075# NB: These do not need to be kept in sync with the repo launcher script.
76# These may be much newer as it allows the repo launcher to roll between
77# different repo releases while source versions might require a newer python.
78#
79# The soft version is when we start warning users that the version is old and
80# we'll be dropping support for it. We'll refuse to work with versions older
81# than the hard version.
82#
83# python-3.6 is in Ubuntu Bionic.
84MIN_PYTHON_VERSION_SOFT = (3, 6)
85MIN_PYTHON_VERSION_HARD = (3, 4)
86
87if sys.version_info.major < 3:
88 print('repo: warning: Python 2 is no longer supported; '
89 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
90 file=sys.stderr)
91else:
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')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700132
David Pursehouse819827a2020-02-12 15:20:19 +0900133
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134class _Repo(object):
135 def __init__(self, repodir):
136 self.repodir = repodir
137 self.commands = all_commands
138
Mike Frysinger3fc15722019-08-27 00:36:46 -0400139 def _ParseArgs(self, argv):
140 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700141 name = None
142 glob = []
143
Sarah Owensa6053d52012-11-01 13:36:50 -0700144 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700145 if not argv[i].startswith('-'):
146 name = argv[i]
147 if i > 0:
148 glob = argv[:i]
149 argv = argv[i + 1:]
150 break
151 if not name:
152 glob = argv
153 name = 'help'
154 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900155 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700156
Mike Frysinger949bc342020-02-18 21:37:00 -0500157 name, alias_args = self._ExpandAlias(name)
158 argv = alias_args + argv
159
Mike Frysinger7c321f12019-12-02 16:49:44 -0500160 if gopts.help:
161 global_options.print_help()
162 commands = ' '.join(sorted(self.commands))
163 wrapped_commands = textwrap.wrap(commands, width=77)
164 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
165 print('\nRun `repo help ` for command-specific details.')
166 global_options.exit()
167
Mike Frysinger3fc15722019-08-27 00:36:46 -0400168 return (name, gopts, argv)
169
Mike Frysinger949bc342020-02-18 21:37:00 -0500170 def _ExpandAlias(self, name):
171 """Look up user registered aliases."""
172 # We don't resolve aliases for existing subcommands. This matches git.
173 if name in self.commands:
174 return name, []
175
176 key = 'alias.%s' % (name,)
177 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
178 if alias is None:
179 alias = RepoConfig.ForUser().GetString(key)
180 if alias is None:
181 return name, []
182
183 args = alias.strip().split(' ', 1)
184 name = args[0]
185 if len(args) == 2:
186 args = shlex.split(args[1])
187 else:
188 args = []
189 return name, args
190
Mike Frysinger3fc15722019-08-27 00:36:46 -0400191 def _Run(self, name, gopts, argv):
192 """Execute the requested subcommand."""
193 result = 0
194
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700195 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700196 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800197 if gopts.show_version:
198 if name == 'help':
199 name = 'version'
200 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700201 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400202 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800203
Mike Frysinger902665b2014-12-22 15:17:59 -0500204 SetDefaultColoring(gopts.color)
205
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500207 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700208 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700209 print("repo: '%s' is not a repo command. See 'repo help'." % name,
210 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400211 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700212
213 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700214 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700215 cmd.gitc_manifest = None
216 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
217 if gitc_client_name:
218 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
219 cmd.manifest.isGitcClient = True
220
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700221 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800223 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700224 print("fatal: '%s' requires a working directory" % name,
225 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400226 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800227
Dan Willemsen79360642015-08-31 15:45:06 -0700228 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700229 print("fatal: '%s' requires GITC to be available" % name,
230 file=sys.stderr)
231 return 1
232
Dan Willemsen79360642015-08-31 15:45:06 -0700233 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
234 print("fatal: '%s' requires a GITC client" % name,
235 file=sys.stderr)
236 return 1
237
Dan Sandler53e902a2014-03-09 13:20:02 -0400238 try:
239 copts, cargs = cmd.OptionParser.parse_args(argv)
240 copts = cmd.ReadEnvironmentOptions(copts)
241 except NoManifestException as e:
242 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900243 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400244 print('error: manifest missing or unreadable -- please run init',
245 file=sys.stderr)
246 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700247
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500248 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249 config = cmd.manifest.globalConfig
250 if gopts.pager:
251 use_pager = True
252 else:
253 use_pager = config.GetBoolean('pager.%s' % name)
254 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700255 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 if use_pager:
257 RunPager(config)
258
Conley Owens7ba25be2012-11-14 14:18:06 -0800259 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700260 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
261 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700262 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400263 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800264 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400265 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900266 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400267 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900268 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400269 if isinstance(e, NoManifestException):
270 print('error: manifest missing or unreadable -- please run init',
271 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800272 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700273 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700275 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700276 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700277 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800278 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700279 except InvalidProjectGroupsError as e:
280 if e.name:
281 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
282 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900283 print('error: project group must be enabled for the project in the current directory',
284 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700285 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700286 except SystemExit as e:
287 if e.code:
288 result = e.code
289 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800290 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700291 finish = time.time()
292 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800293 hours, remainder = divmod(elapsed, 3600)
294 minutes, seconds = divmod(remainder, 60)
295 if gopts.time:
296 if hours == 0:
297 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
298 else:
299 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
300 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400301
David Rileye0684ad2017-04-05 00:02:59 -0700302 cmd.event_log.FinishEvent(cmd_event, finish,
303 result is None or result == 0)
304 if gopts.event_log:
305 cmd.event_log.Write(os.path.abspath(
306 os.path.expanduser(gopts.event_log)))
307
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400308 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309
Conley Owens094cdbe2014-01-30 15:09:59 -0800310
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500311def _CheckWrapperVersion(ver_str, repo_path):
312 """Verify the repo launcher is new enough for this checkout.
313
314 Args:
315 ver_str: The version string passed from the repo launcher when it ran us.
316 repo_path: The path to the repo launcher that loaded us.
317 """
318 # Refuse to work with really old wrapper versions. We don't test these,
319 # so might as well require a somewhat recent sane version.
320 # v1.15 of the repo launcher was released in ~Mar 2012.
321 MIN_REPO_VERSION = (1, 15)
322 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
323
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700324 if not repo_path:
325 repo_path = '~/bin/repo'
326
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500327 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700328 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900329 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700330
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500331 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800332 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500333 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700334
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900335 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500336 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700337 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500338repo: error:
339!!! Your version of repo %s is too old.
340!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900341!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500342!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700343
344 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500345""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700346 sys.exit(1)
347
348 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500349 print('\n... A new version of repo (%s) is available.' % (exp_str,),
350 file=sys.stderr)
351 if os.access(repo_path, os.W_OK):
352 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700353... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700354 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500355""" % (WrapperPath(), repo_path), file=sys.stderr)
356 else:
357 print("""\
358... New version is available at: %s
359... The launcher is run from: %s
360!!! The launcher is not writable. Please talk to your sysadmin or distro
361!!! to get an update installed.
362""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363
David Pursehouse819827a2020-02-12 15:20:19 +0900364
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200365def _CheckRepoDir(repo_dir):
366 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700367 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900368 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700369
David Pursehouse819827a2020-02-12 15:20:19 +0900370
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700371def _PruneOptions(argv, opt):
372 i = 0
373 while i < len(argv):
374 a = argv[i]
375 if a == '--':
376 break
377 if a.startswith('--'):
378 eq = a.find('=')
379 if eq > 0:
380 a = a[0:eq]
381 if not opt.has_option(a):
382 del argv[i]
383 continue
384 i += 1
385
David Pursehouse819827a2020-02-12 15:20:19 +0900386
Sarah Owens1f7627f2012-10-31 09:21:55 -0700387class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700388 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400389 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700390 return req
391
392 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400393 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700394 return req
395
David Pursehouse819827a2020-02-12 15:20:19 +0900396
JoonCheol Parke9860722012-10-11 02:31:44 +0900397def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900398 # If repo could not find auth info from netrc, try to get it from user input
399 url = req.get_full_url()
400 user, password = handler.passwd.find_user_password(None, url)
401 if user is None:
402 print(msg)
403 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530404 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900405 password = getpass.getpass()
406 except KeyboardInterrupt:
407 return
408 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900409
David Pursehouse819827a2020-02-12 15:20:19 +0900410
Sarah Owens1f7627f2012-10-31 09:21:55 -0700411class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900412 def http_error_401(self, req, fp, code, msg, headers):
413 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700414 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900415 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900416
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700417 def http_error_auth_reqed(self, authreq, host, req, headers):
418 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700419 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900420
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700421 def _add_header(name, val):
422 val = val.replace('\n', '')
423 old_add_header(name, val)
424 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700425 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900426 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900427 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700428 reset = getattr(self, 'reset_retry_count', None)
429 if reset is not None:
430 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700431 elif getattr(self, 'retried', None):
432 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700433 raise
434
David Pursehouse819827a2020-02-12 15:20:19 +0900435
Sarah Owens1f7627f2012-10-31 09:21:55 -0700436class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900437 def http_error_401(self, req, fp, code, msg, headers):
438 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700439 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900440 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900441
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800442 def http_error_auth_reqed(self, auth_header, host, req, headers):
443 try:
444 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900445
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800446 def _add_header(name, val):
447 val = val.replace('\n', '')
448 old_add_header(name, val)
449 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700450 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900451 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900452 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800453 reset = getattr(self, 'reset_retry_count', None)
454 if reset is not None:
455 reset()
456 elif getattr(self, 'retried', None):
457 self.retried = 0
458 raise
459
David Pursehouse819827a2020-02-12 15:20:19 +0900460
Carlos Aguado1242e602014-02-03 13:48:47 +0100461class _KerberosAuthHandler(urllib.request.BaseHandler):
462 def __init__(self):
463 self.retried = 0
464 self.context = None
465 self.handler_order = urllib.request.BaseHandler.handler_order - 50
466
David Pursehouse65b0ba52018-06-24 16:21:51 +0900467 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100468 host = req.get_host()
469 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
470 return retry
471
472 def http_error_auth_reqed(self, auth_header, host, req, headers):
473 try:
474 spn = "HTTP@%s" % host
475 authdata = self._negotiate_get_authdata(auth_header, headers)
476
477 if self.retried > 3:
478 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900479 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100480 else:
481 self.retried += 1
482
483 neghdr = self._negotiate_get_svctk(spn, authdata)
484 if neghdr is None:
485 return None
486
487 req.add_unredirected_header('Authorization', neghdr)
488 response = self.parent.open(req)
489
490 srvauth = self._negotiate_get_authdata(auth_header, response.info())
491 if self._validate_response(srvauth):
492 return response
493 except kerberos.GSSError:
494 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900495 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100496 self.reset_retry_count()
497 raise
498 finally:
499 self._clean_context()
500
501 def reset_retry_count(self):
502 self.retried = 0
503
504 def _negotiate_get_authdata(self, auth_header, headers):
505 authhdr = headers.get(auth_header, None)
506 if authhdr is not None:
507 for mech_tuple in authhdr.split(","):
508 mech, __, authdata = mech_tuple.strip().partition(" ")
509 if mech.lower() == "negotiate":
510 return authdata.strip()
511 return None
512
513 def _negotiate_get_svctk(self, spn, authdata):
514 if authdata is None:
515 return None
516
517 result, self.context = kerberos.authGSSClientInit(spn)
518 if result < kerberos.AUTH_GSS_COMPLETE:
519 return None
520
521 result = kerberos.authGSSClientStep(self.context, authdata)
522 if result < kerberos.AUTH_GSS_CONTINUE:
523 return None
524
525 response = kerberos.authGSSClientResponse(self.context)
526 return "Negotiate %s" % response
527
528 def _validate_response(self, authdata):
529 if authdata is None:
530 return None
531 result = kerberos.authGSSClientStep(self.context, authdata)
532 if result == kerberos.AUTH_GSS_COMPLETE:
533 return True
534 return None
535
536 def _clean_context(self):
537 if self.context is not None:
538 kerberos.authGSSClientClean(self.context)
539 self.context = None
540
David Pursehouse819827a2020-02-12 15:20:19 +0900541
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700542def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700543 handlers = [_UserAgentHandler()]
544
Sarah Owens1f7627f2012-10-31 09:21:55 -0700545 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700546 try:
547 n = netrc.netrc()
548 for host in n.hosts:
549 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900550 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800551 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700552 except netrc.NetrcParseError:
553 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700554 except IOError:
555 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700556 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800557 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100558 if kerberos:
559 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700560
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700561 if 'http_proxy' in os.environ:
562 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700563 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700564 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700565 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
566 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
567 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700568
David Pursehouse819827a2020-02-12 15:20:19 +0900569
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700570def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400571 result = 0
572
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700573 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
574 opt.add_option("--repo-dir", dest="repodir",
575 help="path to .repo/")
576 opt.add_option("--wrapper-version", dest="wrapper_version",
577 help="version of the wrapper script")
578 opt.add_option("--wrapper-path", dest="wrapper_path",
579 help="location of the wrapper script")
580 _PruneOptions(argv, opt)
581 opt, argv = opt.parse_args(argv)
582
583 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
584 _CheckRepoDir(opt.repodir)
585
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800586 Version.wrapper_version = opt.wrapper_version
587 Version.wrapper_path = opt.wrapper_path
588
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700589 repo = _Repo(opt.repodir)
590 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700591 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800592 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700593 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400594 name, gopts, argv = repo._ParseArgs(argv)
595 run = lambda: repo._Run(name, gopts, argv) or 0
596 if gopts.trace_python:
597 import trace
598 tracer = trace.Trace(count=False, trace=True, timing=True,
599 ignoredirs=set(sys.path[1:]))
600 result = tracer.runfunc(run)
601 else:
602 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700603 finally:
604 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700605 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700606 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400607 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900608 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700609 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900610 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700611 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800612 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700613 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800614 argv = list(sys.argv)
615 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700616 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400617 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700618 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700619 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
620 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400621 result = 128
622
Renaud Paquaye8595e92016-11-01 15:51:59 -0700623 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400624 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625
David Pursehouse819827a2020-02-12 15:20:19 +0900626
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700627if __name__ == '__main__':
628 _Main(sys.argv[1:])