blob: 9fbccfb934653d0394da5264642e6a802a2517cc [file] [log] [blame]
David Pursehouse8898e2f2012-11-14 07:51:03 +09001#!/usr/bin/env python
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
JoonCheol Parke9860722012-10-11 02:31:44 +090017import getpass
Conley Owensc9129d92012-10-01 16:12:28 -070018import imp
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070019import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import optparse
21import os
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022import sys
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070023import time
Sarah Owens1f7627f2012-10-31 09:21:55 -070024try:
25 import urllib2
26except ImportError:
27 # For python3
28 import urllib.request
29else:
30 # For python2
Sarah Owens1f7627f2012-10-31 09:21:55 -070031 urllib = imp.new_module('urllib')
32 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070034from trace import SetTrace
Shawn O. Pearce334851e2011-09-19 08:05:31 -070035from git_command import git, GitCommand
Doug Anderson0048b692010-12-21 13:39:23 -080036from git_config import init_ssh, close_ssh
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080037from command import InteractiveCommand
38from command import MirrorSafeCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080039from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070040from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070041from error import DownloadError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080042from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090043from error import ManifestParseError
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044from error import NoSuchProjectError
45from error import RepoChangedException
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -070046from manifest_xml import XmlManifest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070047from pager import RunPager
48
David Pursehouse5c6eeac2012-10-11 16:44:48 +090049from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070050
51global_options = optparse.OptionParser(
52 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
53 )
54global_options.add_option('-p', '--paginate',
55 dest='pager', action='store_true',
56 help='display command output in the pager')
57global_options.add_option('--no-pager',
58 dest='no_pager', action='store_true',
59 help='disable the pager')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070060global_options.add_option('--trace',
61 dest='trace', action='store_true',
62 help='trace git command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070063global_options.add_option('--time',
64 dest='time', action='store_true',
65 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080066global_options.add_option('--version',
67 dest='show_version', action='store_true',
68 help='display this version of repo')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070069
70class _Repo(object):
71 def __init__(self, repodir):
72 self.repodir = repodir
73 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -040074 # add 'branch' as an alias for 'branches'
75 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070076
77 def _Run(self, argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -040078 result = 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070079 name = None
80 glob = []
81
Sarah Owensa6053d52012-11-01 13:36:50 -070082 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070083 if not argv[i].startswith('-'):
84 name = argv[i]
85 if i > 0:
86 glob = argv[:i]
87 argv = argv[i + 1:]
88 break
89 if not name:
90 glob = argv
91 name = 'help'
92 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +090093 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070094
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070095 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070096 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080097 if gopts.show_version:
98 if name == 'help':
99 name = 'version'
100 else:
101 print >>sys.stderr, 'fatal: invalid usage of --version'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400102 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104 try:
105 cmd = self.commands[name]
106 except KeyError:
107 print >>sys.stderr,\
108 "repo: '%s' is not a repo command. See 'repo help'."\
109 % name
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400110 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700111
112 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700113 cmd.manifest = XmlManifest(cmd.repodir)
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700114 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800116 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
117 print >>sys.stderr, \
118 "fatal: '%s' requires a working directory"\
119 % name
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400120 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800121
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700122 copts, cargs = cmd.OptionParser.parse_args(argv)
123
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
125 config = cmd.manifest.globalConfig
126 if gopts.pager:
127 use_pager = True
128 else:
129 use_pager = config.GetBoolean('pager.%s' % name)
130 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700131 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700132 if use_pager:
133 RunPager(config)
134
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135 try:
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700136 start = time.time()
137 try:
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400138 result = cmd.Execute(copts, cargs)
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700139 finally:
140 elapsed = time.time() - start
141 hours, remainder = divmod(elapsed, 3600)
142 minutes, seconds = divmod(remainder, 60)
143 if gopts.time:
144 if hours == 0:
145 print >>sys.stderr, 'real\t%dm%.3fs' \
146 % (minutes, seconds)
147 else:
148 print >>sys.stderr, 'real\t%dh%dm%.3fs' \
149 % (hours, minutes, seconds)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700150 except DownloadError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700151 print >>sys.stderr, 'error: %s' % str(e)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400152 return 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700153 except ManifestInvalidRevisionError as e:
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800154 print >>sys.stderr, 'error: %s' % str(e)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400155 return 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700156 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157 if e.name:
158 print >>sys.stderr, 'error: project %s not found' % e.name
159 else:
160 print >>sys.stderr, 'error: no project in current directory'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400161 return 1
162
163 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700164
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700165def _MyRepoPath():
166 return os.path.dirname(__file__)
167
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700168def _MyWrapperPath():
169 return os.path.join(os.path.dirname(__file__), 'repo')
170
Conley Owensc9129d92012-10-01 16:12:28 -0700171_wrapper_module = None
172def WrapperModule():
173 global _wrapper_module
174 if not _wrapper_module:
175 _wrapper_module = imp.load_source('wrapper', _MyWrapperPath())
176 return _wrapper_module
177
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700178def _CurrentWrapperVersion():
Conley Owensc9129d92012-10-01 16:12:28 -0700179 return WrapperModule().VERSION
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700180
181def _CheckWrapperVersion(ver, repo_path):
182 if not repo_path:
183 repo_path = '~/bin/repo'
184
185 if not ver:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900186 print >>sys.stderr, 'no --wrapper-version argument'
187 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700188
189 exp = _CurrentWrapperVersion()
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900190 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700191 if len(ver) == 1:
192 ver = (0, ver[0])
193
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900194 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700195 if exp[0] > ver[0] or ver < (0, 4):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700196 print >>sys.stderr, """
197!!! A new repo command (%5s) is available. !!!
198!!! You must upgrade before you can continue: !!!
199
200 cp %s %s
201""" % (exp_str, _MyWrapperPath(), repo_path)
202 sys.exit(1)
203
204 if exp > ver:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 print >>sys.stderr, """
206... A new repo command (%5s) is available.
207... You should upgrade soon:
208
209 cp %s %s
210""" % (exp_str, _MyWrapperPath(), repo_path)
211
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200212def _CheckRepoDir(repo_dir):
213 if not repo_dir:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900214 print >>sys.stderr, 'no --repo-dir argument'
215 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216
217def _PruneOptions(argv, opt):
218 i = 0
219 while i < len(argv):
220 a = argv[i]
221 if a == '--':
222 break
223 if a.startswith('--'):
224 eq = a.find('=')
225 if eq > 0:
226 a = a[0:eq]
227 if not opt.has_option(a):
228 del argv[i]
229 continue
230 i += 1
231
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700232_user_agent = None
233
234def _UserAgent():
235 global _user_agent
236
237 if _user_agent is None:
238 py_version = sys.version_info
239
240 os_name = sys.platform
241 if os_name == 'linux2':
242 os_name = 'Linux'
243 elif os_name == 'win32':
244 os_name = 'Win32'
245 elif os_name == 'cygwin':
246 os_name = 'Cygwin'
247 elif os_name == 'darwin':
248 os_name = 'Darwin'
249
250 p = GitCommand(
251 None, ['describe', 'HEAD'],
252 cwd = _MyRepoPath(),
253 capture_stdout = True)
254 if p.Wait() == 0:
255 repo_version = p.stdout
256 if len(repo_version) > 0 and repo_version[-1] == '\n':
257 repo_version = repo_version[0:-1]
258 if len(repo_version) > 0 and repo_version[0] == 'v':
259 repo_version = repo_version[1:]
260 else:
261 repo_version = 'unknown'
262
263 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
264 repo_version,
265 os_name,
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900266 '.'.join(map(str, git.version_tuple())),
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700267 py_version[0], py_version[1], py_version[2])
268 return _user_agent
269
Sarah Owens1f7627f2012-10-31 09:21:55 -0700270class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700271 def http_request(self, req):
272 req.add_header('User-Agent', _UserAgent())
273 return req
274
275 def https_request(self, req):
276 req.add_header('User-Agent', _UserAgent())
277 return req
278
JoonCheol Parke9860722012-10-11 02:31:44 +0900279def _AddPasswordFromUserInput(handler, msg, req):
280 # If repo could not find auth info from netrc, try to get it from user input
281 url = req.get_full_url()
282 user, password = handler.passwd.find_user_password(None, url)
283 if user is None:
284 print msg
285 try:
286 user = raw_input('User: ')
287 password = getpass.getpass()
288 except KeyboardInterrupt:
289 return
290 handler.passwd.add_password(None, url, user, password)
291
Sarah Owens1f7627f2012-10-31 09:21:55 -0700292class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900293 def http_error_401(self, req, fp, code, msg, headers):
294 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700295 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900296 self, req, fp, code, msg, headers)
297
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700298 def http_error_auth_reqed(self, authreq, host, req, headers):
299 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700300 old_add_header = req.add_header
301 def _add_header(name, val):
302 val = val.replace('\n', '')
303 old_add_header(name, val)
304 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700305 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700306 self, authreq, host, req, headers)
307 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700308 reset = getattr(self, 'reset_retry_count', None)
309 if reset is not None:
310 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700311 elif getattr(self, 'retried', None):
312 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700313 raise
314
Sarah Owens1f7627f2012-10-31 09:21:55 -0700315class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900316 def http_error_401(self, req, fp, code, msg, headers):
317 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700318 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900319 self, req, fp, code, msg, headers)
320
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800321 def http_error_auth_reqed(self, auth_header, host, req, headers):
322 try:
323 old_add_header = req.add_header
324 def _add_header(name, val):
325 val = val.replace('\n', '')
326 old_add_header(name, val)
327 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700328 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800329 self, auth_header, host, req, headers)
330 except:
331 reset = getattr(self, 'reset_retry_count', None)
332 if reset is not None:
333 reset()
334 elif getattr(self, 'retried', None):
335 self.retried = 0
336 raise
337
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700338def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700339 handlers = [_UserAgentHandler()]
340
Sarah Owens1f7627f2012-10-31 09:21:55 -0700341 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700342 try:
343 n = netrc.netrc()
344 for host in n.hosts:
345 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800346 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
347 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700348 except netrc.NetrcParseError:
349 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700350 except IOError:
351 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700352 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800353 handlers.append(_DigestAuthHandler(mgr))
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700354
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700355 if 'http_proxy' in os.environ:
356 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700357 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700358 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700359 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
360 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
361 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700362
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400364 result = 0
365
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700366 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
367 opt.add_option("--repo-dir", dest="repodir",
368 help="path to .repo/")
369 opt.add_option("--wrapper-version", dest="wrapper_version",
370 help="version of the wrapper script")
371 opt.add_option("--wrapper-path", dest="wrapper_path",
372 help="location of the wrapper script")
373 _PruneOptions(argv, opt)
374 opt, argv = opt.parse_args(argv)
375
376 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
377 _CheckRepoDir(opt.repodir)
378
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800379 Version.wrapper_version = opt.wrapper_version
380 Version.wrapper_path = opt.wrapper_path
381
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700382 repo = _Repo(opt.repodir)
383 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700384 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800385 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700386 init_http()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400387 result = repo._Run(argv) or 0
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700388 finally:
389 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700390 except KeyboardInterrupt:
David Pursehouseb0936b02012-11-13 09:56:16 +0900391 print >>sys.stderr, 'aborted by user'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400392 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900393 except ManifestParseError as mpe:
394 print >>sys.stderr, 'fatal: %s' % mpe
395 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700396 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800397 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700398 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800399 argv = list(sys.argv)
400 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700401 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800402 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700403 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700404 print >>sys.stderr, 'fatal: cannot restart repo after upgrade'
405 print >>sys.stderr, 'fatal: %s' % e
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400406 result = 128
407
408 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700409
410if __name__ == '__main__':
411 _Main(sys.argv[1:])