blob: 7aad80d2a30ad43aea6f82bfae823d3abc84694c [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
19import sys
Shawn O. Pearceb54a3922009-01-05 16:18:58 -080020from urllib2 import urlopen, HTTPError
21from error import GitError, UploadError
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070022from trace import Trace
23from git_command import GitCommand
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024
25R_HEADS = 'refs/heads/'
26R_TAGS = 'refs/tags/'
27ID_RE = re.compile('^[0-9a-f]{40}$')
28
Shawn O. Pearce146fe902009-03-25 14:06:43 -070029REVIEW_CACHE = dict()
30
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070031def IsId(rev):
32 return ID_RE.match(rev)
33
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070034def _key(name):
35 parts = name.split('.')
36 if len(parts) < 2:
37 return name.lower()
38 parts[ 0] = parts[ 0].lower()
39 parts[-1] = parts[-1].lower()
40 return '.'.join(parts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041
42class GitConfig(object):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070043 _ForUser = None
44
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045 @classmethod
46 def ForUser(cls):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070047 if cls._ForUser is None:
48 cls._ForUser = cls(file = os.path.expanduser('~/.gitconfig'))
49 return cls._ForUser
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070050
51 @classmethod
52 def ForRepository(cls, gitdir, defaults=None):
53 return cls(file = os.path.join(gitdir, 'config'),
54 defaults = defaults)
55
56 def __init__(self, file, defaults=None):
57 self.file = file
58 self.defaults = defaults
59 self._cache_dict = None
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070060 self._section_dict = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061 self._remotes = {}
62 self._branches = {}
Shawn O. Pearcec12c3602009-04-17 21:03:32 -070063 self._pickle = os.path.join(
64 os.path.dirname(self.file),
65 '.repopickle_' + os.path.basename(self.file))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070066
67 def Has(self, name, include_defaults = True):
68 """Return true if this configuration file has the key.
69 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070070 if _key(name) in self._cache:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070071 return True
72 if include_defaults and self.defaults:
73 return self.defaults.Has(name, include_defaults = True)
74 return False
75
76 def GetBoolean(self, name):
77 """Returns a boolean from the configuration file.
78 None : The value was not defined, or is not a boolean.
79 True : The value was set to true or yes.
80 False: The value was set to false or no.
81 """
82 v = self.GetString(name)
83 if v is None:
84 return None
85 v = v.lower()
86 if v in ('true', 'yes'):
87 return True
88 if v in ('false', 'no'):
89 return False
90 return None
91
92 def GetString(self, name, all=False):
93 """Get the first value for a key, or None if it is not defined.
94
95 This configuration file is used first, if the key is not
96 defined or all = True then the defaults are also searched.
97 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070098 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070099 v = self._cache[_key(name)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100 except KeyError:
101 if self.defaults:
102 return self.defaults.GetString(name, all = all)
103 v = []
104
105 if not all:
106 if v:
107 return v[0]
108 return None
109
110 r = []
111 r.extend(v)
112 if self.defaults:
113 r.extend(self.defaults.GetString(name, all = True))
114 return r
115
116 def SetString(self, name, value):
117 """Set the value(s) for a key.
118 Only this configuration file is modified.
119
120 The supplied value should be either a string,
121 or a list of strings (to store multiple values).
122 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700123 key = _key(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124
125 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700126 old = self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127 except KeyError:
128 old = []
129
130 if value is None:
131 if old:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700132 del self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133 self._do('--unset-all', name)
134
135 elif isinstance(value, list):
136 if len(value) == 0:
137 self.SetString(name, None)
138
139 elif len(value) == 1:
140 self.SetString(name, value[0])
141
142 elif old != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700143 self._cache[key] = list(value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700144 self._do('--replace-all', name, value[0])
145 for i in xrange(1, len(value)):
146 self._do('--add', name, value[i])
147
148 elif len(old) != 1 or old[0] != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700149 self._cache[key] = [value]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700150 self._do('--replace-all', name, value)
151
152 def GetRemote(self, name):
153 """Get the remote.$name.* configuration values as an object.
154 """
155 try:
156 r = self._remotes[name]
157 except KeyError:
158 r = Remote(self, name)
159 self._remotes[r.name] = r
160 return r
161
162 def GetBranch(self, name):
163 """Get the branch.$name.* configuration values as an object.
164 """
165 try:
166 b = self._branches[name]
167 except KeyError:
168 b = Branch(self, name)
169 self._branches[b.name] = b
170 return b
171
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700172 def HasSection(self, section, subsection = ''):
173 """Does at least one key in section.subsection exist?
174 """
175 try:
176 return subsection in self._sections[section]
177 except KeyError:
178 return False
179
180 @property
181 def _sections(self):
182 d = self._section_dict
183 if d is None:
184 d = {}
185 for name in self._cache.keys():
186 p = name.split('.')
187 if 2 == len(p):
188 section = p[0]
189 subsect = ''
190 else:
191 section = p[0]
192 subsect = '.'.join(p[1:-1])
193 if section not in d:
194 d[section] = set()
195 d[section].add(subsect)
196 self._section_dict = d
197 return d
198
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199 @property
200 def _cache(self):
201 if self._cache_dict is None:
202 self._cache_dict = self._Read()
203 return self._cache_dict
204
205 def _Read(self):
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700206 d = self._ReadPickle()
207 if d is None:
208 d = self._ReadGit()
209 self._SavePickle(d)
210 return d
211
212 def _ReadPickle(self):
213 try:
214 if os.path.getmtime(self._pickle) \
215 <= os.path.getmtime(self.file):
216 os.remove(self._pickle)
217 return None
218 except OSError:
219 return None
220 try:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700221 Trace(': unpickle %s', self.file)
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700222 return cPickle.load(open(self._pickle, 'r'))
223 except IOError:
224 os.remove(self._pickle)
225 return None
226 except cPickle.PickleError:
227 os.remove(self._pickle)
228 return None
229
230 def _SavePickle(self, cache):
231 try:
232 cPickle.dump(cache,
233 open(self._pickle, 'w'),
234 cPickle.HIGHEST_PROTOCOL)
235 except IOError:
236 os.remove(self._pickle)
237 except cPickle.PickleError:
238 os.remove(self._pickle)
239
240 def _ReadGit(self):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700241 d = self._do('--null', '--list')
242 c = {}
243 while d:
244 lf = d.index('\n')
245 nul = d.index('\0', lf + 1)
246
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700247 key = _key(d[0:lf])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700248 val = d[lf + 1:nul]
249
250 if key in c:
251 c[key].append(val)
252 else:
253 c[key] = [val]
254
255 d = d[nul + 1:]
256 return c
257
258 def _do(self, *args):
259 command = ['config', '--file', self.file]
260 command.extend(args)
261
262 p = GitCommand(None,
263 command,
264 capture_stdout = True,
265 capture_stderr = True)
266 if p.Wait() == 0:
267 return p.stdout
268 else:
269 GitError('git config %s: %s' % (str(args), p.stderr))
270
271
272class RefSpec(object):
273 """A Git refspec line, split into its components:
274
275 forced: True if the line starts with '+'
276 src: Left side of the line
277 dst: Right side of the line
278 """
279
280 @classmethod
281 def FromString(cls, rs):
282 lhs, rhs = rs.split(':', 2)
283 if lhs.startswith('+'):
284 lhs = lhs[1:]
285 forced = True
286 else:
287 forced = False
288 return cls(forced, lhs, rhs)
289
290 def __init__(self, forced, lhs, rhs):
291 self.forced = forced
292 self.src = lhs
293 self.dst = rhs
294
295 def SourceMatches(self, rev):
296 if self.src:
297 if rev == self.src:
298 return True
299 if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
300 return True
301 return False
302
303 def DestMatches(self, ref):
304 if self.dst:
305 if ref == self.dst:
306 return True
307 if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
308 return True
309 return False
310
311 def MapSource(self, rev):
312 if self.src.endswith('/*'):
313 return self.dst[:-1] + rev[len(self.src) - 1:]
314 return self.dst
315
316 def __str__(self):
317 s = ''
318 if self.forced:
319 s += '+'
320 if self.src:
321 s += self.src
322 if self.dst:
323 s += ':'
324 s += self.dst
325 return s
326
327
328class Remote(object):
329 """Configuration options related to a remote.
330 """
331 def __init__(self, config, name):
332 self._config = config
333 self.name = name
334 self.url = self._Get('url')
335 self.review = self._Get('review')
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800336 self.projectname = self._Get('projectname')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 self.fetch = map(lambda x: RefSpec.FromString(x),
338 self._Get('fetch', all=True))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800339 self._review_protocol = None
340
341 @property
342 def ReviewProtocol(self):
343 if self._review_protocol is None:
344 if self.review is None:
345 return None
346
347 u = self.review
348 if not u.startswith('http:') and not u.startswith('https:'):
349 u = 'http://%s' % u
Shawn O. Pearce13cc3842009-03-25 13:54:54 -0700350 if u.endswith('/Gerrit'):
351 u = u[:len(u) - len('/Gerrit')]
352 if not u.endswith('/ssh_info'):
353 if not u.endswith('/'):
354 u += '/'
355 u += 'ssh_info'
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800356
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700357 if u in REVIEW_CACHE:
358 info = REVIEW_CACHE[u]
359 self._review_protocol = info[0]
360 self._review_host = info[1]
361 self._review_port = info[2]
362 else:
363 try:
364 info = urlopen(u).read()
365 if info == 'NOT_AVAILABLE':
366 raise UploadError('Upload over ssh unavailable')
367 if '<' in info:
368 # Assume the server gave us some sort of HTML
369 # response back, like maybe a login page.
370 #
371 raise UploadError('Cannot read %s:\n%s' % (u, info))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800372
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700373 self._review_protocol = 'ssh'
374 self._review_host = info.split(" ")[0]
375 self._review_port = info.split(" ")[1]
376 except HTTPError, e:
377 if e.code == 404:
378 self._review_protocol = 'http-post'
379 self._review_host = None
380 self._review_port = None
381 else:
382 raise UploadError('Cannot guess Gerrit version')
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800383
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700384 REVIEW_CACHE[u] = (
385 self._review_protocol,
386 self._review_host,
387 self._review_port)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800388 return self._review_protocol
389
390 def SshReviewUrl(self, userEmail):
391 if self.ReviewProtocol != 'ssh':
392 return None
393 return 'ssh://%s@%s:%s/%s' % (
394 userEmail.split("@")[0],
395 self._review_host,
396 self._review_port,
397 self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700398
399 def ToLocal(self, rev):
400 """Convert a remote revision string to something we have locally.
401 """
402 if IsId(rev):
403 return rev
404 if rev.startswith(R_TAGS):
405 return rev
406
407 if not rev.startswith('refs/'):
408 rev = R_HEADS + rev
409
410 for spec in self.fetch:
411 if spec.SourceMatches(rev):
412 return spec.MapSource(rev)
413 raise GitError('remote %s does not have %s' % (self.name, rev))
414
415 def WritesTo(self, ref):
416 """True if the remote stores to the tracking ref.
417 """
418 for spec in self.fetch:
419 if spec.DestMatches(ref):
420 return True
421 return False
422
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800423 def ResetFetch(self, mirror=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700424 """Set the fetch refspec to its default value.
425 """
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800426 if mirror:
427 dst = 'refs/heads/*'
428 else:
429 dst = 'refs/remotes/%s/*' % self.name
430 self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700431
432 def Save(self):
433 """Save this remote to the configuration.
434 """
435 self._Set('url', self.url)
436 self._Set('review', self.review)
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800437 self._Set('projectname', self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700438 self._Set('fetch', map(lambda x: str(x), self.fetch))
439
440 def _Set(self, key, value):
441 key = 'remote.%s.%s' % (self.name, key)
442 return self._config.SetString(key, value)
443
444 def _Get(self, key, all=False):
445 key = 'remote.%s.%s' % (self.name, key)
446 return self._config.GetString(key, all = all)
447
448
449class Branch(object):
450 """Configuration options related to a single branch.
451 """
452 def __init__(self, config, name):
453 self._config = config
454 self.name = name
455 self.merge = self._Get('merge')
456
457 r = self._Get('remote')
458 if r:
459 self.remote = self._config.GetRemote(r)
460 else:
461 self.remote = None
462
463 @property
464 def LocalMerge(self):
465 """Convert the merge spec to a local name.
466 """
467 if self.remote and self.merge:
468 return self.remote.ToLocal(self.merge)
469 return None
470
471 def Save(self):
472 """Save this branch back into the configuration.
473 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700474 if self._config.HasSection('branch', self.name):
475 if self.remote:
476 self._Set('remote', self.remote.name)
477 else:
478 self._Set('remote', None)
479 self._Set('merge', self.merge)
480
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700481 else:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700482 fd = open(self._config.file, 'ab')
483 try:
484 fd.write('[branch "%s"]\n' % self.name)
485 if self.remote:
486 fd.write('\tremote = %s\n' % self.remote.name)
487 if self.merge:
488 fd.write('\tmerge = %s\n' % self.merge)
489 finally:
490 fd.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700491
492 def _Set(self, key, value):
493 key = 'branch.%s.%s' % (self.name, key)
494 return self._config.SetString(key, value)
495
496 def _Get(self, key, all=False):
497 key = 'branch.%s.%s' % (self.name, key)
498 return self._config.GetString(key, all = all)