git_config.py 17 KB

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