git_config.py 18 KB

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