git_config.py 20 KB

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