blob: 531400c5338186abb56d545c72b65b28b6770d55 [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
Sarah Owenscecd1d82012-11-01 22:59:27 -070018from __future__ import print_function
JoonCheol Parke9860722012-10-11 02:31:44 +090019import getpass
Conley Owensc9129d92012-10-01 16:12:28 -070020import imp
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070021import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022import optparse
23import os
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024import sys
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070025import time
David Pursehouse59bbb582013-05-17 10:49:33 +090026
27from pyversion import is_python3
28if is_python3():
Sarah Owens1f7627f2012-10-31 09:21:55 -070029 import urllib.request
30else:
David Pursehouse59bbb582013-05-17 10:49:33 +090031 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -070032 urllib = imp.new_module('urllib')
33 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
Carlos Aguado1242e602014-02-03 13:48:47 +010035try:
36 import kerberos
37except ImportError:
38 kerberos = None
39
Mike Frysinger902665b2014-12-22 15:17:59 -050040from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070041import event_log
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070042from trace import SetTrace
Shawn O. Pearce334851e2011-09-19 08:05:31 -070043from git_command import git, GitCommand
Doug Anderson0048b692010-12-21 13:39:23 -080044from git_config import init_ssh, close_ssh
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080045from command import InteractiveCommand
46from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070047from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080048from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070049from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070050from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070051from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080052from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090053from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080054from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070055from error import NoSuchProjectError
56from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070057import gitc_utils
58from manifest_xml import GitcManifest, XmlManifest
Renaud Paquaye8595e92016-11-01 15:51:59 -070059from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080060from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061
David Pursehouse5c6eeac2012-10-11 16:44:48 +090062from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063
David Pursehouse59bbb582013-05-17 10:49:33 +090064if not is_python3():
Chirayu Desai217ea7d2013-03-01 19:14:38 +053065 input = raw_input
Chirayu Desai217ea7d2013-03-01 19:14:38 +053066
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070067global_options = optparse.OptionParser(
68 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
69 )
70global_options.add_option('-p', '--paginate',
71 dest='pager', action='store_true',
72 help='display command output in the pager')
73global_options.add_option('--no-pager',
74 dest='no_pager', action='store_true',
75 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -050076global_options.add_option('--color',
77 choices=('auto', 'always', 'never'), default=None,
78 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070079global_options.add_option('--trace',
80 dest='trace', action='store_true',
81 help='trace git command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070082global_options.add_option('--time',
83 dest='time', action='store_true',
84 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080085global_options.add_option('--version',
86 dest='show_version', action='store_true',
87 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -070088global_options.add_option('--event-log',
89 dest='event_log', action='store',
90 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070091
92class _Repo(object):
93 def __init__(self, repodir):
94 self.repodir = repodir
95 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -040096 # add 'branch' as an alias for 'branches'
97 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070098
99 def _Run(self, argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400100 result = 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700101 name = None
102 glob = []
103
Sarah Owensa6053d52012-11-01 13:36:50 -0700104 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105 if not argv[i].startswith('-'):
106 name = argv[i]
107 if i > 0:
108 glob = argv[:i]
109 argv = argv[i + 1:]
110 break
111 if not name:
112 glob = argv
113 name = 'help'
114 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900115 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700117 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700118 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800119 if gopts.show_version:
120 if name == 'help':
121 name = 'version'
122 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700123 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400124 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800125
Mike Frysinger902665b2014-12-22 15:17:59 -0500126 SetDefaultColoring(gopts.color)
127
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128 try:
129 cmd = self.commands[name]
130 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700131 print("repo: '%s' is not a repo command. See 'repo help'." % name,
132 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400133 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134
135 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700136 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700137 cmd.gitc_manifest = None
138 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
139 if gitc_client_name:
140 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
141 cmd.manifest.isGitcClient = True
142
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700143 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700144
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800145 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700146 print("fatal: '%s' requires a working directory" % name,
147 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400148 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800149
Dan Willemsen79360642015-08-31 15:45:06 -0700150 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700151 print("fatal: '%s' requires GITC to be available" % name,
152 file=sys.stderr)
153 return 1
154
Dan Willemsen79360642015-08-31 15:45:06 -0700155 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
156 print("fatal: '%s' requires a GITC client" % name,
157 file=sys.stderr)
158 return 1
159
Dan Sandler53e902a2014-03-09 13:20:02 -0400160 try:
161 copts, cargs = cmd.OptionParser.parse_args(argv)
162 copts = cmd.ReadEnvironmentOptions(copts)
163 except NoManifestException as e:
164 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
165 file=sys.stderr)
166 print('error: manifest missing or unreadable -- please run init',
167 file=sys.stderr)
168 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700169
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700170 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
171 config = cmd.manifest.globalConfig
172 if gopts.pager:
173 use_pager = True
174 else:
175 use_pager = config.GetBoolean('pager.%s' % name)
176 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700177 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700178 if use_pager:
179 RunPager(config)
180
Conley Owens7ba25be2012-11-14 14:18:06 -0800181 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700182 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
183 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700184 try:
Conley Owens7ba25be2012-11-14 14:18:06 -0800185 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400186 except (DownloadError, ManifestInvalidRevisionError,
187 NoManifestException) as e:
188 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
189 file=sys.stderr)
190 if isinstance(e, NoManifestException):
191 print('error: manifest missing or unreadable -- please run init',
192 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800193 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700194 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700195 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700196 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700198 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800199 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700200 except InvalidProjectGroupsError as e:
201 if e.name:
202 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
203 else:
204 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
205 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700206 except SystemExit as e:
207 if e.code:
208 result = e.code
209 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800210 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700211 finish = time.time()
212 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800213 hours, remainder = divmod(elapsed, 3600)
214 minutes, seconds = divmod(remainder, 60)
215 if gopts.time:
216 if hours == 0:
217 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
218 else:
219 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
220 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400221
David Rileye0684ad2017-04-05 00:02:59 -0700222 cmd.event_log.FinishEvent(cmd_event, finish,
223 result is None or result == 0)
224 if gopts.event_log:
225 cmd.event_log.Write(os.path.abspath(
226 os.path.expanduser(gopts.event_log)))
227
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400228 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700229
Conley Owens094cdbe2014-01-30 15:09:59 -0800230
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700231def _MyRepoPath():
232 return os.path.dirname(__file__)
233
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234
235def _CheckWrapperVersion(ver, repo_path):
236 if not repo_path:
237 repo_path = '~/bin/repo'
238
239 if not ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700240 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900241 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700242
Conley Owens094cdbe2014-01-30 15:09:59 -0800243 exp = Wrapper().VERSION
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900244 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700245 if len(ver) == 1:
246 ver = (0, ver[0])
247
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900248 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249 if exp[0] > ver[0] or ver < (0, 4):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700250 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251!!! A new repo command (%5s) is available. !!!
252!!! You must upgrade before you can continue: !!!
253
254 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800255""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 sys.exit(1)
257
258 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700259 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700260... A new repo command (%5s) is available.
261... You should upgrade soon:
262
263 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800264""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200266def _CheckRepoDir(repo_dir):
267 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700268 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900269 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270
271def _PruneOptions(argv, opt):
272 i = 0
273 while i < len(argv):
274 a = argv[i]
275 if a == '--':
276 break
277 if a.startswith('--'):
278 eq = a.find('=')
279 if eq > 0:
280 a = a[0:eq]
281 if not opt.has_option(a):
282 del argv[i]
283 continue
284 i += 1
285
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700286_user_agent = None
287
288def _UserAgent():
289 global _user_agent
290
291 if _user_agent is None:
292 py_version = sys.version_info
293
294 os_name = sys.platform
295 if os_name == 'linux2':
296 os_name = 'Linux'
297 elif os_name == 'win32':
298 os_name = 'Win32'
299 elif os_name == 'cygwin':
300 os_name = 'Cygwin'
301 elif os_name == 'darwin':
302 os_name = 'Darwin'
303
304 p = GitCommand(
305 None, ['describe', 'HEAD'],
306 cwd = _MyRepoPath(),
307 capture_stdout = True)
308 if p.Wait() == 0:
309 repo_version = p.stdout
310 if len(repo_version) > 0 and repo_version[-1] == '\n':
311 repo_version = repo_version[0:-1]
312 if len(repo_version) > 0 and repo_version[0] == 'v':
313 repo_version = repo_version[1:]
314 else:
315 repo_version = 'unknown'
316
317 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
318 repo_version,
319 os_name,
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900320 '.'.join(map(str, git.version_tuple())),
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700321 py_version[0], py_version[1], py_version[2])
322 return _user_agent
323
Sarah Owens1f7627f2012-10-31 09:21:55 -0700324class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700325 def http_request(self, req):
326 req.add_header('User-Agent', _UserAgent())
327 return req
328
329 def https_request(self, req):
330 req.add_header('User-Agent', _UserAgent())
331 return req
332
JoonCheol Parke9860722012-10-11 02:31:44 +0900333def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900334 # If repo could not find auth info from netrc, try to get it from user input
335 url = req.get_full_url()
336 user, password = handler.passwd.find_user_password(None, url)
337 if user is None:
338 print(msg)
339 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530340 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900341 password = getpass.getpass()
342 except KeyboardInterrupt:
343 return
344 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900345
Sarah Owens1f7627f2012-10-31 09:21:55 -0700346class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900347 def http_error_401(self, req, fp, code, msg, headers):
348 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700349 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900350 self, req, fp, code, msg, headers)
351
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700352 def http_error_auth_reqed(self, authreq, host, req, headers):
353 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700354 old_add_header = req.add_header
355 def _add_header(name, val):
356 val = val.replace('\n', '')
357 old_add_header(name, val)
358 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700359 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700360 self, authreq, host, req, headers)
361 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700362 reset = getattr(self, 'reset_retry_count', None)
363 if reset is not None:
364 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700365 elif getattr(self, 'retried', None):
366 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700367 raise
368
Sarah Owens1f7627f2012-10-31 09:21:55 -0700369class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900370 def http_error_401(self, req, fp, code, msg, headers):
371 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700372 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900373 self, req, fp, code, msg, headers)
374
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800375 def http_error_auth_reqed(self, auth_header, host, req, headers):
376 try:
377 old_add_header = req.add_header
378 def _add_header(name, val):
379 val = val.replace('\n', '')
380 old_add_header(name, val)
381 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700382 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800383 self, auth_header, host, req, headers)
384 except:
385 reset = getattr(self, 'reset_retry_count', None)
386 if reset is not None:
387 reset()
388 elif getattr(self, 'retried', None):
389 self.retried = 0
390 raise
391
Carlos Aguado1242e602014-02-03 13:48:47 +0100392class _KerberosAuthHandler(urllib.request.BaseHandler):
393 def __init__(self):
394 self.retried = 0
395 self.context = None
396 self.handler_order = urllib.request.BaseHandler.handler_order - 50
397
David Pursehouse65b0ba52018-06-24 16:21:51 +0900398 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100399 host = req.get_host()
400 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
401 return retry
402
403 def http_error_auth_reqed(self, auth_header, host, req, headers):
404 try:
405 spn = "HTTP@%s" % host
406 authdata = self._negotiate_get_authdata(auth_header, headers)
407
408 if self.retried > 3:
409 raise urllib.request.HTTPError(req.get_full_url(), 401,
410 "Negotiate auth failed", headers, None)
411 else:
412 self.retried += 1
413
414 neghdr = self._negotiate_get_svctk(spn, authdata)
415 if neghdr is None:
416 return None
417
418 req.add_unredirected_header('Authorization', neghdr)
419 response = self.parent.open(req)
420
421 srvauth = self._negotiate_get_authdata(auth_header, response.info())
422 if self._validate_response(srvauth):
423 return response
424 except kerberos.GSSError:
425 return None
426 except:
427 self.reset_retry_count()
428 raise
429 finally:
430 self._clean_context()
431
432 def reset_retry_count(self):
433 self.retried = 0
434
435 def _negotiate_get_authdata(self, auth_header, headers):
436 authhdr = headers.get(auth_header, None)
437 if authhdr is not None:
438 for mech_tuple in authhdr.split(","):
439 mech, __, authdata = mech_tuple.strip().partition(" ")
440 if mech.lower() == "negotiate":
441 return authdata.strip()
442 return None
443
444 def _negotiate_get_svctk(self, spn, authdata):
445 if authdata is None:
446 return None
447
448 result, self.context = kerberos.authGSSClientInit(spn)
449 if result < kerberos.AUTH_GSS_COMPLETE:
450 return None
451
452 result = kerberos.authGSSClientStep(self.context, authdata)
453 if result < kerberos.AUTH_GSS_CONTINUE:
454 return None
455
456 response = kerberos.authGSSClientResponse(self.context)
457 return "Negotiate %s" % response
458
459 def _validate_response(self, authdata):
460 if authdata is None:
461 return None
462 result = kerberos.authGSSClientStep(self.context, authdata)
463 if result == kerberos.AUTH_GSS_COMPLETE:
464 return True
465 return None
466
467 def _clean_context(self):
468 if self.context is not None:
469 kerberos.authGSSClientClean(self.context)
470 self.context = None
471
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700472def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700473 handlers = [_UserAgentHandler()]
474
Sarah Owens1f7627f2012-10-31 09:21:55 -0700475 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700476 try:
477 n = netrc.netrc()
478 for host in n.hosts:
479 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800480 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
481 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700482 except netrc.NetrcParseError:
483 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700484 except IOError:
485 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700486 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800487 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100488 if kerberos:
489 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700490
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700491 if 'http_proxy' in os.environ:
492 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700493 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700494 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700495 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
496 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
497 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700498
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700499def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400500 result = 0
501
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700502 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
503 opt.add_option("--repo-dir", dest="repodir",
504 help="path to .repo/")
505 opt.add_option("--wrapper-version", dest="wrapper_version",
506 help="version of the wrapper script")
507 opt.add_option("--wrapper-path", dest="wrapper_path",
508 help="location of the wrapper script")
509 _PruneOptions(argv, opt)
510 opt, argv = opt.parse_args(argv)
511
512 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
513 _CheckRepoDir(opt.repodir)
514
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800515 Version.wrapper_version = opt.wrapper_version
516 Version.wrapper_path = opt.wrapper_path
517
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518 repo = _Repo(opt.repodir)
519 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700520 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800521 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700522 init_http()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400523 result = repo._Run(argv) or 0
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700524 finally:
525 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700526 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700527 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400528 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900529 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700530 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900531 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700532 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800533 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800535 argv = list(sys.argv)
536 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800538 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700539 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700540 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
541 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400542 result = 128
543
Renaud Paquaye8595e92016-11-01 15:51:59 -0700544 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400545 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546
547if __name__ == '__main__':
548 _Main(sys.argv[1:])