git_config.py 19 KB

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