blob: b47bc66f28f36ba04eed8a6c0beaf74c1a69aa8a [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#
2# Copyright (C) 2008 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
Shawn O. Pearcec12c3602009-04-17 21:03:32 -070016import cPickle
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import os
18import re
Shawn O. Pearcefb231612009-04-10 18:53:46 -070019import subprocess
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
Shawn O. Pearcefb231612009-04-10 18:53:46 -070021import time
22from signal import SIGTERM
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080023from urllib2 import urlopen, HTTPError
24from error import GitError, UploadError
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070025from trace import Trace
Shawn O. Pearcefb231612009-04-10 18:53:46 -070026from git_command import GitCommand, _ssh_sock
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027
28R_HEADS = 'refs/heads/'
29R_TAGS = 'refs/tags/'
30ID_RE = re.compile('^[0-9a-f]{40}$')
31
Shawn O. Pearce146fe902009-03-25 14:06:43 -070032REVIEW_CACHE = dict()
33
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034def IsId(rev):
35 return ID_RE.match(rev)
36
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070037def _key(name):
38 parts = name.split('.')
39 if len(parts) < 2:
40 return name.lower()
41 parts[ 0] = parts[ 0].lower()
42 parts[-1] = parts[-1].lower()
43 return '.'.join(parts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044
45class GitConfig(object):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070046 _ForUser = None
47
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070048 @classmethod
49 def ForUser(cls):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070050 if cls._ForUser is None:
51 cls._ForUser = cls(file = os.path.expanduser('~/.gitconfig'))
52 return cls._ForUser
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070053
54 @classmethod
55 def ForRepository(cls, gitdir, defaults=None):
56 return cls(file = os.path.join(gitdir, 'config'),
57 defaults = defaults)
58
Shawn O. Pearce1b34c912009-05-21 18:52:49 -070059 def __init__(self, file, defaults=None, pickleFile=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070060 self.file = file
61 self.defaults = defaults
62 self._cache_dict = None
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070063 self._section_dict = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070064 self._remotes = {}
65 self._branches = {}
Shawn O. Pearce1b34c912009-05-21 18:52:49 -070066
67 if pickleFile is None:
68 self._pickle = os.path.join(
69 os.path.dirname(self.file),
70 '.repopickle_' + os.path.basename(self.file))
71 else:
72 self._pickle = pickleFile
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070073
Shawn O. Pearce98ea26b2009-06-04 19:19:11 -070074 def ClearCache(self):
75 if os.path.exists(self._pickle):
76 os.remove(self._pickle)
77 self._cache_dict = None
78 self._section_dict = None
79 self._remotes = {}
80 self._branches = {}
81
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070082 def Has(self, name, include_defaults = True):
83 """Return true if this configuration file has the key.
84 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070085 if _key(name) in self._cache:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070086 return True
87 if include_defaults and self.defaults:
88 return self.defaults.Has(name, include_defaults = True)
89 return False
90
91 def GetBoolean(self, name):
92 """Returns a boolean from the configuration file.
93 None : The value was not defined, or is not a boolean.
94 True : The value was set to true or yes.
95 False: The value was set to false or no.
96 """
97 v = self.GetString(name)
98 if v is None:
99 return None
100 v = v.lower()
101 if v in ('true', 'yes'):
102 return True
103 if v in ('false', 'no'):
104 return False
105 return None
106
107 def GetString(self, name, all=False):
108 """Get the first value for a key, or None if it is not defined.
109
110 This configuration file is used first, if the key is not
111 defined or all = True then the defaults are also searched.
112 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700113 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700114 v = self._cache[_key(name)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115 except KeyError:
116 if self.defaults:
117 return self.defaults.GetString(name, all = all)
118 v = []
119
120 if not all:
121 if v:
122 return v[0]
123 return None
124
125 r = []
126 r.extend(v)
127 if self.defaults:
128 r.extend(self.defaults.GetString(name, all = True))
129 return r
130
131 def SetString(self, name, value):
132 """Set the value(s) for a key.
133 Only this configuration file is modified.
134
135 The supplied value should be either a string,
136 or a list of strings (to store multiple values).
137 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700138 key = _key(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139
140 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700141 old = self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700142 except KeyError:
143 old = []
144
145 if value is None:
146 if old:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700147 del self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700148 self._do('--unset-all', name)
149
150 elif isinstance(value, list):
151 if len(value) == 0:
152 self.SetString(name, None)
153
154 elif len(value) == 1:
155 self.SetString(name, value[0])
156
157 elif old != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700158 self._cache[key] = list(value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700159 self._do('--replace-all', name, value[0])
160 for i in xrange(1, len(value)):
161 self._do('--add', name, value[i])
162
163 elif len(old) != 1 or old[0] != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700164 self._cache[key] = [value]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700165 self._do('--replace-all', name, value)
166
167 def GetRemote(self, name):
168 """Get the remote.$name.* configuration values as an object.
169 """
170 try:
171 r = self._remotes[name]
172 except KeyError:
173 r = Remote(self, name)
174 self._remotes[r.name] = r
175 return r
176
177 def GetBranch(self, name):
178 """Get the branch.$name.* configuration values as an object.
179 """
180 try:
181 b = self._branches[name]
182 except KeyError:
183 b = Branch(self, name)
184 self._branches[b.name] = b
185 return b
186
Shawn O. Pearce366ad212009-05-19 12:47:37 -0700187 def GetSubSections(self, section):
188 """List all subsection names matching $section.*.*
189 """
190 return self._sections.get(section, set())
191
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700192 def HasSection(self, section, subsection = ''):
193 """Does at least one key in section.subsection exist?
194 """
195 try:
196 return subsection in self._sections[section]
197 except KeyError:
198 return False
199
200 @property
201 def _sections(self):
202 d = self._section_dict
203 if d is None:
204 d = {}
205 for name in self._cache.keys():
206 p = name.split('.')
207 if 2 == len(p):
208 section = p[0]
209 subsect = ''
210 else:
211 section = p[0]
212 subsect = '.'.join(p[1:-1])
213 if section not in d:
214 d[section] = set()
215 d[section].add(subsect)
216 self._section_dict = d
217 return d
218
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219 @property
220 def _cache(self):
221 if self._cache_dict is None:
222 self._cache_dict = self._Read()
223 return self._cache_dict
224
225 def _Read(self):
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700226 d = self._ReadPickle()
227 if d is None:
228 d = self._ReadGit()
229 self._SavePickle(d)
230 return d
231
232 def _ReadPickle(self):
233 try:
234 if os.path.getmtime(self._pickle) \
235 <= os.path.getmtime(self.file):
236 os.remove(self._pickle)
237 return None
238 except OSError:
239 return None
240 try:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700241 Trace(': unpickle %s', self.file)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700242 fd = open(self._pickle, 'rb')
243 try:
244 return cPickle.load(fd)
245 finally:
246 fd.close()
Shawn O. Pearce2a3a81b2009-06-12 09:10:07 -0700247 except EOFError:
248 os.remove(self._pickle)
249 return None
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700250 except IOError:
251 os.remove(self._pickle)
252 return None
253 except cPickle.PickleError:
254 os.remove(self._pickle)
255 return None
256
257 def _SavePickle(self, cache):
258 try:
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700259 fd = open(self._pickle, 'wb')
260 try:
261 cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
262 finally:
263 fd.close()
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700264 except IOError:
Shawn O. Pearceb0ca41e2009-07-03 20:01:47 -0700265 if os.path.exists(self._pickle):
266 os.remove(self._pickle)
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700267 except cPickle.PickleError:
Shawn O. Pearceb0ca41e2009-07-03 20:01:47 -0700268 if os.path.exists(self._pickle):
269 os.remove(self._pickle)
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700270
271 def _ReadGit(self):
David Aguilar438c5472009-06-28 15:09:16 -0700272 """
273 Read configuration data from git.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274
David Aguilar438c5472009-06-28 15:09:16 -0700275 This internal method populates the GitConfig cache.
276
277 """
David Aguilar438c5472009-06-28 15:09:16 -0700278 c = {}
Shawn O. Pearcec24c7202009-07-02 16:12:57 -0700279 d = self._do('--null', '--list')
280 if d is None:
281 return c
282 for line in d.rstrip('\0').split('\0'):
David Aguilar438c5472009-06-28 15:09:16 -0700283 if '\n' in line:
284 key, val = line.split('\n', 1)
285 else:
286 key = line
287 val = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288
289 if key in c:
290 c[key].append(val)
291 else:
292 c[key] = [val]
293
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700294 return c
295
296 def _do(self, *args):
297 command = ['config', '--file', self.file]
298 command.extend(args)
299
300 p = GitCommand(None,
301 command,
302 capture_stdout = True,
303 capture_stderr = True)
304 if p.Wait() == 0:
305 return p.stdout
306 else:
307 GitError('git config %s: %s' % (str(args), p.stderr))
308
309
310class RefSpec(object):
311 """A Git refspec line, split into its components:
312
313 forced: True if the line starts with '+'
314 src: Left side of the line
315 dst: Right side of the line
316 """
317
318 @classmethod
319 def FromString(cls, rs):
320 lhs, rhs = rs.split(':', 2)
321 if lhs.startswith('+'):
322 lhs = lhs[1:]
323 forced = True
324 else:
325 forced = False
326 return cls(forced, lhs, rhs)
327
328 def __init__(self, forced, lhs, rhs):
329 self.forced = forced
330 self.src = lhs
331 self.dst = rhs
332
333 def SourceMatches(self, rev):
334 if self.src:
335 if rev == self.src:
336 return True
337 if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
338 return True
339 return False
340
341 def DestMatches(self, ref):
342 if self.dst:
343 if ref == self.dst:
344 return True
345 if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
346 return True
347 return False
348
349 def MapSource(self, rev):
350 if self.src.endswith('/*'):
351 return self.dst[:-1] + rev[len(self.src) - 1:]
352 return self.dst
353
354 def __str__(self):
355 s = ''
356 if self.forced:
357 s += '+'
358 if self.src:
359 s += self.src
360 if self.dst:
361 s += ':'
362 s += self.dst
363 return s
364
365
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700366_ssh_cache = {}
367_ssh_master = True
368
Shawn O. Pearce896d5df2009-04-21 14:51:04 -0700369def _open_ssh(host, port):
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700370 global _ssh_master
371
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700372 key = '%s:%s' % (host, port)
373 if key in _ssh_cache:
374 return True
375
376 if not _ssh_master \
377 or 'GIT_SSH' in os.environ \
Shawn O. Pearce2b5b4ac2009-04-23 17:22:18 -0700378 or sys.platform in ('win32', 'cygwin'):
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700379 # failed earlier, or cygwin ssh can't do this
380 #
381 return False
382
383 command = ['ssh',
384 '-o','ControlPath %s' % _ssh_sock(),
385 '-p',str(port),
386 '-M',
387 '-N',
388 host]
389 try:
390 Trace(': %s', ' '.join(command))
391 p = subprocess.Popen(command)
392 except Exception, e:
393 _ssh_master = False
394 print >>sys.stderr, \
395 '\nwarn: cannot enable ssh control master for %s:%s\n%s' \
396 % (host,port, str(e))
397 return False
398
399 _ssh_cache[key] = p
400 time.sleep(1)
401 return True
402
403def close_ssh():
404 for key,p in _ssh_cache.iteritems():
Shawn O. Pearce26120ca2009-06-16 11:49:10 -0700405 try:
406 os.kill(p.pid, SIGTERM)
407 p.wait()
Shawn O. Pearcefb5c8fd2009-06-16 14:57:46 -0700408 except OSError:
Shawn O. Pearce26120ca2009-06-16 11:49:10 -0700409 pass
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700410 _ssh_cache.clear()
411
412 d = _ssh_sock(create=False)
413 if d:
414 try:
415 os.rmdir(os.path.dirname(d))
416 except OSError:
417 pass
418
419URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
Shawn O. Pearce2f968c92009-04-30 14:30:28 -0700420URI_ALL = re.compile(r'^([a-z][a-z+]*)://([^@/]*@?[^/]*)/')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700421
422def _preconnect(url):
423 m = URI_ALL.match(url)
424 if m:
425 scheme = m.group(1)
426 host = m.group(2)
427 if ':' in host:
428 host, port = host.split(':')
Shawn O. Pearce896d5df2009-04-21 14:51:04 -0700429 else:
430 port = 22
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700431 if scheme in ('ssh', 'git+ssh', 'ssh+git'):
432 return _open_ssh(host, port)
433 return False
434
435 m = URI_SCP.match(url)
436 if m:
437 host = m.group(1)
Shawn O. Pearce896d5df2009-04-21 14:51:04 -0700438 return _open_ssh(host, 22)
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700439
Shawn O. Pearce7b4f4352009-06-12 09:06:35 -0700440 return False
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700441
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700442class Remote(object):
443 """Configuration options related to a remote.
444 """
445 def __init__(self, config, name):
446 self._config = config
447 self.name = name
448 self.url = self._Get('url')
449 self.review = self._Get('review')
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800450 self.projectname = self._Get('projectname')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700451 self.fetch = map(lambda x: RefSpec.FromString(x),
452 self._Get('fetch', all=True))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800453 self._review_protocol = None
454
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700455 def PreConnectFetch(self):
456 return _preconnect(self.url)
457
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800458 @property
459 def ReviewProtocol(self):
460 if self._review_protocol is None:
461 if self.review is None:
462 return None
463
464 u = self.review
465 if not u.startswith('http:') and not u.startswith('https:'):
466 u = 'http://%s' % u
Shawn O. Pearce13cc3842009-03-25 13:54:54 -0700467 if u.endswith('/Gerrit'):
468 u = u[:len(u) - len('/Gerrit')]
469 if not u.endswith('/ssh_info'):
470 if not u.endswith('/'):
471 u += '/'
472 u += 'ssh_info'
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800473
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700474 if u in REVIEW_CACHE:
475 info = REVIEW_CACHE[u]
476 self._review_protocol = info[0]
477 self._review_host = info[1]
478 self._review_port = info[2]
479 else:
480 try:
481 info = urlopen(u).read()
482 if info == 'NOT_AVAILABLE':
483 raise UploadError('Upload over ssh unavailable')
484 if '<' in info:
485 # Assume the server gave us some sort of HTML
486 # response back, like maybe a login page.
487 #
488 raise UploadError('Cannot read %s:\n%s' % (u, info))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800489
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700490 self._review_protocol = 'ssh'
491 self._review_host = info.split(" ")[0]
492 self._review_port = info.split(" ")[1]
493 except HTTPError, e:
494 if e.code == 404:
495 self._review_protocol = 'http-post'
496 self._review_host = None
497 self._review_port = None
498 else:
499 raise UploadError('Cannot guess Gerrit version')
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800500
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700501 REVIEW_CACHE[u] = (
502 self._review_protocol,
503 self._review_host,
504 self._review_port)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800505 return self._review_protocol
506
507 def SshReviewUrl(self, userEmail):
508 if self.ReviewProtocol != 'ssh':
509 return None
510 return 'ssh://%s@%s:%s/%s' % (
511 userEmail.split("@")[0],
512 self._review_host,
513 self._review_port,
514 self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700515
516 def ToLocal(self, rev):
517 """Convert a remote revision string to something we have locally.
518 """
519 if IsId(rev):
520 return rev
521 if rev.startswith(R_TAGS):
522 return rev
523
524 if not rev.startswith('refs/'):
525 rev = R_HEADS + rev
526
527 for spec in self.fetch:
528 if spec.SourceMatches(rev):
529 return spec.MapSource(rev)
530 raise GitError('remote %s does not have %s' % (self.name, rev))
531
532 def WritesTo(self, ref):
533 """True if the remote stores to the tracking ref.
534 """
535 for spec in self.fetch:
536 if spec.DestMatches(ref):
537 return True
538 return False
539
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800540 def ResetFetch(self, mirror=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700541 """Set the fetch refspec to its default value.
542 """
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800543 if mirror:
544 dst = 'refs/heads/*'
545 else:
546 dst = 'refs/remotes/%s/*' % self.name
547 self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700548
549 def Save(self):
550 """Save this remote to the configuration.
551 """
552 self._Set('url', self.url)
553 self._Set('review', self.review)
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800554 self._Set('projectname', self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700555 self._Set('fetch', map(lambda x: str(x), self.fetch))
556
557 def _Set(self, key, value):
558 key = 'remote.%s.%s' % (self.name, key)
559 return self._config.SetString(key, value)
560
561 def _Get(self, key, all=False):
562 key = 'remote.%s.%s' % (self.name, key)
563 return self._config.GetString(key, all = all)
564
565
566class Branch(object):
567 """Configuration options related to a single branch.
568 """
569 def __init__(self, config, name):
570 self._config = config
571 self.name = name
572 self.merge = self._Get('merge')
573
574 r = self._Get('remote')
575 if r:
576 self.remote = self._config.GetRemote(r)
577 else:
578 self.remote = None
579
580 @property
581 def LocalMerge(self):
582 """Convert the merge spec to a local name.
583 """
584 if self.remote and self.merge:
585 return self.remote.ToLocal(self.merge)
586 return None
587
588 def Save(self):
589 """Save this branch back into the configuration.
590 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700591 if self._config.HasSection('branch', self.name):
592 if self.remote:
593 self._Set('remote', self.remote.name)
594 else:
595 self._Set('remote', None)
596 self._Set('merge', self.merge)
597
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700598 else:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700599 fd = open(self._config.file, 'ab')
600 try:
601 fd.write('[branch "%s"]\n' % self.name)
602 if self.remote:
603 fd.write('\tremote = %s\n' % self.remote.name)
604 if self.merge:
605 fd.write('\tmerge = %s\n' % self.merge)
606 finally:
607 fd.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700608
609 def _Set(self, key, value):
610 key = 'branch.%s.%s' % (self.name, key)
611 return self._config.SetString(key, value)
612
613 def _Get(self, key, all=False):
614 key = 'branch.%s.%s' % (self.name, key)
615 return self._config.GetString(key, all = all)