git_config.py 18 KB

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