git_config.py 15 KB

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