git_config.py 21 KB

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