git_config.py 21 KB

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