git_config.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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) <= 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. with open(self._json) as fd:
  239. return json.load(fd)
  240. except (IOError, ValueError):
  241. platform_utils.remove(self._json)
  242. return None
  243. def _SaveJson(self, cache):
  244. try:
  245. with open(self._json, 'w') as fd:
  246. json.dump(cache, fd, indent=2)
  247. except (IOError, TypeError):
  248. if os.path.exists(self._json):
  249. platform_utils.remove(self._json)
  250. def _ReadGit(self):
  251. """
  252. Read configuration data from git.
  253. This internal method populates the GitConfig cache.
  254. """
  255. c = {}
  256. d = self._do('--null', '--list')
  257. if d is None:
  258. return c
  259. if not is_python3():
  260. d = d.decode('utf-8')
  261. for line in d.rstrip('\0').split('\0'):
  262. if '\n' in line:
  263. key, val = line.split('\n', 1)
  264. else:
  265. key = line
  266. val = None
  267. if key in c:
  268. c[key].append(val)
  269. else:
  270. c[key] = [val]
  271. return c
  272. def _do(self, *args):
  273. command = ['config', '--file', self.file]
  274. command.extend(args)
  275. p = GitCommand(None,
  276. command,
  277. capture_stdout=True,
  278. capture_stderr=True)
  279. if p.Wait() == 0:
  280. return p.stdout
  281. else:
  282. GitError('git config %s: %s' % (str(args), p.stderr))
  283. class RefSpec(object):
  284. """A Git refspec line, split into its components:
  285. forced: True if the line starts with '+'
  286. src: Left side of the line
  287. dst: Right side of the line
  288. """
  289. @classmethod
  290. def FromString(cls, rs):
  291. lhs, rhs = rs.split(':', 2)
  292. if lhs.startswith('+'):
  293. lhs = lhs[1:]
  294. forced = True
  295. else:
  296. forced = False
  297. return cls(forced, lhs, rhs)
  298. def __init__(self, forced, lhs, rhs):
  299. self.forced = forced
  300. self.src = lhs
  301. self.dst = rhs
  302. def SourceMatches(self, rev):
  303. if self.src:
  304. if rev == self.src:
  305. return True
  306. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  307. return True
  308. return False
  309. def DestMatches(self, ref):
  310. if self.dst:
  311. if ref == self.dst:
  312. return True
  313. if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
  314. return True
  315. return False
  316. def MapSource(self, rev):
  317. if self.src.endswith('/*'):
  318. return self.dst[:-1] + rev[len(self.src) - 1:]
  319. return self.dst
  320. def __str__(self):
  321. s = ''
  322. if self.forced:
  323. s += '+'
  324. if self.src:
  325. s += self.src
  326. if self.dst:
  327. s += ':'
  328. s += self.dst
  329. return s
  330. _master_processes = []
  331. _master_keys = set()
  332. _ssh_master = True
  333. _master_keys_lock = None
  334. def init_ssh():
  335. """Should be called once at the start of repo to init ssh master handling.
  336. At the moment, all we do is to create our lock.
  337. """
  338. global _master_keys_lock
  339. assert _master_keys_lock is None, "Should only call init_ssh once"
  340. _master_keys_lock = _threading.Lock()
  341. def _open_ssh(host, port=None):
  342. global _ssh_master
  343. # Acquire the lock. This is needed to prevent opening multiple masters for
  344. # the same host when we're running "repo sync -jN" (for N > 1) _and_ the
  345. # manifest <remote fetch="ssh://xyz"> specifies a different host from the
  346. # one that was passed to repo init.
  347. _master_keys_lock.acquire()
  348. try:
  349. # Check to see whether we already think that the master is running; if we
  350. # think it's already running, return right away.
  351. if port is not None:
  352. key = '%s:%s' % (host, port)
  353. else:
  354. key = host
  355. if key in _master_keys:
  356. return True
  357. if (not _ssh_master
  358. or 'GIT_SSH' in os.environ
  359. or sys.platform in ('win32', 'cygwin')):
  360. # failed earlier, or cygwin ssh can't do this
  361. #
  362. return False
  363. # We will make two calls to ssh; this is the common part of both calls.
  364. command_base = ['ssh',
  365. '-o', 'ControlPath %s' % ssh_sock(),
  366. host]
  367. if port is not None:
  368. command_base[1:1] = ['-p', str(port)]
  369. # Since the key wasn't in _master_keys, we think that master isn't running.
  370. # ...but before actually starting a master, we'll double-check. This can
  371. # be important because we can't tell that that 'git@myhost.com' is the same
  372. # as 'myhost.com' where "User git" is setup in the user's ~/.ssh/config file.
  373. check_command = command_base + ['-O', 'check']
  374. try:
  375. Trace(': %s', ' '.join(check_command))
  376. check_process = subprocess.Popen(check_command,
  377. stdout=subprocess.PIPE,
  378. stderr=subprocess.PIPE)
  379. check_process.communicate() # read output, but ignore it...
  380. isnt_running = check_process.wait()
  381. if not isnt_running:
  382. # Our double-check found that the master _was_ infact running. Add to
  383. # the list of keys.
  384. _master_keys.add(key)
  385. return True
  386. except Exception:
  387. # Ignore excpetions. We we will fall back to the normal command and print
  388. # to the log there.
  389. pass
  390. command = command_base[:1] + ['-M', '-N'] + command_base[1:]
  391. try:
  392. Trace(': %s', ' '.join(command))
  393. p = subprocess.Popen(command)
  394. except Exception as e:
  395. _ssh_master = False
  396. print('\nwarn: cannot enable ssh control master for %s:%s\n%s'
  397. % (host, port, str(e)), file=sys.stderr)
  398. return False
  399. time.sleep(1)
  400. ssh_died = (p.poll() is not None)
  401. if ssh_died:
  402. return False
  403. _master_processes.append(p)
  404. _master_keys.add(key)
  405. return True
  406. finally:
  407. _master_keys_lock.release()
  408. def close_ssh():
  409. global _master_keys_lock
  410. terminate_ssh_clients()
  411. for p in _master_processes:
  412. try:
  413. os.kill(p.pid, SIGTERM)
  414. p.wait()
  415. except OSError:
  416. pass
  417. del _master_processes[:]
  418. _master_keys.clear()
  419. d = ssh_sock(create=False)
  420. if d:
  421. try:
  422. platform_utils.rmdir(os.path.dirname(d))
  423. except OSError:
  424. pass
  425. # We're done with the lock, so we can delete it.
  426. _master_keys_lock = None
  427. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  428. URI_ALL = re.compile(r'^([a-z][a-z+-]*)://([^@/]*@?[^/]*)/')
  429. def GetSchemeFromUrl(url):
  430. m = URI_ALL.match(url)
  431. if m:
  432. return m.group(1)
  433. return None
  434. @contextlib.contextmanager
  435. def GetUrlCookieFile(url, quiet):
  436. if url.startswith('persistent-'):
  437. try:
  438. p = subprocess.Popen(
  439. ['git-remote-persistent-https', '-print_config', url],
  440. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  441. stderr=subprocess.PIPE)
  442. try:
  443. cookieprefix = 'http.cookiefile='
  444. proxyprefix = 'http.proxy='
  445. cookiefile = None
  446. proxy = None
  447. for line in p.stdout:
  448. line = line.strip().decode('utf-8')
  449. if line.startswith(cookieprefix):
  450. cookiefile = os.path.expanduser(line[len(cookieprefix):])
  451. if line.startswith(proxyprefix):
  452. proxy = line[len(proxyprefix):]
  453. # Leave subprocess open, as cookie file may be transient.
  454. if cookiefile or proxy:
  455. yield cookiefile, proxy
  456. return
  457. finally:
  458. p.stdin.close()
  459. if p.wait():
  460. err_msg = p.stderr.read().decode('utf-8')
  461. if ' -print_config' in err_msg:
  462. pass # Persistent proxy doesn't support -print_config.
  463. elif not quiet:
  464. print(err_msg, file=sys.stderr)
  465. except OSError as e:
  466. if e.errno == errno.ENOENT:
  467. pass # No persistent proxy.
  468. raise
  469. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  470. if cookiefile:
  471. cookiefile = os.path.expanduser(cookiefile)
  472. yield cookiefile, None
  473. def _preconnect(url):
  474. m = URI_ALL.match(url)
  475. if m:
  476. scheme = m.group(1)
  477. host = m.group(2)
  478. if ':' in host:
  479. host, port = host.split(':')
  480. else:
  481. port = None
  482. if scheme in ('ssh', 'git+ssh', 'ssh+git'):
  483. return _open_ssh(host, port)
  484. return False
  485. m = URI_SCP.match(url)
  486. if m:
  487. host = m.group(1)
  488. return _open_ssh(host)
  489. return False
  490. class Remote(object):
  491. """Configuration options related to a remote.
  492. """
  493. def __init__(self, config, name):
  494. self._config = config
  495. self.name = name
  496. self.url = self._Get('url')
  497. self.pushUrl = self._Get('pushurl')
  498. self.review = self._Get('review')
  499. self.projectname = self._Get('projectname')
  500. self.fetch = list(map(RefSpec.FromString,
  501. self._Get('fetch', all_keys=True)))
  502. self._review_url = None
  503. def _InsteadOf(self):
  504. globCfg = GitConfig.ForUser()
  505. urlList = globCfg.GetSubSections('url')
  506. longest = ""
  507. longestUrl = ""
  508. for url in urlList:
  509. key = "url." + url + ".insteadOf"
  510. insteadOfList = globCfg.GetString(key, all_keys=True)
  511. for insteadOf in insteadOfList:
  512. if (self.url.startswith(insteadOf)
  513. and len(insteadOf) > len(longest)):
  514. longest = insteadOf
  515. longestUrl = url
  516. if len(longest) == 0:
  517. return self.url
  518. return self.url.replace(longest, longestUrl, 1)
  519. def PreConnectFetch(self):
  520. connectionUrl = self._InsteadOf()
  521. return _preconnect(connectionUrl)
  522. def ReviewUrl(self, userEmail, validate_certs):
  523. if self._review_url is None:
  524. if self.review is None:
  525. return None
  526. u = self.review
  527. if u.startswith('persistent-'):
  528. u = u[len('persistent-'):]
  529. if u.split(':')[0] not in ('http', 'https', 'sso', 'ssh'):
  530. u = 'http://%s' % u
  531. if u.endswith('/Gerrit'):
  532. u = u[:len(u) - len('/Gerrit')]
  533. if u.endswith('/ssh_info'):
  534. u = u[:len(u) - len('/ssh_info')]
  535. if not u.endswith('/'):
  536. u += '/'
  537. http_url = u
  538. if u in REVIEW_CACHE:
  539. self._review_url = REVIEW_CACHE[u]
  540. elif 'REPO_HOST_PORT_INFO' in os.environ:
  541. host, port = os.environ['REPO_HOST_PORT_INFO'].split()
  542. self._review_url = self._SshReviewUrl(userEmail, host, port)
  543. REVIEW_CACHE[u] = self._review_url
  544. elif u.startswith('sso:') or u.startswith('ssh:'):
  545. self._review_url = u # Assume it's right
  546. REVIEW_CACHE[u] = self._review_url
  547. elif 'REPO_IGNORE_SSH_INFO' in os.environ:
  548. self._review_url = http_url
  549. REVIEW_CACHE[u] = self._review_url
  550. else:
  551. try:
  552. info_url = u + 'ssh_info'
  553. if not validate_certs:
  554. context = ssl._create_unverified_context()
  555. info = urllib.request.urlopen(info_url, context=context).read()
  556. else:
  557. info = urllib.request.urlopen(info_url).read()
  558. if info == b'NOT_AVAILABLE' or b'<' in info:
  559. # If `info` contains '<', we assume the server gave us some sort
  560. # of HTML response back, like maybe a login page.
  561. #
  562. # Assume HTTP if SSH is not enabled or ssh_info doesn't look right.
  563. self._review_url = http_url
  564. else:
  565. info = info.decode('utf-8')
  566. host, port = info.split()
  567. self._review_url = self._SshReviewUrl(userEmail, host, port)
  568. except urllib.error.HTTPError as e:
  569. raise UploadError('%s: %s' % (self.review, str(e)))
  570. except urllib.error.URLError as e:
  571. raise UploadError('%s: %s' % (self.review, str(e)))
  572. except HTTPException as e:
  573. raise UploadError('%s: %s' % (self.review, e.__class__.__name__))
  574. REVIEW_CACHE[u] = self._review_url
  575. return self._review_url + self.projectname
  576. def _SshReviewUrl(self, userEmail, host, port):
  577. username = self._config.GetString('review.%s.username' % self.review)
  578. if username is None:
  579. username = userEmail.split('@')[0]
  580. return 'ssh://%s@%s:%s/' % (username, host, port)
  581. def ToLocal(self, rev):
  582. """Convert a remote revision string to something we have locally.
  583. """
  584. if self.name == '.' or IsId(rev):
  585. return rev
  586. if not rev.startswith('refs/'):
  587. rev = R_HEADS + rev
  588. for spec in self.fetch:
  589. if spec.SourceMatches(rev):
  590. return spec.MapSource(rev)
  591. if not rev.startswith(R_HEADS):
  592. return rev
  593. raise GitError('%s: remote %s does not have %s' %
  594. (self.projectname, self.name, rev))
  595. def WritesTo(self, ref):
  596. """True if the remote stores to the tracking ref.
  597. """
  598. for spec in self.fetch:
  599. if spec.DestMatches(ref):
  600. return True
  601. return False
  602. def ResetFetch(self, mirror=False):
  603. """Set the fetch refspec to its default value.
  604. """
  605. if mirror:
  606. dst = 'refs/heads/*'
  607. else:
  608. dst = 'refs/remotes/%s/*' % self.name
  609. self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
  610. def Save(self):
  611. """Save this remote to the configuration.
  612. """
  613. self._Set('url', self.url)
  614. if self.pushUrl is not None:
  615. self._Set('pushurl', self.pushUrl + '/' + self.projectname)
  616. else:
  617. self._Set('pushurl', self.pushUrl)
  618. self._Set('review', self.review)
  619. self._Set('projectname', self.projectname)
  620. self._Set('fetch', list(map(str, self.fetch)))
  621. def _Set(self, key, value):
  622. key = 'remote.%s.%s' % (self.name, key)
  623. return self._config.SetString(key, value)
  624. def _Get(self, key, all_keys=False):
  625. key = 'remote.%s.%s' % (self.name, key)
  626. return self._config.GetString(key, all_keys=all_keys)
  627. class Branch(object):
  628. """Configuration options related to a single branch.
  629. """
  630. def __init__(self, config, name):
  631. self._config = config
  632. self.name = name
  633. self.merge = self._Get('merge')
  634. r = self._Get('remote')
  635. if r:
  636. self.remote = self._config.GetRemote(r)
  637. else:
  638. self.remote = None
  639. @property
  640. def LocalMerge(self):
  641. """Convert the merge spec to a local name.
  642. """
  643. if self.remote and self.merge:
  644. return self.remote.ToLocal(self.merge)
  645. return None
  646. def Save(self):
  647. """Save this branch back into the configuration.
  648. """
  649. if self._config.HasSection('branch', self.name):
  650. if self.remote:
  651. self._Set('remote', self.remote.name)
  652. else:
  653. self._Set('remote', None)
  654. self._Set('merge', self.merge)
  655. else:
  656. with open(self._config.file, 'a') as fd:
  657. fd.write('[branch "%s"]\n' % self.name)
  658. if self.remote:
  659. fd.write('\tremote = %s\n' % self.remote.name)
  660. if self.merge:
  661. fd.write('\tmerge = %s\n' % self.merge)
  662. def _Set(self, key, value):
  663. key = 'branch.%s.%s' % (self.name, key)
  664. return self._config.SetString(key, value)
  665. def _Get(self, key, all_keys=False):
  666. key = 'branch.%s.%s' % (self.name, key)
  667. return self._config.GetString(key, all_keys=all_keys)