git_config.py 19 KB

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