git_config.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import contextlib
  18. import errno
  19. import json
  20. import os
  21. import re
  22. import ssl
  23. import subprocess
  24. import sys
  25. try:
  26. import threading as _threading
  27. except ImportError:
  28. import dummy_threading as _threading
  29. import time
  30. from pyversion import is_python3
  31. if is_python3():
  32. import urllib.request
  33. import urllib.error
  34. else:
  35. import urllib2
  36. import imp
  37. urllib = imp.new_module('urllib')
  38. urllib.request = urllib2
  39. urllib.error = urllib2
  40. from signal import SIGTERM
  41. from error import GitError, UploadError
  42. import platform_utils
  43. from repo_trace import Trace
  44. if is_python3():
  45. from http.client import HTTPException
  46. else:
  47. from httplib import HTTPException
  48. from git_command import GitCommand
  49. from git_command import ssh_sock
  50. from git_command import terminate_ssh_clients
  51. from git_refs import R_CHANGES, R_HEADS, R_TAGS
  52. ID_RE = re.compile(r'^[0-9a-f]{40}$')
  53. REVIEW_CACHE = dict()
  54. def IsChange(rev):
  55. return rev.startswith(R_CHANGES)
  56. def IsId(rev):
  57. return ID_RE.match(rev)
  58. def IsTag(rev):
  59. return rev.startswith(R_TAGS)
  60. def IsImmutable(rev):
  61. return IsChange(rev) or IsId(rev) or IsTag(rev)
  62. def _key(name):
  63. parts = name.split('.')
  64. if len(parts) < 2:
  65. return name.lower()
  66. parts[0] = parts[0].lower()
  67. parts[-1] = parts[-1].lower()
  68. return '.'.join(parts)
  69. class GitConfig(object):
  70. _ForUser = None
  71. @classmethod
  72. def ForUser(cls):
  73. if cls._ForUser is None:
  74. cls._ForUser = cls(configfile=os.path.expanduser('~/.gitconfig'))
  75. return cls._ForUser
  76. @classmethod
  77. def ForRepository(cls, gitdir, defaults=None):
  78. return cls(configfile=os.path.join(gitdir, 'config'),
  79. defaults=defaults)
  80. def __init__(self, configfile, defaults=None, jsonFile=None):
  81. self.file = configfile
  82. self.defaults = defaults
  83. self._cache_dict = None
  84. self._section_dict = None
  85. self._remotes = {}
  86. self._branches = {}
  87. self._json = jsonFile
  88. if self._json is None:
  89. self._json = os.path.join(
  90. os.path.dirname(self.file),
  91. '.repo_' + os.path.basename(self.file) + '.json')
  92. def Has(self, name, include_defaults=True):
  93. """Return true if this configuration file has the key.
  94. """
  95. if _key(name) in self._cache:
  96. return True
  97. if include_defaults and self.defaults:
  98. return self.defaults.Has(name, include_defaults=True)
  99. return False
  100. def GetBoolean(self, name):
  101. """Returns a boolean from the configuration file.
  102. None : The value was not defined, or is not a boolean.
  103. True : The value was set to true or yes.
  104. False: The value was set to false or no.
  105. """
  106. v = self.GetString(name)
  107. if v is None:
  108. return None
  109. v = v.lower()
  110. if v in ('true', 'yes'):
  111. return True
  112. if v in ('false', 'no'):
  113. return False
  114. return None
  115. def GetString(self, name, all_keys=False):
  116. """Get the first value for a key, or None if it is not defined.
  117. This configuration file is used first, if the key is not
  118. defined or all_keys = True then the defaults are also searched.
  119. """
  120. try:
  121. v = self._cache[_key(name)]
  122. except KeyError:
  123. if self.defaults:
  124. return self.defaults.GetString(name, all_keys=all_keys)
  125. v = []
  126. if not all_keys:
  127. if v:
  128. return v[0]
  129. return None
  130. r = []
  131. r.extend(v)
  132. if self.defaults:
  133. r.extend(self.defaults.GetString(name, all_keys=True))
  134. return r
  135. def SetString(self, name, value):
  136. """Set the value(s) for a key.
  137. Only this configuration file is modified.
  138. The supplied value should be either a string,
  139. or a list of strings (to store multiple values).
  140. """
  141. key = _key(name)
  142. try:
  143. old = self._cache[key]
  144. except KeyError:
  145. old = []
  146. if value is None:
  147. if old:
  148. del self._cache[key]
  149. self._do('--unset-all', name)
  150. elif isinstance(value, list):
  151. if len(value) == 0:
  152. self.SetString(name, None)
  153. elif len(value) == 1:
  154. self.SetString(name, value[0])
  155. elif old != value:
  156. self._cache[key] = list(value)
  157. self._do('--replace-all', name, value[0])
  158. for i in range(1, len(value)):
  159. self._do('--add', name, value[i])
  160. elif len(old) != 1 or old[0] != value:
  161. self._cache[key] = [value]
  162. self._do('--replace-all', name, value)
  163. def GetRemote(self, name):
  164. """Get the remote.$name.* configuration values as an object.
  165. """
  166. try:
  167. r = self._remotes[name]
  168. except KeyError:
  169. r = Remote(self, name)
  170. self._remotes[r.name] = r
  171. return r
  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. def GetSubSections(self, section):
  182. """List all subsection names matching $section.*.*
  183. """
  184. return self._sections.get(section, set())
  185. def HasSection(self, section, subsection=''):
  186. """Does at least one key in section.subsection exist?
  187. """
  188. try:
  189. return subsection in self._sections[section]
  190. except KeyError:
  191. return False
  192. def UrlInsteadOf(self, url):
  193. """Resolve any url.*.insteadof references.
  194. """
  195. for new_url in self.GetSubSections('url'):
  196. for old_url in self.GetString('url.%s.insteadof' % new_url, True):
  197. if old_url is not None and url.startswith(old_url):
  198. return new_url + url[len(old_url):]
  199. return url
  200. @property
  201. def _sections(self):
  202. d = self._section_dict
  203. if d is None:
  204. d = {}
  205. for name in self._cache.keys():
  206. p = name.split('.')
  207. if 2 == len(p):
  208. section = p[0]
  209. subsect = ''
  210. else:
  211. section = p[0]
  212. subsect = '.'.join(p[1:-1])
  213. if section not in d:
  214. d[section] = set()
  215. d[section].add(subsect)
  216. self._section_dict = d
  217. return d
  218. @property
  219. def _cache(self):
  220. if self._cache_dict is None:
  221. self._cache_dict = self._Read()
  222. return self._cache_dict
  223. def _Read(self):
  224. d = self._ReadJson()
  225. if d is None:
  226. d = self._ReadGit()
  227. self._SaveJson(d)
  228. return d
  229. def _ReadJson(self):
  230. try:
  231. if os.path.getmtime(self._json) \
  232. <= os.path.getmtime(self.file):
  233. platform_utils.remove(self._json)
  234. return None
  235. except OSError:
  236. return None
  237. try:
  238. Trace(': parsing %s', self.file)
  239. with open(self._json) as fd:
  240. return json.load(fd)
  241. except (IOError, ValueError):
  242. platform_utils.remove(self._json)
  243. return None
  244. def _SaveJson(self, cache):
  245. try:
  246. with open(self._json, 'w') as fd:
  247. json.dump(cache, fd, indent=2)
  248. except (IOError, TypeError):
  249. if os.path.exists(self._json):
  250. platform_utils.remove(self._json)
  251. def _ReadGit(self):
  252. """
  253. Read configuration data from git.
  254. This internal method populates the GitConfig cache.
  255. """
  256. c = {}
  257. d = self._do('--null', '--list')
  258. if d is None:
  259. return c
  260. if not is_python3():
  261. d = d.decode('utf-8')
  262. for line in d.rstrip('\0').split('\0'):
  263. if '\n' in line:
  264. key, val = line.split('\n', 1)
  265. else:
  266. key = line
  267. val = None
  268. if key in c:
  269. c[key].append(val)
  270. else:
  271. c[key] = [val]
  272. return c
  273. def _do(self, *args):
  274. command = ['config', '--file', self.file]
  275. command.extend(args)
  276. p = GitCommand(None,
  277. command,
  278. capture_stdout=True,
  279. capture_stderr=True)
  280. if p.Wait() == 0:
  281. return p.stdout
  282. else:
  283. GitError('git config %s: %s' % (str(args), p.stderr))
  284. class RefSpec(object):
  285. """A Git refspec line, split into its components:
  286. forced: True if the line starts with '+'
  287. src: Left side of the line
  288. dst: Right side of the line
  289. """
  290. @classmethod
  291. def FromString(cls, rs):
  292. lhs, rhs = rs.split(':', 2)
  293. if lhs.startswith('+'):
  294. lhs = lhs[1:]
  295. forced = True
  296. else:
  297. forced = False
  298. return cls(forced, lhs, rhs)
  299. def __init__(self, forced, lhs, rhs):
  300. self.forced = forced
  301. self.src = lhs
  302. self.dst = rhs
  303. def SourceMatches(self, rev):
  304. if self.src:
  305. if rev == self.src:
  306. return True
  307. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  308. return True
  309. return False
  310. def DestMatches(self, ref):
  311. if self.dst:
  312. if ref == self.dst:
  313. return True
  314. if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
  315. return True
  316. return False
  317. def MapSource(self, rev):
  318. if self.src.endswith('/*'):
  319. return self.dst[:-1] + rev[len(self.src) - 1:]
  320. return self.dst
  321. def __str__(self):
  322. s = ''
  323. if self.forced:
  324. s += '+'
  325. if self.src:
  326. s += self.src
  327. if self.dst:
  328. s += ':'
  329. s += self.dst
  330. return s
  331. _master_processes = []
  332. _master_keys = set()
  333. _ssh_master = True
  334. _master_keys_lock = None
  335. def init_ssh():
  336. """Should be called once at the start of repo to init ssh master handling.
  337. At the moment, all we do is to create our lock.
  338. """
  339. global _master_keys_lock
  340. assert _master_keys_lock is None, "Should only call init_ssh once"
  341. _master_keys_lock = _threading.Lock()
  342. def _open_ssh(host, port=None):
  343. global _ssh_master
  344. # Acquire the lock. This is needed to prevent opening multiple masters for
  345. # the same host when we're running "repo sync -jN" (for N > 1) _and_ the
  346. # manifest <remote fetch="ssh://xyz"> specifies a different host from the
  347. # one that was passed to repo init.
  348. _master_keys_lock.acquire()
  349. try:
  350. # Check to see whether we already think that the master is running; if we
  351. # think it's already running, return right away.
  352. if port is not None:
  353. key = '%s:%s' % (host, port)
  354. else:
  355. key = host
  356. if key in _master_keys:
  357. return True
  358. if not _ssh_master \
  359. or 'GIT_SSH' in os.environ \
  360. or sys.platform in ('win32', 'cygwin'):
  361. # failed earlier, or cygwin ssh can't do this
  362. #
  363. return False
  364. # We will make two calls to ssh; this is the common part of both calls.
  365. command_base = ['ssh',
  366. '-o', 'ControlPath %s' % ssh_sock(),
  367. host]
  368. if port is not None:
  369. command_base[1:1] = ['-p', str(port)]
  370. # Since the key wasn't in _master_keys, we think that master isn't running.
  371. # ...but before actually starting a master, we'll double-check. This can
  372. # be important because we can't tell that that 'git@myhost.com' is the same
  373. # as 'myhost.com' where "User git" is setup in the user's ~/.ssh/config file.
  374. check_command = command_base + ['-O', 'check']
  375. try:
  376. Trace(': %s', ' '.join(check_command))
  377. check_process = subprocess.Popen(check_command,
  378. stdout=subprocess.PIPE,
  379. stderr=subprocess.PIPE)
  380. check_process.communicate() # read output, but ignore it...
  381. isnt_running = check_process.wait()
  382. if not isnt_running:
  383. # Our double-check found that the master _was_ infact running. Add to
  384. # the list of keys.
  385. _master_keys.add(key)
  386. return True
  387. except Exception:
  388. # Ignore excpetions. We we will fall back to the normal command and print
  389. # to the log there.
  390. pass
  391. command = command_base[:1] + \
  392. ['-M', '-N'] + \
  393. command_base[1:]
  394. try:
  395. Trace(': %s', ' '.join(command))
  396. p = subprocess.Popen(command)
  397. except Exception as e:
  398. _ssh_master = False
  399. print('\nwarn: cannot enable ssh control master for %s:%s\n%s'
  400. % (host, port, str(e)), file=sys.stderr)
  401. return False
  402. time.sleep(1)
  403. ssh_died = (p.poll() is not None)
  404. if ssh_died:
  405. return False
  406. _master_processes.append(p)
  407. _master_keys.add(key)
  408. return True
  409. finally:
  410. _master_keys_lock.release()
  411. def close_ssh():
  412. global _master_keys_lock
  413. terminate_ssh_clients()
  414. for p in _master_processes:
  415. try:
  416. os.kill(p.pid, SIGTERM)
  417. p.wait()
  418. except OSError:
  419. pass
  420. del _master_processes[:]
  421. _master_keys.clear()
  422. d = ssh_sock(create=False)
  423. if d:
  424. try:
  425. platform_utils.rmdir(os.path.dirname(d))
  426. except OSError:
  427. pass
  428. # We're done with the lock, so we can delete it.
  429. _master_keys_lock = None
  430. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  431. URI_ALL = re.compile(r'^([a-z][a-z+-]*)://([^@/]*@?[^/]*)/')
  432. def GetSchemeFromUrl(url):
  433. m = URI_ALL.match(url)
  434. if m:
  435. return m.group(1)
  436. return None
  437. @contextlib.contextmanager
  438. def GetUrlCookieFile(url, quiet):
  439. if url.startswith('persistent-'):
  440. try:
  441. p = subprocess.Popen(
  442. ['git-remote-persistent-https', '-print_config', url],
  443. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  444. stderr=subprocess.PIPE)
  445. try:
  446. cookieprefix = 'http.cookiefile='
  447. proxyprefix = 'http.proxy='
  448. cookiefile = None
  449. proxy = None
  450. for line in p.stdout:
  451. line = line.strip().decode('utf-8')
  452. if line.startswith(cookieprefix):
  453. cookiefile = os.path.expanduser(line[len(cookieprefix):])
  454. if line.startswith(proxyprefix):
  455. proxy = line[len(proxyprefix):]
  456. # Leave subprocess open, as cookie file may be transient.
  457. if cookiefile or proxy:
  458. yield cookiefile, proxy
  459. return
  460. finally:
  461. p.stdin.close()
  462. if p.wait():
  463. err_msg = p.stderr.read().decode('utf-8')
  464. if ' -print_config' in err_msg:
  465. pass # Persistent proxy doesn't support -print_config.
  466. elif not quiet:
  467. print(err_msg, file=sys.stderr)
  468. except OSError as e:
  469. if e.errno == errno.ENOENT:
  470. pass # No persistent proxy.
  471. raise
  472. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  473. if cookiefile:
  474. cookiefile = os.path.expanduser(cookiefile)
  475. yield 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 == b'NOT_AVAILABLE' or b'<' 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. info = info.decode('utf-8')
  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('%s: remote %s does not have %s' %
  597. (self.projectname, self.name, rev))
  598. def WritesTo(self, ref):
  599. """True if the remote stores to the tracking ref.
  600. """
  601. for spec in self.fetch:
  602. if spec.DestMatches(ref):
  603. return True
  604. return False
  605. def ResetFetch(self, mirror=False):
  606. """Set the fetch refspec to its default value.
  607. """
  608. if mirror:
  609. dst = 'refs/heads/*'
  610. else:
  611. dst = 'refs/remotes/%s/*' % self.name
  612. self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
  613. def Save(self):
  614. """Save this remote to the configuration.
  615. """
  616. self._Set('url', self.url)
  617. if self.pushUrl is not None:
  618. self._Set('pushurl', self.pushUrl + '/' + self.projectname)
  619. else:
  620. self._Set('pushurl', self.pushUrl)
  621. self._Set('review', self.review)
  622. self._Set('projectname', self.projectname)
  623. self._Set('fetch', list(map(str, self.fetch)))
  624. def _Set(self, key, value):
  625. key = 'remote.%s.%s' % (self.name, key)
  626. return self._config.SetString(key, value)
  627. def _Get(self, key, all_keys=False):
  628. key = 'remote.%s.%s' % (self.name, key)
  629. return self._config.GetString(key, all_keys=all_keys)
  630. class Branch(object):
  631. """Configuration options related to a single branch.
  632. """
  633. def __init__(self, config, name):
  634. self._config = config
  635. self.name = name
  636. self.merge = self._Get('merge')
  637. r = self._Get('remote')
  638. if r:
  639. self.remote = self._config.GetRemote(r)
  640. else:
  641. self.remote = None
  642. @property
  643. def LocalMerge(self):
  644. """Convert the merge spec to a local name.
  645. """
  646. if self.remote and self.merge:
  647. return self.remote.ToLocal(self.merge)
  648. return None
  649. def Save(self):
  650. """Save this branch back into the configuration.
  651. """
  652. if self._config.HasSection('branch', self.name):
  653. if self.remote:
  654. self._Set('remote', self.remote.name)
  655. else:
  656. self._Set('remote', None)
  657. self._Set('merge', self.merge)
  658. else:
  659. with open(self._config.file, 'a') as fd:
  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. def _Set(self, key, value):
  666. key = 'branch.%s.%s' % (self.name, key)
  667. return self._config.SetString(key, value)
  668. def _Get(self, key, all_keys=False):
  669. key = 'branch.%s.%s' % (self.name, key)
  670. return self._config.GetString(key, all_keys=all_keys)