git_config.py 18 KB

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