git_config.py 21 KB

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