git_config.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. #
  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. from __future__ import print_function
  16. import contextlib
  17. import errno
  18. import json
  19. import os
  20. import re
  21. import subprocess
  22. import sys
  23. try:
  24. import threading as _threading
  25. except ImportError:
  26. import dummy_threading as _threading
  27. import time
  28. from pyversion import is_python3
  29. if is_python3():
  30. import urllib.request
  31. import urllib.error
  32. else:
  33. import urllib2
  34. import imp
  35. urllib = imp.new_module('urllib')
  36. urllib.request = urllib2
  37. urllib.error = urllib2
  38. from signal import SIGTERM
  39. from error import GitError, UploadError
  40. from trace import Trace
  41. if is_python3():
  42. from http.client import HTTPException
  43. else:
  44. from httplib import HTTPException
  45. from git_command import GitCommand
  46. from git_command import ssh_sock
  47. from git_command import terminate_ssh_clients
  48. from git_refs import R_CHANGES, R_HEADS, R_TAGS
  49. ID_RE = re.compile(r'^[0-9a-f]{40}$')
  50. REVIEW_CACHE = dict()
  51. def IsChange(rev):
  52. return rev.startswith(R_CHANGES)
  53. def IsId(rev):
  54. return ID_RE.match(rev)
  55. def IsTag(rev):
  56. return rev.startswith(R_TAGS)
  57. def IsImmutable(rev):
  58. return IsChange(rev) or IsId(rev) or IsTag(rev)
  59. def _key(name):
  60. parts = name.split('.')
  61. if len(parts) < 2:
  62. return name.lower()
  63. parts[ 0] = parts[ 0].lower()
  64. parts[-1] = parts[-1].lower()
  65. return '.'.join(parts)
  66. class GitConfig(object):
  67. _ForUser = None
  68. @classmethod
  69. def ForUser(cls):
  70. if cls._ForUser is None:
  71. cls._ForUser = cls(configfile = os.path.expanduser('~/.gitconfig'))
  72. return cls._ForUser
  73. @classmethod
  74. def ForRepository(cls, gitdir, defaults=None):
  75. return cls(configfile = os.path.join(gitdir, 'config'),
  76. defaults = defaults)
  77. def __init__(self, configfile, defaults=None, jsonFile=None):
  78. self.file = configfile
  79. self.defaults = defaults
  80. self._cache_dict = None
  81. self._section_dict = None
  82. self._remotes = {}
  83. self._branches = {}
  84. self._json = jsonFile
  85. if self._json is None:
  86. self._json = os.path.join(
  87. os.path.dirname(self.file),
  88. '.repo_' + os.path.basename(self.file) + '.json')
  89. def Has(self, name, include_defaults = True):
  90. """Return true if this configuration file has the key.
  91. """
  92. if _key(name) in self._cache:
  93. return True
  94. if include_defaults and self.defaults:
  95. return self.defaults.Has(name, include_defaults = True)
  96. return False
  97. def GetBoolean(self, name):
  98. """Returns a boolean from the configuration file.
  99. None : The value was not defined, or is not a boolean.
  100. True : The value was set to true or yes.
  101. False: The value was set to false or no.
  102. """
  103. v = self.GetString(name)
  104. if v is None:
  105. return None
  106. v = v.lower()
  107. if v in ('true', 'yes'):
  108. return True
  109. if v in ('false', 'no'):
  110. return False
  111. return None
  112. def GetString(self, name, all_keys=False):
  113. """Get the first value for a key, or None if it is not defined.
  114. This configuration file is used first, if the key is not
  115. defined or all_keys = True then the defaults are also searched.
  116. """
  117. try:
  118. v = self._cache[_key(name)]
  119. except KeyError:
  120. if self.defaults:
  121. return self.defaults.GetString(name, all_keys = all_keys)
  122. v = []
  123. if not all_keys:
  124. if v:
  125. return v[0]
  126. return None
  127. r = []
  128. r.extend(v)
  129. if self.defaults:
  130. r.extend(self.defaults.GetString(name, all_keys = True))
  131. return r
  132. def SetString(self, name, value):
  133. """Set the value(s) for a key.
  134. Only this configuration file is modified.
  135. The supplied value should be either a string,
  136. or a list of strings (to store multiple values).
  137. """
  138. key = _key(name)
  139. try:
  140. old = self._cache[key]
  141. except KeyError:
  142. old = []
  143. if value is None:
  144. if old:
  145. del self._cache[key]
  146. self._do('--unset-all', name)
  147. elif isinstance(value, list):
  148. if len(value) == 0:
  149. self.SetString(name, None)
  150. elif len(value) == 1:
  151. self.SetString(name, value[0])
  152. elif old != value:
  153. self._cache[key] = list(value)
  154. self._do('--replace-all', name, value[0])
  155. for i in range(1, len(value)):
  156. self._do('--add', name, value[i])
  157. elif len(old) != 1 or old[0] != value:
  158. self._cache[key] = [value]
  159. self._do('--replace-all', name, value)
  160. def GetRemote(self, name):
  161. """Get the remote.$name.* configuration values as an object.
  162. """
  163. try:
  164. r = self._remotes[name]
  165. except KeyError:
  166. r = Remote(self, name)
  167. self._remotes[r.name] = r
  168. return r
  169. def GetBranch(self, name):
  170. """Get the branch.$name.* configuration values as an object.
  171. """
  172. try:
  173. b = self._branches[name]
  174. except KeyError:
  175. b = Branch(self, name)
  176. self._branches[b.name] = b
  177. return b
  178. def GetSubSections(self, section):
  179. """List all subsection names matching $section.*.*
  180. """
  181. return self._sections.get(section, set())
  182. def HasSection(self, section, subsection = ''):
  183. """Does at least one key in section.subsection exist?
  184. """
  185. try:
  186. return subsection in self._sections[section]
  187. except KeyError:
  188. return False
  189. def UrlInsteadOf(self, url):
  190. """Resolve any url.*.insteadof references.
  191. """
  192. for new_url in self.GetSubSections('url'):
  193. for old_url in self.GetString('url.%s.insteadof' % new_url, True):
  194. if old_url is not None and url.startswith(old_url):
  195. return new_url + url[len(old_url):]
  196. return url
  197. @property
  198. def _sections(self):
  199. d = self._section_dict
  200. if d is None:
  201. d = {}
  202. for name in self._cache.keys():
  203. p = name.split('.')
  204. if 2 == len(p):
  205. section = p[0]
  206. subsect = ''
  207. else:
  208. section = p[0]
  209. subsect = '.'.join(p[1:-1])
  210. if section not in d:
  211. d[section] = set()
  212. d[section].add(subsect)
  213. self._section_dict = d
  214. return d
  215. @property
  216. def _cache(self):
  217. if self._cache_dict is None:
  218. self._cache_dict = self._Read()
  219. return self._cache_dict
  220. def _Read(self):
  221. d = self._ReadJson()
  222. if d is None:
  223. d = self._ReadGit()
  224. self._SaveJson(d)
  225. return d
  226. def _ReadJson(self):
  227. try:
  228. if os.path.getmtime(self._json) \
  229. <= os.path.getmtime(self.file):
  230. os.remove(self._json)
  231. return None
  232. except OSError:
  233. return None
  234. try:
  235. Trace(': parsing %s', self.file)
  236. fd = open(self._json)
  237. try:
  238. return json.load(fd)
  239. finally:
  240. fd.close()
  241. except (IOError, ValueError):
  242. os.remove(self._json)
  243. return None
  244. def _SaveJson(self, cache):
  245. try:
  246. fd = open(self._json, 'w')
  247. try:
  248. json.dump(cache, fd, indent=2)
  249. finally:
  250. fd.close()
  251. except (IOError, TypeError):
  252. if os.path.exists(self._json):
  253. os.remove(self._json)
  254. def _ReadGit(self):
  255. """
  256. Read configuration data from git.
  257. This internal method populates the GitConfig cache.
  258. """
  259. c = {}
  260. d = self._do('--null', '--list')
  261. if d is None:
  262. return c
  263. for line in d.decode('utf-8').rstrip('\0').split('\0'): # pylint: disable=W1401
  264. # Backslash is not anomalous
  265. if '\n' in line:
  266. key, val = line.split('\n', 1)
  267. else:
  268. key = line
  269. val = None
  270. if key in c:
  271. c[key].append(val)
  272. else:
  273. c[key] = [val]
  274. return c
  275. def _do(self, *args):
  276. command = ['config', '--file', self.file]
  277. command.extend(args)
  278. p = GitCommand(None,
  279. command,
  280. capture_stdout = True,
  281. capture_stderr = True)
  282. if p.Wait() == 0:
  283. return p.stdout
  284. else:
  285. GitError('git config %s: %s' % (str(args), p.stderr))
  286. class RefSpec(object):
  287. """A Git refspec line, split into its components:
  288. forced: True if the line starts with '+'
  289. src: Left side of the line
  290. dst: Right side of the line
  291. """
  292. @classmethod
  293. def FromString(cls, rs):
  294. lhs, rhs = rs.split(':', 2)
  295. if lhs.startswith('+'):
  296. lhs = lhs[1:]
  297. forced = True
  298. else:
  299. forced = False
  300. return cls(forced, lhs, rhs)
  301. def __init__(self, forced, lhs, rhs):
  302. self.forced = forced
  303. self.src = lhs
  304. self.dst = rhs
  305. def SourceMatches(self, rev):
  306. if self.src:
  307. if rev == self.src:
  308. return True
  309. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  310. return True
  311. return False
  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. def MapSource(self, rev):
  320. if self.src.endswith('/*'):
  321. return self.dst[:-1] + rev[len(self.src) - 1:]
  322. return self.dst
  323. def __str__(self):
  324. s = ''
  325. if self.forced:
  326. s += '+'
  327. if self.src:
  328. s += self.src
  329. if self.dst:
  330. s += ':'
  331. s += self.dst
  332. return s
  333. _master_processes = []
  334. _master_keys = set()
  335. _ssh_master = True
  336. _master_keys_lock = None
  337. def init_ssh():
  338. """Should be called once at the start of repo to init ssh master handling.
  339. At the moment, all we do is to create our lock.
  340. """
  341. global _master_keys_lock
  342. assert _master_keys_lock is None, "Should only call init_ssh once"
  343. _master_keys_lock = _threading.Lock()
  344. def _open_ssh(host, port=None):
  345. global _ssh_master
  346. # Acquire the lock. This is needed to prevent opening multiple masters for
  347. # the same host when we're running "repo sync -jN" (for N > 1) _and_ the
  348. # manifest <remote fetch="ssh://xyz"> specifies a different host from the
  349. # one that was passed to repo init.
  350. _master_keys_lock.acquire()
  351. try:
  352. # Check to see whether we already think that the master is running; if we
  353. # think it's already running, return right away.
  354. if port is not None:
  355. key = '%s:%s' % (host, port)
  356. else:
  357. key = host
  358. if key in _master_keys:
  359. return True
  360. if not _ssh_master \
  361. or 'GIT_SSH' in os.environ \
  362. or sys.platform in ('win32', 'cygwin'):
  363. # failed earlier, or cygwin ssh can't do this
  364. #
  365. return False
  366. # We will make two calls to ssh; this is the common part of both calls.
  367. command_base = ['ssh',
  368. '-o','ControlPath %s' % ssh_sock(),
  369. host]
  370. if port is not None:
  371. command_base[1:1] = ['-p', str(port)]
  372. # Since the key wasn't in _master_keys, we think that master isn't running.
  373. # ...but before actually starting a master, we'll double-check. This can
  374. # be important because we can't tell that that 'git@myhost.com' is the same
  375. # as 'myhost.com' where "User git" is setup in the user's ~/.ssh/config file.
  376. check_command = command_base + ['-O','check']
  377. try:
  378. Trace(': %s', ' '.join(check_command))
  379. check_process = subprocess.Popen(check_command,
  380. stdout=subprocess.PIPE,
  381. stderr=subprocess.PIPE)
  382. check_process.communicate() # read output, but ignore it...
  383. isnt_running = check_process.wait()
  384. if not isnt_running:
  385. # Our double-check found that the master _was_ infact running. Add to
  386. # the list of keys.
  387. _master_keys.add(key)
  388. return True
  389. except Exception:
  390. # Ignore excpetions. We we will fall back to the normal command and print
  391. # to the log there.
  392. pass
  393. command = command_base[:1] + \
  394. ['-M', '-N'] + \
  395. command_base[1:]
  396. try:
  397. Trace(': %s', ' '.join(command))
  398. p = subprocess.Popen(command)
  399. except Exception as e:
  400. _ssh_master = False
  401. print('\nwarn: cannot enable ssh control master for %s:%s\n%s'
  402. % (host,port, str(e)), file=sys.stderr)
  403. return False
  404. time.sleep(1)
  405. ssh_died = (p.poll() is not None)
  406. if ssh_died:
  407. return False
  408. _master_processes.append(p)
  409. _master_keys.add(key)
  410. return True
  411. finally:
  412. _master_keys_lock.release()
  413. def close_ssh():
  414. global _master_keys_lock
  415. terminate_ssh_clients()
  416. for p in _master_processes:
  417. try:
  418. os.kill(p.pid, SIGTERM)
  419. p.wait()
  420. except OSError:
  421. pass
  422. del _master_processes[:]
  423. _master_keys.clear()
  424. d = ssh_sock(create=False)
  425. if d:
  426. try:
  427. os.rmdir(os.path.dirname(d))
  428. except OSError:
  429. pass
  430. # We're done with the lock, so we can delete it.
  431. _master_keys_lock = None
  432. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  433. URI_ALL = re.compile(r'^([a-z][a-z+-]*)://([^@/]*@?[^/]*)/')
  434. def GetSchemeFromUrl(url):
  435. m = URI_ALL.match(url)
  436. if m:
  437. return m.group(1)
  438. return None
  439. @contextlib.contextmanager
  440. def GetUrlCookieFile(url, quiet):
  441. if url.startswith('persistent-'):
  442. try:
  443. p = subprocess.Popen(
  444. ['git-remote-persistent-https', '-print_config', url],
  445. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  446. stderr=subprocess.PIPE)
  447. try:
  448. cookieprefix = 'http.cookiefile='
  449. proxyprefix = 'http.proxy='
  450. cookiefile = None
  451. proxy = None
  452. for line in p.stdout:
  453. line = line.strip()
  454. if line.startswith(cookieprefix):
  455. cookiefile = line[len(cookieprefix):]
  456. if line.startswith(proxyprefix):
  457. proxy = line[len(proxyprefix):]
  458. # Leave subprocess open, as cookie file may be transient.
  459. if cookiefile or proxy:
  460. yield cookiefile, proxy
  461. return
  462. finally:
  463. p.stdin.close()
  464. if p.wait():
  465. err_msg = p.stderr.read()
  466. if ' -print_config' in err_msg:
  467. pass # Persistent proxy doesn't support -print_config.
  468. elif not quiet:
  469. print(err_msg, file=sys.stderr)
  470. except OSError as e:
  471. if e.errno == errno.ENOENT:
  472. pass # No persistent proxy.
  473. raise
  474. yield GitConfig.ForUser().GetString('http.cookiefile'), None
  475. def _preconnect(url):
  476. m = URI_ALL.match(url)
  477. if m:
  478. scheme = m.group(1)
  479. host = m.group(2)
  480. if ':' in host:
  481. host, port = host.split(':')
  482. else:
  483. port = None
  484. if scheme in ('ssh', 'git+ssh', 'ssh+git'):
  485. return _open_ssh(host, port)
  486. return False
  487. m = URI_SCP.match(url)
  488. if m:
  489. host = m.group(1)
  490. return _open_ssh(host)
  491. return False
  492. class Remote(object):
  493. """Configuration options related to a remote.
  494. """
  495. def __init__(self, config, name):
  496. self._config = config
  497. self.name = name
  498. self.url = self._Get('url')
  499. self.pushUrl = self._Get('pushurl')
  500. self.review = self._Get('review')
  501. self.projectname = self._Get('projectname')
  502. self.fetch = list(map(RefSpec.FromString,
  503. self._Get('fetch', all_keys=True)))
  504. self._review_url = None
  505. def _InsteadOf(self):
  506. globCfg = GitConfig.ForUser()
  507. urlList = globCfg.GetSubSections('url')
  508. longest = ""
  509. longestUrl = ""
  510. for url in urlList:
  511. key = "url." + url + ".insteadOf"
  512. insteadOfList = globCfg.GetString(key, all_keys=True)
  513. for insteadOf in insteadOfList:
  514. if self.url.startswith(insteadOf) \
  515. and len(insteadOf) > len(longest):
  516. longest = insteadOf
  517. longestUrl = url
  518. if len(longest) == 0:
  519. return self.url
  520. return self.url.replace(longest, longestUrl, 1)
  521. def PreConnectFetch(self):
  522. connectionUrl = self._InsteadOf()
  523. return _preconnect(connectionUrl)
  524. def ReviewUrl(self, userEmail):
  525. if self._review_url is None:
  526. if self.review is None:
  527. return None
  528. u = self.review
  529. if u.startswith('persistent-'):
  530. u = u[len('persistent-'):]
  531. if u.split(':')[0] not in ('http', 'https', 'sso'):
  532. u = 'http://%s' % u
  533. if u.endswith('/Gerrit'):
  534. u = u[:len(u) - len('/Gerrit')]
  535. if u.endswith('/ssh_info'):
  536. u = u[:len(u) - len('/ssh_info')]
  537. if not u.endswith('/'):
  538. u += '/'
  539. http_url = u
  540. if u in REVIEW_CACHE:
  541. self._review_url = REVIEW_CACHE[u]
  542. elif 'REPO_HOST_PORT_INFO' in os.environ:
  543. host, port = os.environ['REPO_HOST_PORT_INFO'].split()
  544. self._review_url = self._SshReviewUrl(userEmail, host, port)
  545. REVIEW_CACHE[u] = self._review_url
  546. elif u.startswith('sso:'):
  547. self._review_url = u # Assume it's right
  548. REVIEW_CACHE[u] = self._review_url
  549. elif 'REPO_IGNORE_SSH_INFO' in os.environ:
  550. self._review_url = http_url
  551. REVIEW_CACHE[u] = self._review_url
  552. else:
  553. try:
  554. info_url = u + 'ssh_info'
  555. info = urllib.request.urlopen(info_url).read()
  556. if info == 'NOT_AVAILABLE' or '<' in info:
  557. # If `info` contains '<', we assume the server gave us some sort
  558. # of HTML response back, like maybe a login page.
  559. #
  560. # Assume HTTP if SSH is not enabled or ssh_info doesn't look right.
  561. self._review_url = http_url
  562. else:
  563. host, port = info.split()
  564. self._review_url = self._SshReviewUrl(userEmail, host, port)
  565. except urllib.error.HTTPError as e:
  566. raise UploadError('%s: %s' % (self.review, str(e)))
  567. except urllib.error.URLError as e:
  568. raise UploadError('%s: %s' % (self.review, str(e)))
  569. except HTTPException as e:
  570. raise UploadError('%s: %s' % (self.review, e.__class__.__name__))
  571. REVIEW_CACHE[u] = self._review_url
  572. return self._review_url + self.projectname
  573. def _SshReviewUrl(self, userEmail, host, port):
  574. username = self._config.GetString('review.%s.username' % self.review)
  575. if username is None:
  576. username = userEmail.split('@')[0]
  577. return 'ssh://%s@%s:%s/' % (username, host, port)
  578. def ToLocal(self, rev):
  579. """Convert a remote revision string to something we have locally.
  580. """
  581. if self.name == '.' or IsId(rev):
  582. return rev
  583. if not rev.startswith('refs/'):
  584. rev = R_HEADS + rev
  585. for spec in self.fetch:
  586. if spec.SourceMatches(rev):
  587. return spec.MapSource(rev)
  588. if not rev.startswith(R_HEADS):
  589. return rev
  590. raise GitError('remote %s does not have %s' % (self.name, rev))
  591. def WritesTo(self, ref):
  592. """True if the remote stores to the tracking ref.
  593. """
  594. for spec in self.fetch:
  595. if spec.DestMatches(ref):
  596. return True
  597. return False
  598. def ResetFetch(self, mirror=False):
  599. """Set the fetch refspec to its default value.
  600. """
  601. if mirror:
  602. dst = 'refs/heads/*'
  603. else:
  604. dst = 'refs/remotes/%s/*' % self.name
  605. self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
  606. def Save(self):
  607. """Save this remote to the configuration.
  608. """
  609. self._Set('url', self.url)
  610. if self.pushUrl is not None:
  611. self._Set('pushurl', self.pushUrl + '/' + self.projectname)
  612. else:
  613. self._Set('pushurl', self.pushUrl)
  614. self._Set('review', self.review)
  615. self._Set('projectname', self.projectname)
  616. self._Set('fetch', list(map(str, self.fetch)))
  617. def _Set(self, key, value):
  618. key = 'remote.%s.%s' % (self.name, key)
  619. return self._config.SetString(key, value)
  620. def _Get(self, key, all_keys=False):
  621. key = 'remote.%s.%s' % (self.name, key)
  622. return self._config.GetString(key, all_keys = all_keys)
  623. class Branch(object):
  624. """Configuration options related to a single branch.
  625. """
  626. def __init__(self, config, name):
  627. self._config = config
  628. self.name = name
  629. self.merge = self._Get('merge')
  630. r = self._Get('remote')
  631. if r:
  632. self.remote = self._config.GetRemote(r)
  633. else:
  634. self.remote = None
  635. @property
  636. def LocalMerge(self):
  637. """Convert the merge spec to a local name.
  638. """
  639. if self.remote and self.merge:
  640. return self.remote.ToLocal(self.merge)
  641. return None
  642. def Save(self):
  643. """Save this branch back into the configuration.
  644. """
  645. if self._config.HasSection('branch', self.name):
  646. if self.remote:
  647. self._Set('remote', self.remote.name)
  648. else:
  649. self._Set('remote', None)
  650. self._Set('merge', self.merge)
  651. else:
  652. fd = open(self._config.file, 'a')
  653. try:
  654. fd.write('[branch "%s"]\n' % self.name)
  655. if self.remote:
  656. fd.write('\tremote = %s\n' % self.remote.name)
  657. if self.merge:
  658. fd.write('\tmerge = %s\n' % self.merge)
  659. finally:
  660. fd.close()
  661. def _Set(self, key, value):
  662. key = 'branch.%s.%s' % (self.name, key)
  663. return self._config.SetString(key, value)
  664. def _Get(self, key, all_keys=False):
  665. key = 'branch.%s.%s' % (self.name, key)
  666. return self._config.GetString(key, all_keys = all_keys)