git_config.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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] + ['-M', '-N'] + command_base[1:]
  392. try:
  393. Trace(': %s', ' '.join(command))
  394. p = subprocess.Popen(command)
  395. except Exception as e:
  396. _ssh_master = False
  397. print('\nwarn: cannot enable ssh control master for %s:%s\n%s'
  398. % (host, port, str(e)), file=sys.stderr)
  399. return False
  400. time.sleep(1)
  401. ssh_died = (p.poll() is not None)
  402. if ssh_died:
  403. return False
  404. _master_processes.append(p)
  405. _master_keys.add(key)
  406. return True
  407. finally:
  408. _master_keys_lock.release()
  409. def close_ssh():
  410. global _master_keys_lock
  411. terminate_ssh_clients()
  412. for p in _master_processes:
  413. try:
  414. os.kill(p.pid, SIGTERM)
  415. p.wait()
  416. except OSError:
  417. pass
  418. del _master_processes[:]
  419. _master_keys.clear()
  420. d = ssh_sock(create=False)
  421. if d:
  422. try:
  423. platform_utils.rmdir(os.path.dirname(d))
  424. except OSError:
  425. pass
  426. # We're done with the lock, so we can delete it.
  427. _master_keys_lock = None
  428. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  429. URI_ALL = re.compile(r'^([a-z][a-z+-]*)://([^@/]*@?[^/]*)/')
  430. def GetSchemeFromUrl(url):
  431. m = URI_ALL.match(url)
  432. if m:
  433. return m.group(1)
  434. return None
  435. @contextlib.contextmanager
  436. def GetUrlCookieFile(url, quiet):
  437. if url.startswith('persistent-'):
  438. try:
  439. p = subprocess.Popen(
  440. ['git-remote-persistent-https', '-print_config', url],
  441. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  442. stderr=subprocess.PIPE)
  443. try:
  444. cookieprefix = 'http.cookiefile='
  445. proxyprefix = 'http.proxy='
  446. cookiefile = None
  447. proxy = None
  448. for line in p.stdout:
  449. line = line.strip().decode('utf-8')
  450. if line.startswith(cookieprefix):
  451. cookiefile = os.path.expanduser(line[len(cookieprefix):])
  452. if line.startswith(proxyprefix):
  453. proxy = line[len(proxyprefix):]
  454. # Leave subprocess open, as cookie file may be transient.
  455. if cookiefile or proxy:
  456. yield cookiefile, proxy
  457. return
  458. finally:
  459. p.stdin.close()
  460. if p.wait():
  461. err_msg = p.stderr.read().decode('utf-8')
  462. if ' -print_config' in err_msg:
  463. pass # Persistent proxy doesn't support -print_config.
  464. elif not quiet:
  465. print(err_msg, file=sys.stderr)
  466. except OSError as e:
  467. if e.errno == errno.ENOENT:
  468. pass # No persistent proxy.
  469. raise
  470. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  471. if cookiefile:
  472. cookiefile = os.path.expanduser(cookiefile)
  473. yield cookiefile, None
  474. def _preconnect(url):
  475. m = URI_ALL.match(url)
  476. if m:
  477. scheme = m.group(1)
  478. host = m.group(2)
  479. if ':' in host:
  480. host, port = host.split(':')
  481. else:
  482. port = None
  483. if scheme in ('ssh', 'git+ssh', 'ssh+git'):
  484. return _open_ssh(host, port)
  485. return False
  486. m = URI_SCP.match(url)
  487. if m:
  488. host = m.group(1)
  489. return _open_ssh(host)
  490. return False
  491. class Remote(object):
  492. """Configuration options related to a remote.
  493. """
  494. def __init__(self, config, name):
  495. self._config = config
  496. self.name = name
  497. self.url = self._Get('url')
  498. self.pushUrl = self._Get('pushurl')
  499. self.review = self._Get('review')
  500. self.projectname = self._Get('projectname')
  501. self.fetch = list(map(RefSpec.FromString,
  502. self._Get('fetch', all_keys=True)))
  503. self._review_url = None
  504. def _InsteadOf(self):
  505. globCfg = GitConfig.ForUser()
  506. urlList = globCfg.GetSubSections('url')
  507. longest = ""
  508. longestUrl = ""
  509. for url in urlList:
  510. key = "url." + url + ".insteadOf"
  511. insteadOfList = globCfg.GetString(key, all_keys=True)
  512. for insteadOf in insteadOfList:
  513. if self.url.startswith(insteadOf) \
  514. and len(insteadOf) > len(longest):
  515. longest = insteadOf
  516. longestUrl = url
  517. if len(longest) == 0:
  518. return self.url
  519. return self.url.replace(longest, longestUrl, 1)
  520. def PreConnectFetch(self):
  521. connectionUrl = self._InsteadOf()
  522. return _preconnect(connectionUrl)
  523. def ReviewUrl(self, userEmail, validate_certs):
  524. if self._review_url is None:
  525. if self.review is None:
  526. return None
  527. u = self.review
  528. if u.startswith('persistent-'):
  529. u = u[len('persistent-'):]
  530. if u.split(':')[0] not in ('http', 'https', 'sso', 'ssh'):
  531. u = 'http://%s' % u
  532. if u.endswith('/Gerrit'):
  533. u = u[:len(u) - len('/Gerrit')]
  534. if u.endswith('/ssh_info'):
  535. u = u[:len(u) - len('/ssh_info')]
  536. if not u.endswith('/'):
  537. u += '/'
  538. http_url = u
  539. if u in REVIEW_CACHE:
  540. self._review_url = REVIEW_CACHE[u]
  541. elif 'REPO_HOST_PORT_INFO' in os.environ:
  542. host, port = os.environ['REPO_HOST_PORT_INFO'].split()
  543. self._review_url = self._SshReviewUrl(userEmail, host, port)
  544. REVIEW_CACHE[u] = self._review_url
  545. elif u.startswith('sso:') or u.startswith('ssh:'):
  546. self._review_url = u # Assume it's right
  547. REVIEW_CACHE[u] = self._review_url
  548. elif 'REPO_IGNORE_SSH_INFO' in os.environ:
  549. self._review_url = http_url
  550. REVIEW_CACHE[u] = self._review_url
  551. else:
  552. try:
  553. info_url = u + 'ssh_info'
  554. if not validate_certs:
  555. context = ssl._create_unverified_context()
  556. info = urllib.request.urlopen(info_url, context=context).read()
  557. else:
  558. info = urllib.request.urlopen(info_url).read()
  559. if info == b'NOT_AVAILABLE' or b'<' in info:
  560. # If `info` contains '<', we assume the server gave us some sort
  561. # of HTML response back, like maybe a login page.
  562. #
  563. # Assume HTTP if SSH is not enabled or ssh_info doesn't look right.
  564. self._review_url = http_url
  565. else:
  566. info = info.decode('utf-8')
  567. host, port = info.split()
  568. self._review_url = self._SshReviewUrl(userEmail, host, port)
  569. except urllib.error.HTTPError as e:
  570. raise UploadError('%s: %s' % (self.review, str(e)))
  571. except urllib.error.URLError as e:
  572. raise UploadError('%s: %s' % (self.review, str(e)))
  573. except HTTPException as e:
  574. raise UploadError('%s: %s' % (self.review, e.__class__.__name__))
  575. REVIEW_CACHE[u] = self._review_url
  576. return self._review_url + self.projectname
  577. def _SshReviewUrl(self, userEmail, host, port):
  578. username = self._config.GetString('review.%s.username' % self.review)
  579. if username is None:
  580. username = userEmail.split('@')[0]
  581. return 'ssh://%s@%s:%s/' % (username, host, port)
  582. def ToLocal(self, rev):
  583. """Convert a remote revision string to something we have locally.
  584. """
  585. if self.name == '.' or IsId(rev):
  586. return rev
  587. if not rev.startswith('refs/'):
  588. rev = R_HEADS + rev
  589. for spec in self.fetch:
  590. if spec.SourceMatches(rev):
  591. return spec.MapSource(rev)
  592. if not rev.startswith(R_HEADS):
  593. return rev
  594. raise GitError('%s: remote %s does not have %s' %
  595. (self.projectname, 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. with open(self._config.file, 'a') as fd:
  658. fd.write('[branch "%s"]\n' % self.name)
  659. if self.remote:
  660. fd.write('\tremote = %s\n' % self.remote.name)
  661. if self.merge:
  662. fd.write('\tmerge = %s\n' % self.merge)
  663. def _Set(self, key, value):
  664. key = 'branch.%s.%s' % (self.name, key)
  665. return self._config.SetString(key, value)
  666. def _Get(self, key, all_keys=False):
  667. key = 'branch.%s.%s' % (self.name, key)
  668. return self._config.GetString(key, all_keys=all_keys)