git_config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 IOError:
  208. os.remove(self._pickle)
  209. return None
  210. except cPickle.PickleError:
  211. os.remove(self._pickle)
  212. return None
  213. def _SavePickle(self, cache):
  214. try:
  215. fd = open(self._pickle, 'wb')
  216. try:
  217. cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
  218. finally:
  219. fd.close()
  220. except IOError:
  221. os.remove(self._pickle)
  222. except cPickle.PickleError:
  223. os.remove(self._pickle)
  224. def _ReadGit(self):
  225. d = self._do('--null', '--list')
  226. c = {}
  227. while d:
  228. lf = d.index('\n')
  229. nul = d.index('\0', lf + 1)
  230. key = _key(d[0:lf])
  231. val = d[lf + 1:nul]
  232. if key in c:
  233. c[key].append(val)
  234. else:
  235. c[key] = [val]
  236. d = d[nul + 1:]
  237. return c
  238. def _do(self, *args):
  239. command = ['config', '--file', self.file]
  240. command.extend(args)
  241. p = GitCommand(None,
  242. command,
  243. capture_stdout = True,
  244. capture_stderr = True)
  245. if p.Wait() == 0:
  246. return p.stdout
  247. else:
  248. GitError('git config %s: %s' % (str(args), p.stderr))
  249. class RefSpec(object):
  250. """A Git refspec line, split into its components:
  251. forced: True if the line starts with '+'
  252. src: Left side of the line
  253. dst: Right side of the line
  254. """
  255. @classmethod
  256. def FromString(cls, rs):
  257. lhs, rhs = rs.split(':', 2)
  258. if lhs.startswith('+'):
  259. lhs = lhs[1:]
  260. forced = True
  261. else:
  262. forced = False
  263. return cls(forced, lhs, rhs)
  264. def __init__(self, forced, lhs, rhs):
  265. self.forced = forced
  266. self.src = lhs
  267. self.dst = rhs
  268. def SourceMatches(self, rev):
  269. if self.src:
  270. if rev == self.src:
  271. return True
  272. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  273. return True
  274. return False
  275. def DestMatches(self, ref):
  276. if self.dst:
  277. if ref == self.dst:
  278. return True
  279. if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
  280. return True
  281. return False
  282. def MapSource(self, rev):
  283. if self.src.endswith('/*'):
  284. return self.dst[:-1] + rev[len(self.src) - 1:]
  285. return self.dst
  286. def __str__(self):
  287. s = ''
  288. if self.forced:
  289. s += '+'
  290. if self.src:
  291. s += self.src
  292. if self.dst:
  293. s += ':'
  294. s += self.dst
  295. return s
  296. _ssh_cache = {}
  297. _ssh_master = True
  298. def _open_ssh(host, port):
  299. global _ssh_master
  300. key = '%s:%s' % (host, port)
  301. if key in _ssh_cache:
  302. return True
  303. if not _ssh_master \
  304. or 'GIT_SSH' in os.environ \
  305. or sys.platform in ('win32', 'cygwin'):
  306. # failed earlier, or cygwin ssh can't do this
  307. #
  308. return False
  309. command = ['ssh',
  310. '-o','ControlPath %s' % _ssh_sock(),
  311. '-p',str(port),
  312. '-M',
  313. '-N',
  314. host]
  315. try:
  316. Trace(': %s', ' '.join(command))
  317. p = subprocess.Popen(command)
  318. except Exception, e:
  319. _ssh_master = False
  320. print >>sys.stderr, \
  321. '\nwarn: cannot enable ssh control master for %s:%s\n%s' \
  322. % (host,port, str(e))
  323. return False
  324. _ssh_cache[key] = p
  325. time.sleep(1)
  326. return True
  327. def close_ssh():
  328. for key,p in _ssh_cache.iteritems():
  329. os.kill(p.pid, SIGTERM)
  330. p.wait()
  331. _ssh_cache.clear()
  332. d = _ssh_sock(create=False)
  333. if d:
  334. try:
  335. os.rmdir(os.path.dirname(d))
  336. except OSError:
  337. pass
  338. URI_SCP = re.compile(r'^([^@:]*@?[^:/]{1,}):')
  339. URI_ALL = re.compile(r'^([a-z][a-z+]*)://([^@/]*@?[^/]*)/')
  340. def _preconnect(url):
  341. m = URI_ALL.match(url)
  342. if m:
  343. scheme = m.group(1)
  344. host = m.group(2)
  345. if ':' in host:
  346. host, port = host.split(':')
  347. else:
  348. port = 22
  349. if scheme in ('ssh', 'git+ssh', 'ssh+git'):
  350. return _open_ssh(host, port)
  351. return False
  352. m = URI_SCP.match(url)
  353. if m:
  354. host = m.group(1)
  355. return _open_ssh(host, 22)
  356. class Remote(object):
  357. """Configuration options related to a remote.
  358. """
  359. def __init__(self, config, name):
  360. self._config = config
  361. self.name = name
  362. self.url = self._Get('url')
  363. self.review = self._Get('review')
  364. self.projectname = self._Get('projectname')
  365. self.fetch = map(lambda x: RefSpec.FromString(x),
  366. self._Get('fetch', all=True))
  367. self._review_protocol = None
  368. def PreConnectFetch(self):
  369. return _preconnect(self.url)
  370. @property
  371. def ReviewProtocol(self):
  372. if self._review_protocol is None:
  373. if self.review is None:
  374. return None
  375. u = self.review
  376. if not u.startswith('http:') and not u.startswith('https:'):
  377. u = 'http://%s' % u
  378. if u.endswith('/Gerrit'):
  379. u = u[:len(u) - len('/Gerrit')]
  380. if not u.endswith('/ssh_info'):
  381. if not u.endswith('/'):
  382. u += '/'
  383. u += 'ssh_info'
  384. if u in REVIEW_CACHE:
  385. info = REVIEW_CACHE[u]
  386. self._review_protocol = info[0]
  387. self._review_host = info[1]
  388. self._review_port = info[2]
  389. else:
  390. try:
  391. info = urlopen(u).read()
  392. if info == 'NOT_AVAILABLE':
  393. raise UploadError('Upload over ssh unavailable')
  394. if '<' in info:
  395. # Assume the server gave us some sort of HTML
  396. # response back, like maybe a login page.
  397. #
  398. raise UploadError('Cannot read %s:\n%s' % (u, info))
  399. self._review_protocol = 'ssh'
  400. self._review_host = info.split(" ")[0]
  401. self._review_port = info.split(" ")[1]
  402. except HTTPError, e:
  403. if e.code == 404:
  404. self._review_protocol = 'http-post'
  405. self._review_host = None
  406. self._review_port = None
  407. else:
  408. raise UploadError('Cannot guess Gerrit version')
  409. REVIEW_CACHE[u] = (
  410. self._review_protocol,
  411. self._review_host,
  412. self._review_port)
  413. return self._review_protocol
  414. def SshReviewUrl(self, userEmail):
  415. if self.ReviewProtocol != 'ssh':
  416. return None
  417. return 'ssh://%s@%s:%s/%s' % (
  418. userEmail.split("@")[0],
  419. self._review_host,
  420. self._review_port,
  421. self.projectname)
  422. def ToLocal(self, rev):
  423. """Convert a remote revision string to something we have locally.
  424. """
  425. if IsId(rev):
  426. return rev
  427. if rev.startswith(R_TAGS):
  428. return rev
  429. if not rev.startswith('refs/'):
  430. rev = R_HEADS + rev
  431. for spec in self.fetch:
  432. if spec.SourceMatches(rev):
  433. return spec.MapSource(rev)
  434. raise GitError('remote %s does not have %s' % (self.name, rev))
  435. def WritesTo(self, ref):
  436. """True if the remote stores to the tracking ref.
  437. """
  438. for spec in self.fetch:
  439. if spec.DestMatches(ref):
  440. return True
  441. return False
  442. def ResetFetch(self, mirror=False):
  443. """Set the fetch refspec to its default value.
  444. """
  445. if mirror:
  446. dst = 'refs/heads/*'
  447. else:
  448. dst = 'refs/remotes/%s/*' % self.name
  449. self.fetch = [RefSpec(True, 'refs/heads/*', dst)]
  450. def Save(self):
  451. """Save this remote to the configuration.
  452. """
  453. self._Set('url', self.url)
  454. self._Set('review', self.review)
  455. self._Set('projectname', self.projectname)
  456. self._Set('fetch', map(lambda x: str(x), self.fetch))
  457. def _Set(self, key, value):
  458. key = 'remote.%s.%s' % (self.name, key)
  459. return self._config.SetString(key, value)
  460. def _Get(self, key, all=False):
  461. key = 'remote.%s.%s' % (self.name, key)
  462. return self._config.GetString(key, all = all)
  463. class Branch(object):
  464. """Configuration options related to a single branch.
  465. """
  466. def __init__(self, config, name):
  467. self._config = config
  468. self.name = name
  469. self.merge = self._Get('merge')
  470. r = self._Get('remote')
  471. if r:
  472. self.remote = self._config.GetRemote(r)
  473. else:
  474. self.remote = None
  475. @property
  476. def LocalMerge(self):
  477. """Convert the merge spec to a local name.
  478. """
  479. if self.remote and self.merge:
  480. return self.remote.ToLocal(self.merge)
  481. return None
  482. def Save(self):
  483. """Save this branch back into the configuration.
  484. """
  485. if self._config.HasSection('branch', self.name):
  486. if self.remote:
  487. self._Set('remote', self.remote.name)
  488. else:
  489. self._Set('remote', None)
  490. self._Set('merge', self.merge)
  491. else:
  492. fd = open(self._config.file, 'ab')
  493. try:
  494. fd.write('[branch "%s"]\n' % self.name)
  495. if self.remote:
  496. fd.write('\tremote = %s\n' % self.remote.name)
  497. if self.merge:
  498. fd.write('\tmerge = %s\n' % self.merge)
  499. finally:
  500. fd.close()
  501. def _Set(self, key, value):
  502. key = 'branch.%s.%s' % (self.name, key)
  503. return self._config.SetString(key, value)
  504. def _Get(self, key, all=False):
  505. key = 'branch.%s.%s' % (self.name, key)
  506. return self._config.GetString(key, all = all)