blob: cd62793d8391a52c4b034c1a28d8f5ecc55d713a [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
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:
Mike Frysingera488af52020-09-06 13:33:45 -040088 print('repo: error: Python 2 is no longer supported; '
Mike Frysinger37f28f12020-02-16 15:15:53 -050089 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
90 file=sys.stderr)
Mike Frysingera488af52020-09-06 13:33:45 -040091 sys.exit(1)
Mike Frysinger37f28f12020-02-16 15:15:53 -050092else:
93 if sys.version_info < MIN_PYTHON_VERSION_HARD:
94 print('repo: error: Python 3 version is too old; '
95 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
96 file=sys.stderr)
97 sys.exit(1)
98 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
99 print('repo: warning: your Python 3 version is no longer supported; '
100 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
101 file=sys.stderr)
102
103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -0500105 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
106 add_help_option=False)
107global_options.add_option('-h', '--help', action='store_true',
108 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109global_options.add_option('-p', '--paginate',
110 dest='pager', action='store_true',
111 help='display command output in the pager')
112global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500113 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500115global_options.add_option('--color',
116 choices=('auto', 'always', 'never'), default=None,
117 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700118global_options.add_option('--trace',
119 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400120 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400121global_options.add_option('--trace-python',
122 dest='trace_python', action='store_true',
123 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700124global_options.add_option('--time',
125 dest='time', action='store_true',
126 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800127global_options.add_option('--version',
128 dest='show_version', action='store_true',
129 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700130global_options.add_option('--event-log',
131 dest='event_log', action='store',
132 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133
David Pursehouse819827a2020-02-12 15:20:19 +0900134
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135class _Repo(object):
136 def __init__(self, repodir):
137 self.repodir = repodir
138 self.commands = all_commands
139
Mike Frysinger3fc15722019-08-27 00:36:46 -0400140 def _ParseArgs(self, argv):
141 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700142 name = None
143 glob = []
144
Sarah Owensa6053d52012-11-01 13:36:50 -0700145 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146 if not argv[i].startswith('-'):
147 name = argv[i]
148 if i > 0:
149 glob = argv[:i]
150 argv = argv[i + 1:]
151 break
152 if not name:
153 glob = argv
154 name = 'help'
155 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900156 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
Mike Frysinger949bc342020-02-18 21:37:00 -0500158 name, alias_args = self._ExpandAlias(name)
159 argv = alias_args + argv
160
Mike Frysinger7c321f12019-12-02 16:49:44 -0500161 if gopts.help:
162 global_options.print_help()
163 commands = ' '.join(sorted(self.commands))
164 wrapped_commands = textwrap.wrap(commands, width=77)
165 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
166 print('\nRun `repo help ` for command-specific details.')
167 global_options.exit()
168
Mike Frysinger3fc15722019-08-27 00:36:46 -0400169 return (name, gopts, argv)
170
Mike Frysinger949bc342020-02-18 21:37:00 -0500171 def _ExpandAlias(self, name):
172 """Look up user registered aliases."""
173 # We don't resolve aliases for existing subcommands. This matches git.
174 if name in self.commands:
175 return name, []
176
177 key = 'alias.%s' % (name,)
178 alias = RepoConfig.ForRepository(self.repodir).GetString(key)
179 if alias is None:
180 alias = RepoConfig.ForUser().GetString(key)
181 if alias is None:
182 return name, []
183
184 args = alias.strip().split(' ', 1)
185 name = args[0]
186 if len(args) == 2:
187 args = shlex.split(args[1])
188 else:
189 args = []
190 return name, args
191
Mike Frysinger3fc15722019-08-27 00:36:46 -0400192 def _Run(self, name, gopts, argv):
193 """Execute the requested subcommand."""
194 result = 0
195
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700196 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700197 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800198 if gopts.show_version:
199 if name == 'help':
200 name = 'version'
201 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700202 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400203 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800204
Mike Frysinger902665b2014-12-22 15:17:59 -0500205 SetDefaultColoring(gopts.color)
206
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207 try:
Mike Frysingerbb930462020-02-25 15:18:31 -0500208 cmd = self.commands[name]()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700209 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700210 print("repo: '%s' is not a repo command. See 'repo help'." % name,
211 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400212 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700213
214 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700215 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700216 cmd.gitc_manifest = None
217 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
218 if gitc_client_name:
219 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
220 cmd.manifest.isGitcClient = True
221
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700222 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700223
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800224 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700225 print("fatal: '%s' requires a working directory" % name,
226 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400227 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800228
Dan Willemsen79360642015-08-31 15:45:06 -0700229 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700230 print("fatal: '%s' requires GITC to be available" % name,
231 file=sys.stderr)
232 return 1
233
Dan Willemsen79360642015-08-31 15:45:06 -0700234 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
235 print("fatal: '%s' requires a GITC client" % name,
236 file=sys.stderr)
237 return 1
238
Dan Sandler53e902a2014-03-09 13:20:02 -0400239 try:
240 copts, cargs = cmd.OptionParser.parse_args(argv)
241 copts = cmd.ReadEnvironmentOptions(copts)
242 except NoManifestException as e:
243 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900244 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400245 print('error: manifest missing or unreadable -- please run init',
246 file=sys.stderr)
247 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700248
Mike Frysinger8a98efe2020-02-19 01:17:56 -0500249 if gopts.pager is not False and not isinstance(cmd, InteractiveCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700250 config = cmd.manifest.globalConfig
251 if gopts.pager:
252 use_pager = True
253 else:
254 use_pager = config.GetBoolean('pager.%s' % name)
255 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700256 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257 if use_pager:
258 RunPager(config)
259
Conley Owens7ba25be2012-11-14 14:18:06 -0800260 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700261 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
262 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400264 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800265 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400266 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900267 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400268 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900269 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400270 if isinstance(e, NoManifestException):
271 print('error: manifest missing or unreadable -- please run init',
272 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800273 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700274 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700275 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700276 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700277 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700278 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800279 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700280 except InvalidProjectGroupsError as e:
281 if e.name:
282 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
283 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900284 print('error: project group must be enabled for the project in the current directory',
285 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700286 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700287 except SystemExit as e:
288 if e.code:
289 result = e.code
290 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800291 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700292 finish = time.time()
293 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800294 hours, remainder = divmod(elapsed, 3600)
295 minutes, seconds = divmod(remainder, 60)
296 if gopts.time:
297 if hours == 0:
298 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
299 else:
300 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
301 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400302
David Rileye0684ad2017-04-05 00:02:59 -0700303 cmd.event_log.FinishEvent(cmd_event, finish,
304 result is None or result == 0)
305 if gopts.event_log:
306 cmd.event_log.Write(os.path.abspath(
307 os.path.expanduser(gopts.event_log)))
308
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400309 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700310
Conley Owens094cdbe2014-01-30 15:09:59 -0800311
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500312def _CheckWrapperVersion(ver_str, repo_path):
313 """Verify the repo launcher is new enough for this checkout.
314
315 Args:
316 ver_str: The version string passed from the repo launcher when it ran us.
317 repo_path: The path to the repo launcher that loaded us.
318 """
319 # Refuse to work with really old wrapper versions. We don't test these,
320 # so might as well require a somewhat recent sane version.
321 # v1.15 of the repo launcher was released in ~Mar 2012.
322 MIN_REPO_VERSION = (1, 15)
323 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
324
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700325 if not repo_path:
326 repo_path = '~/bin/repo'
327
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500328 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700329 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900330 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700331
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500332 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800333 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500334 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700335
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900336 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500337 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700338 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500339repo: error:
340!!! Your version of repo %s is too old.
341!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900342!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500343!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344
345 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500346""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347 sys.exit(1)
348
349 if exp > ver:
Mike Frysingereea23b42020-02-26 16:21:08 -0500350 print('\n... A new version of repo (%s) is available.' % (exp_str,),
351 file=sys.stderr)
352 if os.access(repo_path, os.W_OK):
353 print("""\
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700354... You should upgrade soon:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700355 cp %s %s
Mike Frysingereea23b42020-02-26 16:21:08 -0500356""" % (WrapperPath(), repo_path), file=sys.stderr)
357 else:
358 print("""\
359... New version is available at: %s
360... The launcher is run from: %s
361!!! The launcher is not writable. Please talk to your sysadmin or distro
362!!! to get an update installed.
363""" % (WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364
David Pursehouse819827a2020-02-12 15:20:19 +0900365
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200366def _CheckRepoDir(repo_dir):
367 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700368 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900369 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700370
David Pursehouse819827a2020-02-12 15:20:19 +0900371
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372def _PruneOptions(argv, opt):
373 i = 0
374 while i < len(argv):
375 a = argv[i]
376 if a == '--':
377 break
378 if a.startswith('--'):
379 eq = a.find('=')
380 if eq > 0:
381 a = a[0:eq]
382 if not opt.has_option(a):
383 del argv[i]
384 continue
385 i += 1
386
David Pursehouse819827a2020-02-12 15:20:19 +0900387
Sarah Owens1f7627f2012-10-31 09:21:55 -0700388class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700389 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400390 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700391 return req
392
393 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400394 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700395 return req
396
David Pursehouse819827a2020-02-12 15:20:19 +0900397
JoonCheol Parke9860722012-10-11 02:31:44 +0900398def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900399 # If repo could not find auth info from netrc, try to get it from user input
400 url = req.get_full_url()
401 user, password = handler.passwd.find_user_password(None, url)
402 if user is None:
403 print(msg)
404 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530405 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900406 password = getpass.getpass()
407 except KeyboardInterrupt:
408 return
409 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900410
David Pursehouse819827a2020-02-12 15:20:19 +0900411
Sarah Owens1f7627f2012-10-31 09:21:55 -0700412class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900413 def http_error_401(self, req, fp, code, msg, headers):
414 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700415 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900416 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900417
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700418 def http_error_auth_reqed(self, authreq, host, req, headers):
419 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700420 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900421
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700422 def _add_header(name, val):
423 val = val.replace('\n', '')
424 old_add_header(name, val)
425 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700426 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900427 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900428 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700429 reset = getattr(self, 'reset_retry_count', None)
430 if reset is not None:
431 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700432 elif getattr(self, 'retried', None):
433 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700434 raise
435
David Pursehouse819827a2020-02-12 15:20:19 +0900436
Sarah Owens1f7627f2012-10-31 09:21:55 -0700437class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900438 def http_error_401(self, req, fp, code, msg, headers):
439 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700440 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900441 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900442
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800443 def http_error_auth_reqed(self, auth_header, host, req, headers):
444 try:
445 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900446
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800447 def _add_header(name, val):
448 val = val.replace('\n', '')
449 old_add_header(name, val)
450 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700451 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900452 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900453 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800454 reset = getattr(self, 'reset_retry_count', None)
455 if reset is not None:
456 reset()
457 elif getattr(self, 'retried', None):
458 self.retried = 0
459 raise
460
David Pursehouse819827a2020-02-12 15:20:19 +0900461
Carlos Aguado1242e602014-02-03 13:48:47 +0100462class _KerberosAuthHandler(urllib.request.BaseHandler):
463 def __init__(self):
464 self.retried = 0
465 self.context = None
466 self.handler_order = urllib.request.BaseHandler.handler_order - 50
467
David Pursehouse65b0ba52018-06-24 16:21:51 +0900468 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100469 host = req.get_host()
470 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
471 return retry
472
473 def http_error_auth_reqed(self, auth_header, host, req, headers):
474 try:
475 spn = "HTTP@%s" % host
476 authdata = self._negotiate_get_authdata(auth_header, headers)
477
478 if self.retried > 3:
479 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900480 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100481 else:
482 self.retried += 1
483
484 neghdr = self._negotiate_get_svctk(spn, authdata)
485 if neghdr is None:
486 return None
487
488 req.add_unredirected_header('Authorization', neghdr)
489 response = self.parent.open(req)
490
491 srvauth = self._negotiate_get_authdata(auth_header, response.info())
492 if self._validate_response(srvauth):
493 return response
494 except kerberos.GSSError:
495 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900496 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100497 self.reset_retry_count()
498 raise
499 finally:
500 self._clean_context()
501
502 def reset_retry_count(self):
503 self.retried = 0
504
505 def _negotiate_get_authdata(self, auth_header, headers):
506 authhdr = headers.get(auth_header, None)
507 if authhdr is not None:
508 for mech_tuple in authhdr.split(","):
509 mech, __, authdata = mech_tuple.strip().partition(" ")
510 if mech.lower() == "negotiate":
511 return authdata.strip()
512 return None
513
514 def _negotiate_get_svctk(self, spn, authdata):
515 if authdata is None:
516 return None
517
518 result, self.context = kerberos.authGSSClientInit(spn)
519 if result < kerberos.AUTH_GSS_COMPLETE:
520 return None
521
522 result = kerberos.authGSSClientStep(self.context, authdata)
523 if result < kerberos.AUTH_GSS_CONTINUE:
524 return None
525
526 response = kerberos.authGSSClientResponse(self.context)
527 return "Negotiate %s" % response
528
529 def _validate_response(self, authdata):
530 if authdata is None:
531 return None
532 result = kerberos.authGSSClientStep(self.context, authdata)
533 if result == kerberos.AUTH_GSS_COMPLETE:
534 return True
535 return None
536
537 def _clean_context(self):
538 if self.context is not None:
539 kerberos.authGSSClientClean(self.context)
540 self.context = None
541
David Pursehouse819827a2020-02-12 15:20:19 +0900542
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700543def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700544 handlers = [_UserAgentHandler()]
545
Sarah Owens1f7627f2012-10-31 09:21:55 -0700546 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700547 try:
548 n = netrc.netrc()
549 for host in n.hosts:
550 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900551 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800552 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700553 except netrc.NetrcParseError:
554 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700555 except IOError:
556 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700557 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800558 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100559 if kerberos:
560 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700561
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700562 if 'http_proxy' in os.environ:
563 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700564 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700565 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700566 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
567 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
568 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700569
David Pursehouse819827a2020-02-12 15:20:19 +0900570
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700571def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400572 result = 0
573
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
575 opt.add_option("--repo-dir", dest="repodir",
576 help="path to .repo/")
577 opt.add_option("--wrapper-version", dest="wrapper_version",
578 help="version of the wrapper script")
579 opt.add_option("--wrapper-path", dest="wrapper_path",
580 help="location of the wrapper script")
581 _PruneOptions(argv, opt)
582 opt, argv = opt.parse_args(argv)
583
584 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
585 _CheckRepoDir(opt.repodir)
586
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800587 Version.wrapper_version = opt.wrapper_version
588 Version.wrapper_path = opt.wrapper_path
589
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700590 repo = _Repo(opt.repodir)
591 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700592 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800593 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700594 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400595 name, gopts, argv = repo._ParseArgs(argv)
596 run = lambda: repo._Run(name, gopts, argv) or 0
597 if gopts.trace_python:
598 import trace
599 tracer = trace.Trace(count=False, trace=True, timing=True,
600 ignoredirs=set(sys.path[1:]))
601 result = tracer.runfunc(run)
602 else:
603 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700604 finally:
605 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700606 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700607 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400608 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900609 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700610 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900611 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700612 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800613 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700614 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800615 argv = list(sys.argv)
616 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700617 try:
Mike Frysingerdd37fb22020-04-16 12:38:04 -0400618 os.execv(sys.executable, [__file__] + argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700619 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700620 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
621 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400622 result = 128
623
Renaud Paquaye8595e92016-11-01 15:51:59 -0700624 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400625 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700626
David Pursehouse819827a2020-02-12 15:20:19 +0900627
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700628if __name__ == '__main__':
629 _Main(sys.argv[1:])