blob: 138470c5c8060fb4cd1075ee97a9bde1b6f97b20 [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. Pearceca8c32c2010-05-11 18:21:33 -070026
27from git_command import GitCommand
28from git_command import ssh_sock
29from git_command import terminate_ssh_clients
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
31R_HEADS = 'refs/heads/'
32R_TAGS = 'refs/tags/'
33ID_RE = re.compile('^[0-9a-f]{40}$')
34
Shawn O. Pearce146fe902009-03-25 14:06:43 -070035REVIEW_CACHE = dict()
36
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070037def IsId(rev):
38 return ID_RE.match(rev)
39
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070040def _key(name):
41 parts = name.split('.')
42 if len(parts) < 2:
43 return name.lower()
44 parts[ 0] = parts[ 0].lower()
45 parts[-1] = parts[-1].lower()
46 return '.'.join(parts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070047
48class GitConfig(object):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070049 _ForUser = None
50
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070051 @classmethod
52 def ForUser(cls):
Shawn O. Pearce90be5c02008-10-29 15:21:24 -070053 if cls._ForUser is None:
54 cls._ForUser = cls(file = os.path.expanduser('~/.gitconfig'))
55 return cls._ForUser
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070056
57 @classmethod
58 def ForRepository(cls, gitdir, defaults=None):
59 return cls(file = os.path.join(gitdir, 'config'),
60 defaults = defaults)
61
Shawn O. Pearce1b34c912009-05-21 18:52:49 -070062 def __init__(self, file, defaults=None, pickleFile=None):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063 self.file = file
64 self.defaults = defaults
65 self._cache_dict = None
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -070066 self._section_dict = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070067 self._remotes = {}
68 self._branches = {}
Shawn O. Pearce1b34c912009-05-21 18:52:49 -070069
70 if pickleFile is None:
71 self._pickle = os.path.join(
72 os.path.dirname(self.file),
73 '.repopickle_' + os.path.basename(self.file))
74 else:
75 self._pickle = pickleFile
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070076
77 def Has(self, name, include_defaults = True):
78 """Return true if this configuration file has the key.
79 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -070080 if _key(name) in self._cache:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070081 return True
82 if include_defaults and self.defaults:
83 return self.defaults.Has(name, include_defaults = True)
84 return False
85
86 def GetBoolean(self, name):
87 """Returns a boolean from the configuration file.
88 None : The value was not defined, or is not a boolean.
89 True : The value was set to true or yes.
90 False: The value was set to false or no.
91 """
92 v = self.GetString(name)
93 if v is None:
94 return None
95 v = v.lower()
96 if v in ('true', 'yes'):
97 return True
98 if v in ('false', 'no'):
99 return False
100 return None
101
102 def GetString(self, name, all=False):
103 """Get the first value for a key, or None if it is not defined.
104
105 This configuration file is used first, if the key is not
106 defined or all = True then the defaults are also searched.
107 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700108 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700109 v = self._cache[_key(name)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110 except KeyError:
111 if self.defaults:
112 return self.defaults.GetString(name, all = all)
113 v = []
114
115 if not all:
116 if v:
117 return v[0]
118 return None
119
120 r = []
121 r.extend(v)
122 if self.defaults:
123 r.extend(self.defaults.GetString(name, all = True))
124 return r
125
126 def SetString(self, name, value):
127 """Set the value(s) for a key.
128 Only this configuration file is modified.
129
130 The supplied value should be either a string,
131 or a list of strings (to store multiple values).
132 """
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700133 key = _key(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134
135 try:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700136 old = self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137 except KeyError:
138 old = []
139
140 if value is None:
141 if old:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700142 del self._cache[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700143 self._do('--unset-all', name)
144
145 elif isinstance(value, list):
146 if len(value) == 0:
147 self.SetString(name, None)
148
149 elif len(value) == 1:
150 self.SetString(name, value[0])
151
152 elif old != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700153 self._cache[key] = list(value)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700154 self._do('--replace-all', name, value[0])
155 for i in xrange(1, len(value)):
156 self._do('--add', name, value[i])
157
158 elif len(old) != 1 or old[0] != value:
Shawn O. Pearcef8e32732009-04-17 11:00:31 -0700159 self._cache[key] = [value]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160 self._do('--replace-all', name, value)
161
162 def GetRemote(self, name):
163 """Get the remote.$name.* configuration values as an object.
164 """
165 try:
166 r = self._remotes[name]
167 except KeyError:
168 r = Remote(self, name)
169 self._remotes[r.name] = r
170 return r
171
172 def GetBranch(self, name):
173 """Get the branch.$name.* configuration values as an object.
174 """
175 try:
176 b = self._branches[name]
177 except KeyError:
178 b = Branch(self, name)
179 self._branches[b.name] = b
180 return b
181
Shawn O. Pearce366ad212009-05-19 12:47:37 -0700182 def GetSubSections(self, section):
183 """List all subsection names matching $section.*.*
184 """
185 return self._sections.get(section, set())
186
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700187 def HasSection(self, section, subsection = ''):
188 """Does at least one key in section.subsection exist?
189 """
190 try:
191 return subsection in self._sections[section]
192 except KeyError:
193 return False
194
195 @property
196 def _sections(self):
197 d = self._section_dict
198 if d is None:
199 d = {}
200 for name in self._cache.keys():
201 p = name.split('.')
202 if 2 == len(p):
203 section = p[0]
204 subsect = ''
205 else:
206 section = p[0]
207 subsect = '.'.join(p[1:-1])
208 if section not in d:
209 d[section] = set()
210 d[section].add(subsect)
211 self._section_dict = d
212 return d
213
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214 @property
215 def _cache(self):
216 if self._cache_dict is None:
217 self._cache_dict = self._Read()
218 return self._cache_dict
219
220 def _Read(self):
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700221 d = self._ReadPickle()
222 if d is None:
223 d = self._ReadGit()
224 self._SavePickle(d)
225 return d
226
227 def _ReadPickle(self):
228 try:
229 if os.path.getmtime(self._pickle) \
230 <= os.path.getmtime(self.file):
231 os.remove(self._pickle)
232 return None
233 except OSError:
234 return None
235 try:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700236 Trace(': unpickle %s', self.file)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700237 fd = open(self._pickle, 'rb')
238 try:
239 return cPickle.load(fd)
240 finally:
241 fd.close()
Shawn O. Pearce2a3a81b2009-06-12 09:10:07 -0700242 except EOFError:
243 os.remove(self._pickle)
244 return None
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700245 except IOError:
246 os.remove(self._pickle)
247 return None
248 except cPickle.PickleError:
249 os.remove(self._pickle)
250 return None
251
252 def _SavePickle(self, cache):
253 try:
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -0700254 fd = open(self._pickle, 'wb')
255 try:
256 cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
257 finally:
258 fd.close()
Shawn O. Pearcec12c3602009-04-17 21:03:32 -0700259 except IOError:
260 os.remove(self._pickle)
261 except cPickle.PickleError:
262 os.remove(self._pickle)
263
264 def _ReadGit(self):
David Aguilar438c5472009-06-28 15:09:16 -0700265 """
266 Read configuration data from git.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
David Aguilar438c5472009-06-28 15:09:16 -0700268 This internal method populates the GitConfig cache.
269
270 """
David Aguilar438c5472009-06-28 15:09:16 -0700271 c = {}
Shawn O. Pearcec24c7202009-07-02 16:12:57 -0700272 d = self._do('--null', '--list')
273 if d is None:
274 return c
275 for line in d.rstrip('\0').split('\0'):
David Aguilar438c5472009-06-28 15:09:16 -0700276 if '\n' in line:
277 key, val = line.split('\n', 1)
278 else:
279 key = line
280 val = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281
282 if key in c:
283 c[key].append(val)
284 else:
285 c[key] = [val]
286
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700287 return c
288
289 def _do(self, *args):
290 command = ['config', '--file', self.file]
291 command.extend(args)
292
293 p = GitCommand(None,
294 command,
295 capture_stdout = True,
296 capture_stderr = True)
297 if p.Wait() == 0:
298 return p.stdout
299 else:
300 GitError('git config %s: %s' % (str(args), p.stderr))
301
302
303class RefSpec(object):
304 """A Git refspec line, split into its components:
305
306 forced: True if the line starts with '+'
307 src: Left side of the line
308 dst: Right side of the line
309 """
310
311 @classmethod
312 def FromString(cls, rs):
313 lhs, rhs = rs.split(':', 2)
314 if lhs.startswith('+'):
315 lhs = lhs[1:]
316 forced = True
317 else:
318 forced = False
319 return cls(forced, lhs, rhs)
320
321 def __init__(self, forced, lhs, rhs):
322 self.forced = forced
323 self.src = lhs
324 self.dst = rhs
325
326 def SourceMatches(self, rev):
327 if self.src:
328 if rev == self.src:
329 return True
330 if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
331 return True
332 return False
333
334 def DestMatches(self, ref):
335 if self.dst:
336 if ref == self.dst:
337 return True
338 if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
339 return True
340 return False
341
342 def MapSource(self, rev):
343 if self.src.endswith('/*'):
344 return self.dst[:-1] + rev[len(self.src) - 1:]
345 return self.dst
346
347 def __str__(self):
348 s = ''
349 if self.forced:
350 s += '+'
351 if self.src:
352 s += self.src
353 if self.dst:
354 s += ':'
355 s += self.dst
356 return s
357
358
Doug Anderson06d029c2010-10-27 17:06:01 -0700359_master_processes = []
360_master_keys = set()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700361_ssh_master = True
362
Josh Guilfoyle71985722009-08-16 09:44:40 -0700363def _open_ssh(host, port=None):
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700364 global _ssh_master
365
Doug Anderson06d029c2010-10-27 17:06:01 -0700366 # Check to see whether we already think that the master is running; if we
367 # think it's already running, return right away.
Josh Guilfoyle71985722009-08-16 09:44:40 -0700368 if port is not None:
369 key = '%s:%s' % (host, port)
370 else:
371 key = host
372
Doug Anderson06d029c2010-10-27 17:06:01 -0700373 if key in _master_keys:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700374 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
Doug Anderson06d029c2010-10-27 17:06:01 -0700383 # We will make two calls to ssh; this is the common part of both calls.
384 command_base = ['ssh',
385 '-o','ControlPath %s' % ssh_sock(),
386 host]
Josh Guilfoyle71985722009-08-16 09:44:40 -0700387 if port is not None:
Doug Anderson06d029c2010-10-27 17:06:01 -0700388 command_base[1:1] = ['-p',str(port)]
Josh Guilfoyle71985722009-08-16 09:44:40 -0700389
Doug Anderson06d029c2010-10-27 17:06:01 -0700390 # Since the key wasn't in _master_keys, we think that master isn't running.
391 # ...but before actually starting a master, we'll double-check. This can
392 # be important because we can't tell that that 'git@myhost.com' is the same
393 # as 'myhost.com' where "User git" is setup in the user's ~/.ssh/config file.
394 check_command = command_base + ['-O','check']
395 try:
396 Trace(': %s', ' '.join(check_command))
397 check_process = subprocess.Popen(check_command,
398 stdout=subprocess.PIPE,
399 stderr=subprocess.PIPE)
400 check_process.communicate() # read output, but ignore it...
401 isnt_running = check_process.wait()
402
403 if not isnt_running:
404 # Our double-check found that the master _was_ infact running. Add to
405 # the list of keys.
406 _master_keys.add(key)
407 return True
408 except Exception:
409 # Ignore excpetions. We we will fall back to the normal command and print
410 # to the log there.
411 pass
412
413 command = command_base[:1] + \
414 ['-M', '-N'] + \
415 command_base[1:]
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700416 try:
417 Trace(': %s', ' '.join(command))
418 p = subprocess.Popen(command)
419 except Exception, e:
420 _ssh_master = False
421 print >>sys.stderr, \
422 '\nwarn: cannot enable ssh control master for %s:%s\n%s' \
423 % (host,port, str(e))
424 return False
425
Doug Anderson06d029c2010-10-27 17:06:01 -0700426 _master_processes.append(p)
427 _master_keys.add(key)
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700428 time.sleep(1)
429 return True
430
431def close_ssh():
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700432 terminate_ssh_clients()
433
Doug Anderson06d029c2010-10-27 17:06:01 -0700434 for p in _master_processes:
Shawn O. Pearce26120ca2009-06-16 11:49:10 -0700435 try:
436 os.kill(p.pid, SIGTERM)
437 p.wait()
Shawn O. Pearcefb5c8fd2009-06-16 14:57:46 -0700438 except OSError:
Shawn O. Pearce26120ca2009-06-16 11:49:10 -0700439 pass
Doug Anderson06d029c2010-10-27 17:06:01 -0700440 del _master_processes[:]
441 _master_keys.clear()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700442
Nico Sallembien1c85f4e2010-04-27 14:35:27 -0700443 d = ssh_sock(create=False)
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700444 if d:
445 try:
446 os.rmdir(os.path.dirname(d))
447 except OSError:
448 pass
449
450URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
Shawn O. Pearce2f968c92009-04-30 14:30:28 -0700451URI_ALL = re.compile(r'^([a-z][a-z+]*)://([^@/]*@?[^/]*)/')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700452
453def _preconnect(url):
454 m = URI_ALL.match(url)
455 if m:
456 scheme = m.group(1)
457 host = m.group(2)
458 if ':' in host:
459 host, port = host.split(':')
Shawn O. Pearce896d5df2009-04-21 14:51:04 -0700460 else:
Josh Guilfoyle71985722009-08-16 09:44:40 -0700461 port = None
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700462 if scheme in ('ssh', 'git+ssh', 'ssh+git'):
463 return _open_ssh(host, port)
464 return False
465
466 m = URI_SCP.match(url)
467 if m:
468 host = m.group(1)
Josh Guilfoyle71985722009-08-16 09:44:40 -0700469 return _open_ssh(host)
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700470
Shawn O. Pearce7b4f4352009-06-12 09:06:35 -0700471 return False
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700472
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700473class Remote(object):
474 """Configuration options related to a remote.
475 """
476 def __init__(self, config, name):
477 self._config = config
478 self.name = name
479 self.url = self._Get('url')
480 self.review = self._Get('review')
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800481 self.projectname = self._Get('projectname')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700482 self.fetch = map(lambda x: RefSpec.FromString(x),
483 self._Get('fetch', all=True))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800484 self._review_protocol = None
485
Ulrik Sjolinb6ea3bf2010-01-03 18:20:17 +0100486 def _InsteadOf(self):
487 globCfg = GitConfig.ForUser()
488 urlList = globCfg.GetSubSections('url')
489 longest = ""
490 longestUrl = ""
491
492 for url in urlList:
493 key = "url." + url + ".insteadOf"
494 insteadOfList = globCfg.GetString(key, all=True)
495
496 for insteadOf in insteadOfList:
497 if self.url.startswith(insteadOf) \
498 and len(insteadOf) > len(longest):
499 longest = insteadOf
500 longestUrl = url
501
502 if len(longest) == 0:
503 return self.url
504
505 return self.url.replace(longest, longestUrl, 1)
506
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700507 def PreConnectFetch(self):
Ulrik Sjolinb6ea3bf2010-01-03 18:20:17 +0100508 connectionUrl = self._InsteadOf()
509 return _preconnect(connectionUrl)
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700510
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800511 @property
512 def ReviewProtocol(self):
513 if self._review_protocol is None:
514 if self.review is None:
515 return None
516
517 u = self.review
518 if not u.startswith('http:') and not u.startswith('https:'):
519 u = 'http://%s' % u
Shawn O. Pearce13cc3842009-03-25 13:54:54 -0700520 if u.endswith('/Gerrit'):
521 u = u[:len(u) - len('/Gerrit')]
522 if not u.endswith('/ssh_info'):
523 if not u.endswith('/'):
524 u += '/'
525 u += 'ssh_info'
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800526
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700527 if u in REVIEW_CACHE:
528 info = REVIEW_CACHE[u]
529 self._review_protocol = info[0]
530 self._review_host = info[1]
531 self._review_port = info[2]
532 else:
533 try:
534 info = urlopen(u).read()
535 if info == 'NOT_AVAILABLE':
536 raise UploadError('Upload over ssh unavailable')
537 if '<' in info:
538 # Assume the server gave us some sort of HTML
539 # response back, like maybe a login page.
540 #
541 raise UploadError('Cannot read %s:\n%s' % (u, info))
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800542
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700543 self._review_protocol = 'ssh'
544 self._review_host = info.split(" ")[0]
545 self._review_port = info.split(" ")[1]
546 except HTTPError, e:
547 if e.code == 404:
548 self._review_protocol = 'http-post'
549 self._review_host = None
550 self._review_port = None
551 else:
552 raise UploadError('Cannot guess Gerrit version')
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800553
Shawn O. Pearce146fe902009-03-25 14:06:43 -0700554 REVIEW_CACHE[u] = (
555 self._review_protocol,
556 self._review_host,
557 self._review_port)
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800558 return self._review_protocol
559
560 def SshReviewUrl(self, userEmail):
561 if self.ReviewProtocol != 'ssh':
562 return None
Shawn O. Pearce3575b8f2010-07-15 17:00:14 -0700563 username = self._config.GetString('review.%s.username' % self.review)
564 if username is None:
565 username = userEmail.split("@")[0]
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800566 return 'ssh://%s@%s:%s/%s' % (
Shawn O. Pearce3575b8f2010-07-15 17:00:14 -0700567 username,
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800568 self._review_host,
569 self._review_port,
570 self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700571
572 def ToLocal(self, rev):
573 """Convert a remote revision string to something we have locally.
574 """
575 if IsId(rev):
576 return rev
577 if rev.startswith(R_TAGS):
578 return rev
579
580 if not rev.startswith('refs/'):
581 rev = R_HEADS + rev
582
583 for spec in self.fetch:
584 if spec.SourceMatches(rev):
585 return spec.MapSource(rev)
586 raise GitError('remote %s does not have %s' % (self.name, rev))
587
588 def WritesTo(self, ref):
589 """True if the remote stores to the tracking ref.
590 """
591 for spec in self.fetch:
592 if spec.DestMatches(ref):
593 return True
594 return False
595
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800596 def ResetFetch(self, mirror=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700597 """Set the fetch refspec to its default value.
598 """
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800599 if mirror:
600 dst = 'refs/heads/*'
601 else:
602 dst = 'refs/remotes/%s/*' % self.name
603 self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700604
605 def Save(self):
606 """Save this remote to the configuration.
607 """
608 self._Set('url', self.url)
609 self._Set('review', self.review)
Shawn O. Pearce339ba9f2008-11-06 09:52:51 -0800610 self._Set('projectname', self.projectname)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700611 self._Set('fetch', map(lambda x: str(x), self.fetch))
612
613 def _Set(self, key, value):
614 key = 'remote.%s.%s' % (self.name, key)
615 return self._config.SetString(key, value)
616
617 def _Get(self, key, all=False):
618 key = 'remote.%s.%s' % (self.name, key)
619 return self._config.GetString(key, all = all)
620
621
622class Branch(object):
623 """Configuration options related to a single branch.
624 """
625 def __init__(self, config, name):
626 self._config = config
627 self.name = name
628 self.merge = self._Get('merge')
629
630 r = self._Get('remote')
631 if r:
632 self.remote = self._config.GetRemote(r)
633 else:
634 self.remote = None
635
636 @property
637 def LocalMerge(self):
638 """Convert the merge spec to a local name.
639 """
640 if self.remote and self.merge:
641 return self.remote.ToLocal(self.merge)
642 return None
643
644 def Save(self):
645 """Save this branch back into the configuration.
646 """
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700647 if self._config.HasSection('branch', self.name):
648 if self.remote:
649 self._Set('remote', self.remote.name)
650 else:
651 self._Set('remote', None)
652 self._Set('merge', self.merge)
653
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700654 else:
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700655 fd = open(self._config.file, 'ab')
656 try:
657 fd.write('[branch "%s"]\n' % self.name)
658 if self.remote:
659 fd.write('\tremote = %s\n' % self.remote.name)
660 if self.merge:
661 fd.write('\tmerge = %s\n' % self.merge)
662 finally:
663 fd.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700664
665 def _Set(self, key, value):
666 key = 'branch.%s.%s' % (self.name, key)
667 return self._config.SetString(key, value)
668
669 def _Get(self, key, all=False):
670 key = 'branch.%s.%s' % (self.name, key)
671 return self._config.GetString(key, all = all)