git_config.py 21 KB

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