git_config.py 22 KB

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