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