blob: f41fb8036c0d79a0ef35bf5666b3125c8ffa07a2 [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
31 import imp
32 urllib = imp.new_module('urllib')
33 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070035from trace import SetTrace
Shawn O. Pearce334851e2011-09-19 08:05:31 -070036from git_command import git, GitCommand
Doug Anderson0048b692010-12-21 13:39:23 -080037from git_config import init_ssh, close_ssh
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080038from command import InteractiveCommand
39from command import MirrorSafeCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080040from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070041from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070042from error import DownloadError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080043from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090044from error import ManifestParseError
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045from error import NoSuchProjectError
46from error import RepoChangedException
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -070047from manifest_xml import XmlManifest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070048from pager import RunPager
49
David Pursehouse5c6eeac2012-10-11 16:44:48 +090050from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070051
52global_options = optparse.OptionParser(
53 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
54 )
55global_options.add_option('-p', '--paginate',
56 dest='pager', action='store_true',
57 help='display command output in the pager')
58global_options.add_option('--no-pager',
59 dest='no_pager', action='store_true',
60 help='disable the pager')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070061global_options.add_option('--trace',
62 dest='trace', action='store_true',
63 help='trace git command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070064global_options.add_option('--time',
65 dest='time', action='store_true',
66 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080067global_options.add_option('--version',
68 dest='show_version', action='store_true',
69 help='display this version of repo')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070070
71class _Repo(object):
72 def __init__(self, repodir):
73 self.repodir = repodir
74 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -040075 # add 'branch' as an alias for 'branches'
76 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070077
78 def _Run(self, argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -040079 result = 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070080 name = None
81 glob = []
82
Sarah Owensa6053d52012-11-01 13:36:50 -070083 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070084 if not argv[i].startswith('-'):
85 name = argv[i]
86 if i > 0:
87 glob = argv[:i]
88 argv = argv[i + 1:]
89 break
90 if not name:
91 glob = argv
92 name = 'help'
93 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +090094 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070095
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070096 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070097 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080098 if gopts.show_version:
99 if name == 'help':
100 name = 'version'
101 else:
102 print >>sys.stderr, 'fatal: invalid usage of --version'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400103 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800104
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105 try:
106 cmd = self.commands[name]
107 except KeyError:
108 print >>sys.stderr,\
109 "repo: '%s' is not a repo command. See 'repo help'."\
110 % name
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400111 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700112
113 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700114 cmd.manifest = XmlManifest(cmd.repodir)
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700115 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800117 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
118 print >>sys.stderr, \
119 "fatal: '%s' requires a working directory"\
120 % name
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400121 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800122
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700123 copts, cargs = cmd.OptionParser.parse_args(argv)
124
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
126 config = cmd.manifest.globalConfig
127 if gopts.pager:
128 use_pager = True
129 else:
130 use_pager = config.GetBoolean('pager.%s' % name)
131 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700132 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133 if use_pager:
134 RunPager(config)
135
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136 try:
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700137 start = time.time()
138 try:
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400139 result = cmd.Execute(copts, cargs)
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700140 finally:
141 elapsed = time.time() - start
142 hours, remainder = divmod(elapsed, 3600)
143 minutes, seconds = divmod(remainder, 60)
144 if gopts.time:
145 if hours == 0:
146 print >>sys.stderr, 'real\t%dm%.3fs' \
147 % (minutes, seconds)
148 else:
149 print >>sys.stderr, 'real\t%dh%dm%.3fs' \
150 % (hours, minutes, seconds)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700151 except DownloadError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700152 print >>sys.stderr, 'error: %s' % str(e)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400153 return 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700154 except ManifestInvalidRevisionError as e:
Shawn O. Pearce559b8462009-03-02 12:56:08 -0800155 print >>sys.stderr, 'error: %s' % str(e)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400156 return 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700157 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158 if e.name:
159 print >>sys.stderr, 'error: project %s not found' % e.name
160 else:
161 print >>sys.stderr, 'error: no project in current directory'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400162 return 1
163
164 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700165
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700166def _MyRepoPath():
167 return os.path.dirname(__file__)
168
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169def _MyWrapperPath():
170 return os.path.join(os.path.dirname(__file__), 'repo')
171
Conley Owensc9129d92012-10-01 16:12:28 -0700172_wrapper_module = None
173def WrapperModule():
174 global _wrapper_module
175 if not _wrapper_module:
176 _wrapper_module = imp.load_source('wrapper', _MyWrapperPath())
177 return _wrapper_module
178
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179def _CurrentWrapperVersion():
Conley Owensc9129d92012-10-01 16:12:28 -0700180 return WrapperModule().VERSION
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700181
182def _CheckWrapperVersion(ver, repo_path):
183 if not repo_path:
184 repo_path = '~/bin/repo'
185
186 if not ver:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900187 print >>sys.stderr, 'no --wrapper-version argument'
188 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700189
190 exp = _CurrentWrapperVersion()
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900191 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700192 if len(ver) == 1:
193 ver = (0, ver[0])
194
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900195 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700196 if exp[0] > ver[0] or ver < (0, 4):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197 print >>sys.stderr, """
198!!! A new repo command (%5s) is available. !!!
199!!! You must upgrade before you can continue: !!!
200
201 cp %s %s
202""" % (exp_str, _MyWrapperPath(), repo_path)
203 sys.exit(1)
204
205 if exp > ver:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700206 print >>sys.stderr, """
207... A new repo command (%5s) is available.
208... You should upgrade soon:
209
210 cp %s %s
211""" % (exp_str, _MyWrapperPath(), repo_path)
212
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200213def _CheckRepoDir(repo_dir):
214 if not repo_dir:
David Pursehouse8a68ff92012-09-24 12:15:13 +0900215 print >>sys.stderr, 'no --repo-dir argument'
216 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
218def _PruneOptions(argv, opt):
219 i = 0
220 while i < len(argv):
221 a = argv[i]
222 if a == '--':
223 break
224 if a.startswith('--'):
225 eq = a.find('=')
226 if eq > 0:
227 a = a[0:eq]
228 if not opt.has_option(a):
229 del argv[i]
230 continue
231 i += 1
232
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700233_user_agent = None
234
235def _UserAgent():
236 global _user_agent
237
238 if _user_agent is None:
239 py_version = sys.version_info
240
241 os_name = sys.platform
242 if os_name == 'linux2':
243 os_name = 'Linux'
244 elif os_name == 'win32':
245 os_name = 'Win32'
246 elif os_name == 'cygwin':
247 os_name = 'Cygwin'
248 elif os_name == 'darwin':
249 os_name = 'Darwin'
250
251 p = GitCommand(
252 None, ['describe', 'HEAD'],
253 cwd = _MyRepoPath(),
254 capture_stdout = True)
255 if p.Wait() == 0:
256 repo_version = p.stdout
257 if len(repo_version) > 0 and repo_version[-1] == '\n':
258 repo_version = repo_version[0:-1]
259 if len(repo_version) > 0 and repo_version[0] == 'v':
260 repo_version = repo_version[1:]
261 else:
262 repo_version = 'unknown'
263
264 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
265 repo_version,
266 os_name,
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900267 '.'.join(map(str, git.version_tuple())),
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700268 py_version[0], py_version[1], py_version[2])
269 return _user_agent
270
Sarah Owens1f7627f2012-10-31 09:21:55 -0700271class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700272 def http_request(self, req):
273 req.add_header('User-Agent', _UserAgent())
274 return req
275
276 def https_request(self, req):
277 req.add_header('User-Agent', _UserAgent())
278 return req
279
JoonCheol Parke9860722012-10-11 02:31:44 +0900280def _AddPasswordFromUserInput(handler, msg, req):
281 # If repo could not find auth info from netrc, try to get it from user input
282 url = req.get_full_url()
283 user, password = handler.passwd.find_user_password(None, url)
284 if user is None:
285 print msg
286 try:
287 user = raw_input('User: ')
288 password = getpass.getpass()
289 except KeyboardInterrupt:
290 return
291 handler.passwd.add_password(None, url, user, password)
292
Sarah Owens1f7627f2012-10-31 09:21:55 -0700293class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900294 def http_error_401(self, req, fp, code, msg, headers):
295 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700296 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900297 self, req, fp, code, msg, headers)
298
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700299 def http_error_auth_reqed(self, authreq, host, req, headers):
300 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700301 old_add_header = req.add_header
302 def _add_header(name, val):
303 val = val.replace('\n', '')
304 old_add_header(name, val)
305 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700306 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700307 self, authreq, host, req, headers)
308 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700309 reset = getattr(self, 'reset_retry_count', None)
310 if reset is not None:
311 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700312 elif getattr(self, 'retried', None):
313 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700314 raise
315
Sarah Owens1f7627f2012-10-31 09:21:55 -0700316class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900317 def http_error_401(self, req, fp, code, msg, headers):
318 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700319 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900320 self, req, fp, code, msg, headers)
321
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800322 def http_error_auth_reqed(self, auth_header, host, req, headers):
323 try:
324 old_add_header = req.add_header
325 def _add_header(name, val):
326 val = val.replace('\n', '')
327 old_add_header(name, val)
328 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700329 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800330 self, auth_header, host, req, headers)
331 except:
332 reset = getattr(self, 'reset_retry_count', None)
333 if reset is not None:
334 reset()
335 elif getattr(self, 'retried', None):
336 self.retried = 0
337 raise
338
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700339def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700340 handlers = [_UserAgentHandler()]
341
Sarah Owens1f7627f2012-10-31 09:21:55 -0700342 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700343 try:
344 n = netrc.netrc()
345 for host in n.hosts:
346 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800347 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
348 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700349 except netrc.NetrcParseError:
350 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700351 except IOError:
352 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700353 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800354 handlers.append(_DigestAuthHandler(mgr))
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700355
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700356 if 'http_proxy' in os.environ:
357 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700358 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700359 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700360 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
361 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
362 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700363
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400365 result = 0
366
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700367 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
368 opt.add_option("--repo-dir", dest="repodir",
369 help="path to .repo/")
370 opt.add_option("--wrapper-version", dest="wrapper_version",
371 help="version of the wrapper script")
372 opt.add_option("--wrapper-path", dest="wrapper_path",
373 help="location of the wrapper script")
374 _PruneOptions(argv, opt)
375 opt, argv = opt.parse_args(argv)
376
377 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
378 _CheckRepoDir(opt.repodir)
379
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800380 Version.wrapper_version = opt.wrapper_version
381 Version.wrapper_path = opt.wrapper_path
382
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383 repo = _Repo(opt.repodir)
384 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700385 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800386 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700387 init_http()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400388 result = repo._Run(argv) or 0
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700389 finally:
390 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700391 except KeyboardInterrupt:
David Pursehouseb0936b02012-11-13 09:56:16 +0900392 print >>sys.stderr, 'aborted by user'
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400393 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900394 except ManifestParseError as mpe:
395 print >>sys.stderr, 'fatal: %s' % mpe
396 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700397 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800398 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700399 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800400 argv = list(sys.argv)
401 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700402 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800403 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700404 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700405 print >>sys.stderr, 'fatal: cannot restart repo after upgrade'
406 print >>sys.stderr, 'fatal: %s' % e
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400407 result = 128
408
409 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410
411if __name__ == '__main__':
412 _Main(sys.argv[1:])