git_config.py 15 KB

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