git_config.py 19 KB

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