git_config.py 17 KB

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