blob: 163b08093def701301d62881050aa314cefa3de2 [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
59 def __init__(self, file, defaults=None):
60 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. Pearcec12c3602009-04-17 21:03:32 -070066 self._pickle = os.path.join(
67 os.path.dirname(self.file),
68 '.repopickle_' + os.path.basename(self.file))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070069
70 def Has(self, name, include_defaults = True):
71 """Return true if this configuration file has the key.
72 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070073 if _key(name) in self._cache:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070074 return True
75 if include_defaults and self.defaults:
76 return self.defaults.Has(name, include_defaults = True)
77 return False
78
79 def GetBoolean(self, name):
80 """Returns a boolean from the configuration file.
81 None : The value was not defined, or is not a boolean.
82 True : The value was set to true or yes.
83 False: The value was set to false or no.
84 """
85 v = self.GetString(name)
86 if v is None:
87 return None
88 v = v.lower()
89 if v in ('true', 'yes'):
90 return True
91 if v in ('false', 'no'):
92 return False
93 return None
94
95 def GetString(self, name, all=False):
96 """Get the first value for a key, or None if it is not defined.
97
98 This configuration file is used first, if the key is not
99 defined or all = True then the defaults are also searched.
100 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700101 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700102 v = self._cache[_key(name)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103 except KeyError:
104 if self.defaults:
105 return self.defaults.GetString(name, all = all)
106 v = []
107
108 if not all:
109 if v:
110 return v[0]
111 return None
112
113 r = []
114 r.extend(v)
115 if self.defaults:
116 r.extend(self.defaults.GetString(name, all = True))
117 return r
118
119 def SetString(self, name, value):
120 """Set the value(s) for a key.
121 Only this configuration file is modified.
122
123 The supplied value should be either a string,
124 or a list of strings (to store multiple values).
125 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700126 key = _key(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127
128 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700129 old = self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700130 except KeyError:
131 old = []
132
133 if value is None:
134 if old:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700135 del self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136 self._do('--unset-all', name)
137
138 elif isinstance(value, list):
139 if len(value) == 0:
140 self.SetString(name, None)
141
142 elif len(value) == 1:
143 self.SetString(name, value[0])
144
145 elif old != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700146 self._cache[key] = list(value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147 self._do('--replace-all', name, value[0])
148 for i in xrange(1, len(value)):
149 self._do('--add', name, value[i])
150
151 elif len(old) != 1 or old[0] != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700152 self._cache[key] = [value]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700153 self._do('--replace-all', name, value)
154
155 def GetRemote(self, name):
156 """Get the remote.$name.* configuration values as an object.
157 """
158 try:
159 r = self._remotes[name]
160 except KeyError:
161 r = Remote(self, name)
162 self._remotes[r.name] = r
163 return r
164
165 def GetBranch(self, name):
166 """Get the branch.$name.* configuration values as an object.
167 """
168 try:
169 b = self._branches[name]
170 except KeyError:
171 b = Branch(self, name)
172 self._branches[b.name] = b
173 return b
174
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700175 def HasSection(self, section, subsection = ''):
176 """Does at least one key in section.subsection exist?
177 """
178 try:
179 return subsection in self._sections[section]
180 except KeyError:
181 return False
182
183 @property
184 def _sections(self):
185 d = self._section_dict
186 if d is None:
187 d = {}
188 for name in self._cache.keys():
189 p = name.split('.')
190 if 2 == len(p):
191 section = p[0]
192 subsect = ''
193 else:
194 section = p[0]
195 subsect = '.'.join(p[1:-1])
196 if section not in d:
197 d[section] = set()
198 d[section].add(subsect)
199 self._section_dict = d
200 return d
201
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202 @property
203 def _cache(self):
204 if self._cache_dict is None:
205 self._cache_dict = self._Read()
206 return self._cache_dict
207
208 def _Read(self):
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700209 d = self._ReadPickle()
210 if d is None:
211 d = self._ReadGit()
212 self._SavePickle(d)
213 return d
214
215 def _ReadPickle(self):
216 try:
217 if os.path.getmtime(self._pickle) \
218 <= os.path.getmtime(self.file):
219 os.remove(self._pickle)
220 return None
221 except OSError:
222 return None
223 try:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700224 Trace(': unpickle %s', self.file)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700225 fd = open(self._pickle, 'rb')
226 try:
227 return cPickle.load(fd)
228 finally:
229 fd.close()
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700230 except IOError:
231 os.remove(self._pickle)
232 return None
233 except cPickle.PickleError:
234 os.remove(self._pickle)
235 return None
236
237 def _SavePickle(self, cache):
238 try:
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700239 fd = open(self._pickle, 'wb')
240 try:
241 cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
242 finally:
243 fd.close()
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700244 except IOError:
245 os.remove(self._pickle)
246 except cPickle.PickleError:
247 os.remove(self._pickle)
248
249 def _ReadGit(self):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700250 d = self._do('--null', '--list')
251 c = {}
252 while d:
253 lf = d.index('\n')
254 nul = d.index('\0', lf + 1)
255
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700256 key = _key(d[0:lf])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257 val = d[lf + 1:nul]
258
259 if key in c:
260 c[key].append(val)
261 else:
262 c[key] = [val]
263
264 d = d[nul + 1:]
265 return c
266
267 def _do(self, *args):
268 command = ['config', '--file', self.file]
269 command.extend(args)
270
271 p = GitCommand(None,
272 command,
273 capture_stdout = True,
274 capture_stderr = True)
275 if p.Wait() == 0:
276 return p.stdout
277 else:
278 GitError('git config %s: %s' % (str(args), p.stderr))
279
280
281class RefSpec(object):
282 """A Git refspec line, split into its components:
283
284 forced: True if the line starts with '+'
285 src: Left side of the line
286 dst: Right side of the line
287 """
288
289 @classmethod
290 def FromString(cls, rs):
291 lhs, rhs = rs.split(':', 2)
292 if lhs.startswith('+'):
293 lhs = lhs[1:]
294 forced = True
295 else:
296 forced = False
297 return cls(forced, lhs, rhs)
298
299 def __init__(self, forced, lhs, rhs):
300 self.forced = forced
301 self.src = lhs
302 self.dst = rhs
303
304 def SourceMatches(self, rev):
305 if self.src:
306 if rev == self.src:
307 return True
308 if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
309 return True
310 return False
311
312 def DestMatches(self, ref):
313 if self.dst:
314 if ref == self.dst:
315 return True
316 if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
317 return True
318 return False
319
320 def MapSource(self, rev):
321 if self.src.endswith('/*'):
322 return self.dst[:-1] + rev[len(self.src) - 1:]
323 return self.dst
324
325 def __str__(self):
326 s = ''
327 if self.forced:
328 s += '+'
329 if self.src:
330 s += self.src
331 if self.dst:
332 s += ':'
333 s += self.dst
334 return s
335
336
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700337_ssh_cache = {}
338_ssh_master = True
339
340def _open_ssh(host, port=None):
341 global _ssh_master
342
343 if port is None:
344 port = 22
345
346 key = '%s:%s' % (host, port)
347 if key in _ssh_cache:
348 return True
349
350 if not _ssh_master \
351 or 'GIT_SSH' in os.environ \
352 or sys.platform == 'win32':
353 # failed earlier, or cygwin ssh can't do this
354 #
355 return False
356
357 command = ['ssh',
358 '-o','ControlPath %s' % _ssh_sock(),
359 '-p',str(port),
360 '-M',
361 '-N',
362 host]
363 try:
364 Trace(': %s', ' '.join(command))
365 p = subprocess.Popen(command)
366 except Exception, e:
367 _ssh_master = False
368 print >>sys.stderr, \
369 '\nwarn: cannot enable ssh control master for %s:%s\n%s' \
370 % (host,port, str(e))
371 return False
372
373 _ssh_cache[key] = p
374 time.sleep(1)
375 return True
376
377def close_ssh():
378 for key,p in _ssh_cache.iteritems():
379 os.kill(p.pid, SIGTERM)
380 p.wait()
381 _ssh_cache.clear()
382
383 d = _ssh_sock(create=False)
384 if d:
385 try:
386 os.rmdir(os.path.dirname(d))
387 except OSError:
388 pass
389
390URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
391URI_ALL = re.compile(r'^([a-z][a-z+]*)://([^@/]*@?[^/])/')
392
393def _preconnect(url):
394 m = URI_ALL.match(url)
395 if m:
396 scheme = m.group(1)
397 host = m.group(2)
398 if ':' in host:
399 host, port = host.split(':')
400 if scheme in ('ssh', 'git+ssh', 'ssh+git'):
401 return _open_ssh(host, port)
402 return False
403
404 m = URI_SCP.match(url)
405 if m:
406 host = m.group(1)
407 return _open_ssh(host)
408
409
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410class Remote(object):
411 """Configuration options related to a remote.
412 """
413 def __init__(self, config, name):
414 self._config = config
415 self.name = name
416 self.url = self._Get('url')
417 self.review = self._Get('review')
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800418 self.projectname = self._Get('projectname')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700419 self.fetch = map(lambda x: RefSpec.FromString(x),
420 self._Get('fetch', all=True))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800421 self._review_protocol = None
422
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700423 def PreConnectFetch(self):
424 return _preconnect(self.url)
425
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800426 @property
427 def ReviewProtocol(self):
428 if self._review_protocol is None:
429 if self.review is None:
430 return None
431
432 u = self.review
433 if not u.startswith('http:') and not u.startswith('https:'):
434 u = 'http://%s' % u
Shawn O. Pearce13cc3842009-03-25 13:54:54 -0700435 if u.endswith('/Gerrit'):
436 u = u[:len(u) - len('/Gerrit')]
437 if not u.endswith('/ssh_info'):
438 if not u.endswith('/'):
439 u += '/'
440 u += 'ssh_info'
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800441
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700442 if u in REVIEW_CACHE:
443 info = REVIEW_CACHE[u]
444 self._review_protocol = info[0]
445 self._review_host = info[1]
446 self._review_port = info[2]
447 else:
448 try:
449 info = urlopen(u).read()
450 if info == 'NOT_AVAILABLE':
451 raise UploadError('Upload over ssh unavailable')
452 if '<' in info:
453 # Assume the server gave us some sort of HTML
454 # response back, like maybe a login page.
455 #
456 raise UploadError('Cannot read %s:\n%s' % (u, info))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800457
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700458 self._review_protocol = 'ssh'
459 self._review_host = info.split(" ")[0]
460 self._review_port = info.split(" ")[1]
461 except HTTPError, e:
462 if e.code == 404:
463 self._review_protocol = 'http-post'
464 self._review_host = None
465 self._review_port = None
466 else:
467 raise UploadError('Cannot guess Gerrit version')
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800468
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700469 REVIEW_CACHE[u] = (
470 self._review_protocol,
471 self._review_host,
472 self._review_port)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800473 return self._review_protocol
474
475 def SshReviewUrl(self, userEmail):
476 if self.ReviewProtocol != 'ssh':
477 return None
478 return 'ssh://%s@%s:%s/%s' % (
479 userEmail.split("@")[0],
480 self._review_host,
481 self._review_port,
482 self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700483
484 def ToLocal(self, rev):
485 """Convert a remote revision string to something we have locally.
486 """
487 if IsId(rev):
488 return rev
489 if rev.startswith(R_TAGS):
490 return rev
491
492 if not rev.startswith('refs/'):
493 rev = R_HEADS + rev
494
495 for spec in self.fetch:
496 if spec.SourceMatches(rev):
497 return spec.MapSource(rev)
498 raise GitError('remote %s does not have %s' % (self.name, rev))
499
500 def WritesTo(self, ref):
501 """True if the remote stores to the tracking ref.
502 """
503 for spec in self.fetch:
504 if spec.DestMatches(ref):
505 return True
506 return False
507
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800508 def ResetFetch(self, mirror=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700509 """Set the fetch refspec to its default value.
510 """
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800511 if mirror:
512 dst = 'refs/heads/*'
513 else:
514 dst = 'refs/remotes/%s/*' % self.name
515 self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700516
517 def Save(self):
518 """Save this remote to the configuration.
519 """
520 self._Set('url', self.url)
521 self._Set('review', self.review)
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800522 self._Set('projectname', self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700523 self._Set('fetch', map(lambda x: str(x), self.fetch))
524
525 def _Set(self, key, value):
526 key = 'remote.%s.%s' % (self.name, key)
527 return self._config.SetString(key, value)
528
529 def _Get(self, key, all=False):
530 key = 'remote.%s.%s' % (self.name, key)
531 return self._config.GetString(key, all = all)
532
533
534class Branch(object):
535 """Configuration options related to a single branch.
536 """
537 def __init__(self, config, name):
538 self._config = config
539 self.name = name
540 self.merge = self._Get('merge')
541
542 r = self._Get('remote')
543 if r:
544 self.remote = self._config.GetRemote(r)
545 else:
546 self.remote = None
547
548 @property
549 def LocalMerge(self):
550 """Convert the merge spec to a local name.
551 """
552 if self.remote and self.merge:
553 return self.remote.ToLocal(self.merge)
554 return None
555
556 def Save(self):
557 """Save this branch back into the configuration.
558 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700559 if self._config.HasSection('branch', self.name):
560 if self.remote:
561 self._Set('remote', self.remote.name)
562 else:
563 self._Set('remote', None)
564 self._Set('merge', self.merge)
565
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700566 else:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700567 fd = open(self._config.file, 'ab')
568 try:
569 fd.write('[branch "%s"]\n' % self.name)
570 if self.remote:
571 fd.write('\tremote = %s\n' % self.remote.name)
572 if self.merge:
573 fd.write('\tmerge = %s\n' % self.merge)
574 finally:
575 fd.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700576
577 def _Set(self, key, value):
578 key = 'branch.%s.%s' % (self.name, key)
579 return self._config.SetString(key, value)
580
581 def _Get(self, key, all=False):
582 key = 'branch.%s.%s' % (self.name, key)
583 return self._config.GetString(key, all = all)