git_config.py 21 KB

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