git_config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. import time
  21. from signal import SIGTERM
  22. from urllib2 import urlopen, HTTPError
  23. from error import GitError, UploadError
  24. from trace import Trace
  25. from git_command import GitCommand, _ssh_sock
  26. R_HEADS = 'refs/heads/'
  27. R_TAGS = 'refs/tags/'
  28. ID_RE = re.compile('^[0-9a-f]{40}$')
  29. REVIEW_CACHE = dict()
  30. def IsId(rev):
  31. return ID_RE.match(rev)
  32. def _key(name):
  33. parts = name.split('.')
  34. if len(parts) < 2:
  35. return name.lower()
  36. parts[ 0] = parts[ 0].lower()
  37. parts[-1] = parts[-1].lower()
  38. return '.'.join(parts)
  39. class GitConfig(object):
  40. _ForUser = None
  41. @classmethod
  42. def ForUser(cls):
  43. if cls._ForUser is None:
  44. cls._ForUser = cls(file = os.path.expanduser('~/.gitconfig'))
  45. return cls._ForUser
  46. @classmethod
  47. def ForRepository(cls, gitdir, defaults=None):
  48. return cls(file = os.path.join(gitdir, 'config'),
  49. defaults = defaults)
  50. def __init__(self, file, defaults=None):
  51. self.file = file
  52. self.defaults = defaults
  53. self._cache_dict = None
  54. self._section_dict = None
  55. self._remotes = {}
  56. self._branches = {}
  57. self._pickle = os.path.join(
  58. os.path.dirname(self.file),
  59. '.repopickle_' + os.path.basename(self.file))
  60. def Has(self, name, include_defaults = True):
  61. """Return true if this configuration file has the key.
  62. """
  63. if _key(name) in self._cache:
  64. return True
  65. if include_defaults and self.defaults:
  66. return self.defaults.Has(name, include_defaults = True)
  67. return False
  68. def GetBoolean(self, name):
  69. """Returns a boolean from the configuration file.
  70. None : The value was not defined, or is not a boolean.
  71. True : The value was set to true or yes.
  72. False: The value was set to false or no.
  73. """
  74. v = self.GetString(name)
  75. if v is None:
  76. return None
  77. v = v.lower()
  78. if v in ('true', 'yes'):
  79. return True
  80. if v in ('false', 'no'):
  81. return False
  82. return None
  83. def GetString(self, name, all=False):
  84. """Get the first value for a key, or None if it is not defined.
  85. This configuration file is used first, if the key is not
  86. defined or all = True then the defaults are also searched.
  87. """
  88. try:
  89. v = self._cache[_key(name)]
  90. except KeyError:
  91. if self.defaults:
  92. return self.defaults.GetString(name, all = all)
  93. v = []
  94. if not all:
  95. if v:
  96. return v[0]
  97. return None
  98. r = []
  99. r.extend(v)
  100. if self.defaults:
  101. r.extend(self.defaults.GetString(name, all = True))
  102. return r
  103. def SetString(self, name, value):
  104. """Set the value(s) for a key.
  105. Only this configuration file is modified.
  106. The supplied value should be either a string,
  107. or a list of strings (to store multiple values).
  108. """
  109. key = _key(name)
  110. try:
  111. old = self._cache[key]
  112. except KeyError:
  113. old = []
  114. if value is None:
  115. if old:
  116. del self._cache[key]
  117. self._do('--unset-all', name)
  118. elif isinstance(value, list):
  119. if len(value) == 0:
  120. self.SetString(name, None)
  121. elif len(value) == 1:
  122. self.SetString(name, value[0])
  123. elif old != value:
  124. self._cache[key] = list(value)
  125. self._do('--replace-all', name, value[0])
  126. for i in xrange(1, len(value)):
  127. self._do('--add', name, value[i])
  128. elif len(old) != 1 or old[0] != value:
  129. self._cache[key] = [value]
  130. self._do('--replace-all', name, value)
  131. def GetRemote(self, name):
  132. """Get the remote.$name.* configuration values as an object.
  133. """
  134. try:
  135. r = self._remotes[name]
  136. except KeyError:
  137. r = Remote(self, name)
  138. self._remotes[r.name] = r
  139. return r
  140. def GetBranch(self, name):
  141. """Get the branch.$name.* configuration values as an object.
  142. """
  143. try:
  144. b = self._branches[name]
  145. except KeyError:
  146. b = Branch(self, name)
  147. self._branches[b.name] = b
  148. return b
  149. def HasSection(self, section, subsection = ''):
  150. """Does at least one key in section.subsection exist?
  151. """
  152. try:
  153. return subsection in self._sections[section]
  154. except KeyError:
  155. return False
  156. @property
  157. def _sections(self):
  158. d = self._section_dict
  159. if d is None:
  160. d = {}
  161. for name in self._cache.keys():
  162. p = name.split('.')
  163. if 2 == len(p):
  164. section = p[0]
  165. subsect = ''
  166. else:
  167. section = p[0]
  168. subsect = '.'.join(p[1:-1])
  169. if section not in d:
  170. d[section] = set()
  171. d[section].add(subsect)
  172. self._section_dict = d
  173. return d
  174. @property
  175. def _cache(self):
  176. if self._cache_dict is None:
  177. self._cache_dict = self._Read()
  178. return self._cache_dict
  179. def _Read(self):
  180. d = self._ReadPickle()
  181. if d is None:
  182. d = self._ReadGit()
  183. self._SavePickle(d)
  184. return d
  185. def _ReadPickle(self):
  186. try:
  187. if os.path.getmtime(self._pickle) \
  188. <= os.path.getmtime(self.file):
  189. os.remove(self._pickle)
  190. return None
  191. except OSError:
  192. return None
  193. try:
  194. Trace(': unpickle %s', self.file)
  195. fd = open(self._pickle, 'rb')
  196. try:
  197. return cPickle.load(fd)
  198. finally:
  199. fd.close()
  200. except IOError:
  201. os.remove(self._pickle)
  202. return None
  203. except cPickle.PickleError:
  204. os.remove(self._pickle)
  205. return None
  206. def _SavePickle(self, cache):
  207. try:
  208. fd = open(self._pickle, 'wb')
  209. try:
  210. cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
  211. finally:
  212. fd.close()
  213. except IOError:
  214. os.remove(self._pickle)
  215. except cPickle.PickleError:
  216. os.remove(self._pickle)
  217. def _ReadGit(self):
  218. d = self._do('--null', '--list')
  219. c = {}
  220. while d:
  221. lf = d.index('\n')
  222. nul = d.index('\0', lf + 1)
  223. key = _key(d[0:lf])
  224. val = d[lf + 1:nul]
  225. if key in c:
  226. c[key].append(val)
  227. else:
  228. c[key] = [val]
  229. d = d[nul + 1:]
  230. return c
  231. def _do(self, *args):
  232. command = ['config', '--file', self.file]
  233. command.extend(args)
  234. p = GitCommand(None,
  235. command,
  236. capture_stdout = True,
  237. capture_stderr = True)
  238. if p.Wait() == 0:
  239. return p.stdout
  240. else:
  241. GitError('git config %s: %s' % (str(args), p.stderr))
  242. class RefSpec(object):
  243. """A Git refspec line, split into its components:
  244. forced: True if the line starts with '+'
  245. src: Left side of the line
  246. dst: Right side of the line
  247. """
  248. @classmethod
  249. def FromString(cls, rs):
  250. lhs, rhs = rs.split(':', 2)
  251. if lhs.startswith('+'):
  252. lhs = lhs[1:]
  253. forced = True
  254. else:
  255. forced = False
  256. return cls(forced, lhs, rhs)
  257. def __init__(self, forced, lhs, rhs):
  258. self.forced = forced
  259. self.src = lhs
  260. self.dst = rhs
  261. def SourceMatches(self, rev):
  262. if self.src:
  263. if rev == self.src:
  264. return True
  265. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  266. return True
  267. return False
  268. def DestMatches(self, ref):
  269. if self.dst:
  270. if ref == self.dst:
  271. return True
  272. if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
  273. return True
  274. return False
  275. def MapSource(self, rev):
  276. if self.src.endswith('/*'):
  277. return self.dst[:-1] + rev[len(self.src) - 1:]
  278. return self.dst
  279. def __str__(self):
  280. s = ''
  281. if self.forced:
  282. s += '+'
  283. if self.src:
  284. s += self.src
  285. if self.dst:
  286. s += ':'
  287. s += self.dst
  288. return s
  289. _ssh_cache = {}
  290. _ssh_master = True
  291. def _open_ssh(host, port=None):
  292. global _ssh_master
  293. if port is None:
  294. port = 22
  295. key = '%s:%s' % (host, port)
  296. if key in _ssh_cache:
  297. return True
  298. if not _ssh_master \
  299. or 'GIT_SSH' in os.environ \
  300. or sys.platform == 'win32':
  301. # failed earlier, or cygwin ssh can't do this
  302. #
  303. return False
  304. command = ['ssh',
  305. '-o','ControlPath %s' % _ssh_sock(),
  306. '-p',str(port),
  307. '-M',
  308. '-N',
  309. host]
  310. try:
  311. Trace(': %s', ' '.join(command))
  312. p = subprocess.Popen(command)
  313. except Exception, e:
  314. _ssh_master = False
  315. print >>sys.stderr, \
  316. '\nwarn: cannot enable ssh control master for %s:%s\n%s' \
  317. % (host,port, str(e))
  318. return False
  319. _ssh_cache[key] = p
  320. time.sleep(1)
  321. return True
  322. def close_ssh():
  323. for key,p in _ssh_cache.iteritems():
  324. os.kill(p.pid, SIGTERM)
  325. p.wait()
  326. _ssh_cache.clear()
  327. d = _ssh_sock(create=False)
  328. if d:
  329. try:
  330. os.rmdir(os.path.dirname(d))
  331. except OSError:
  332. pass
  333. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  334. URI_ALL = re.compile(r'^([a-z][a-z+]*)://([^@/]*@?[^/])/')
  335. def _preconnect(url):
  336. m = URI_ALL.match(url)
  337. if m:
  338. scheme = m.group(1)
  339. host = m.group(2)
  340. if ':' in host:
  341. host, port = host.split(':')
  342. if scheme in ('ssh', 'git+ssh', 'ssh+git'):
  343. return _open_ssh(host, port)
  344. return False
  345. m = URI_SCP.match(url)
  346. if m:
  347. host = m.group(1)
  348. return _open_ssh(host)
  349. class Remote(object):
  350. """Configuration options related to a remote.
  351. """
  352. def __init__(self, config, name):
  353. self._config = config
  354. self.name = name
  355. self.url = self._Get('url')
  356. self.review = self._Get('review')
  357. self.projectname = self._Get('projectname')
  358. self.fetch = map(lambda x: RefSpec.FromString(x),
  359. self._Get('fetch', all=True))
  360. self._review_protocol = None
  361. def PreConnectFetch(self):
  362. return _preconnect(self.url)
  363. @property
  364. def ReviewProtocol(self):
  365. if self._review_protocol is None:
  366. if self.review is None:
  367. return None
  368. u = self.review
  369. if not u.startswith('http:') and not u.startswith('https:'):
  370. u = 'http://%s' % u
  371. if u.endswith('/Gerrit'):
  372. u = u[:len(u) - len('/Gerrit')]
  373. if not u.endswith('/ssh_info'):
  374. if not u.endswith('/'):
  375. u += '/'
  376. u += 'ssh_info'
  377. if u in REVIEW_CACHE:
  378. info = REVIEW_CACHE[u]
  379. self._review_protocol = info[0]
  380. self._review_host = info[1]
  381. self._review_port = info[2]
  382. else:
  383. try:
  384. info = urlopen(u).read()
  385. if info == 'NOT_AVAILABLE':
  386. raise UploadError('Upload over ssh unavailable')
  387. if '<' in info:
  388. # Assume the server gave us some sort of HTML
  389. # response back, like maybe a login page.
  390. #
  391. raise UploadError('Cannot read %s:\n%s' % (u, info))
  392. self._review_protocol = 'ssh'
  393. self._review_host = info.split(" ")[0]
  394. self._review_port = info.split(" ")[1]
  395. except HTTPError, e:
  396. if e.code == 404:
  397. self._review_protocol = 'http-post'
  398. self._review_host = None
  399. self._review_port = None
  400. else:
  401. raise UploadError('Cannot guess Gerrit version')
  402. REVIEW_CACHE[u] = (
  403. self._review_protocol,
  404. self._review_host,
  405. self._review_port)
  406. return self._review_protocol
  407. def SshReviewUrl(self, userEmail):
  408. if self.ReviewProtocol != 'ssh':
  409. return None
  410. return 'ssh://%s@%s:%s/%s' % (
  411. userEmail.split("@")[0],
  412. self._review_host,
  413. self._review_port,
  414. self.projectname)
  415. def ToLocal(self, rev):
  416. """Convert a remote revision string to something we have locally.
  417. """
  418. if IsId(rev):
  419. return rev
  420. if rev.startswith(R_TAGS):
  421. return rev
  422. if not rev.startswith('refs/'):
  423. rev = R_HEADS + rev
  424. for spec in self.fetch:
  425. if spec.SourceMatches(rev):
  426. return spec.MapSource(rev)
  427. raise GitError('remote %s does not have %s' % (self.name, rev))
  428. def WritesTo(self, ref):
  429. """True if the remote stores to the tracking ref.
  430. """
  431. for spec in self.fetch:
  432. if spec.DestMatches(ref):
  433. return True
  434. return False
  435. def ResetFetch(self, mirror=False):
  436. """Set the fetch refspec to its default value.
  437. """
  438. if mirror:
  439. dst = 'refs/heads/*'
  440. else:
  441. dst = 'refs/remotes/%s/*' % self.name
  442. self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
  443. def Save(self):
  444. """Save this remote to the configuration.
  445. """
  446. self._Set('url', self.url)
  447. self._Set('review', self.review)
  448. self._Set('projectname', self.projectname)
  449. self._Set('fetch', map(lambda x: str(x), self.fetch))
  450. def _Set(self, key, value):
  451. key = 'remote.%s.%s' % (self.name, key)
  452. return self._config.SetString(key, value)
  453. def _Get(self, key, all=False):
  454. key = 'remote.%s.%s' % (self.name, key)
  455. return self._config.GetString(key, all = all)
  456. class Branch(object):
  457. """Configuration options related to a single branch.
  458. """
  459. def __init__(self, config, name):
  460. self._config = config
  461. self.name = name
  462. self.merge = self._Get('merge')
  463. r = self._Get('remote')
  464. if r:
  465. self.remote = self._config.GetRemote(r)
  466. else:
  467. self.remote = None
  468. @property
  469. def LocalMerge(self):
  470. """Convert the merge spec to a local name.
  471. """
  472. if self.remote and self.merge:
  473. return self.remote.ToLocal(self.merge)
  474. return None
  475. def Save(self):
  476. """Save this branch back into the configuration.
  477. """
  478. if self._config.HasSection('branch', self.name):
  479. if self.remote:
  480. self._Set('remote', self.remote.name)
  481. else:
  482. self._Set('remote', None)
  483. self._Set('merge', self.merge)
  484. else:
  485. fd = open(self._config.file, 'ab')
  486. try:
  487. fd.write('[branch "%s"]\n' % self.name)
  488. if self.remote:
  489. fd.write('\tremote = %s\n' % self.remote.name)
  490. if self.merge:
  491. fd.write('\tmerge = %s\n' % self.merge)
  492. finally:
  493. fd.close()
  494. def _Set(self, key, value):
  495. key = 'branch.%s.%s' % (self.name, key)
  496. return self._config.SetString(key, value)
  497. def _Get(self, key, all=False):
  498. key = 'branch.%s.%s' % (self.name, key)
  499. return self._config.GetString(key, all = all)