git_config.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 os
  16. import re
  17. import sys
  18. from error import GitError
  19. from git_command import GitCommand
  20. R_HEADS = 'refs/heads/'
  21. R_TAGS = 'refs/tags/'
  22. ID_RE = re.compile('^[0-9a-f]{40}$')
  23. def IsId(rev):
  24. return ID_RE.match(rev)
  25. class GitConfig(object):
  26. @classmethod
  27. def ForUser(cls):
  28. return cls(file = os.path.expanduser('~/.gitconfig'))
  29. @classmethod
  30. def ForRepository(cls, gitdir, defaults=None):
  31. return cls(file = os.path.join(gitdir, 'config'),
  32. defaults = defaults)
  33. def __init__(self, file, defaults=None):
  34. self.file = file
  35. self.defaults = defaults
  36. self._cache_dict = None
  37. self._remotes = {}
  38. self._branches = {}
  39. def Has(self, name, include_defaults = True):
  40. """Return true if this configuration file has the key.
  41. """
  42. name = name.lower()
  43. if name in self._cache:
  44. return True
  45. if include_defaults and self.defaults:
  46. return self.defaults.Has(name, include_defaults = True)
  47. return False
  48. def GetBoolean(self, name):
  49. """Returns a boolean from the configuration file.
  50. None : The value was not defined, or is not a boolean.
  51. True : The value was set to true or yes.
  52. False: The value was set to false or no.
  53. """
  54. v = self.GetString(name)
  55. if v is None:
  56. return None
  57. v = v.lower()
  58. if v in ('true', 'yes'):
  59. return True
  60. if v in ('false', 'no'):
  61. return False
  62. return None
  63. def GetString(self, name, all=False):
  64. """Get the first value for a key, or None if it is not defined.
  65. This configuration file is used first, if the key is not
  66. defined or all = True then the defaults are also searched.
  67. """
  68. name = name.lower()
  69. try:
  70. v = self._cache[name]
  71. except KeyError:
  72. if self.defaults:
  73. return self.defaults.GetString(name, all = all)
  74. v = []
  75. if not all:
  76. if v:
  77. return v[0]
  78. return None
  79. r = []
  80. r.extend(v)
  81. if self.defaults:
  82. r.extend(self.defaults.GetString(name, all = True))
  83. return r
  84. def SetString(self, name, value):
  85. """Set the value(s) for a key.
  86. Only this configuration file is modified.
  87. The supplied value should be either a string,
  88. or a list of strings (to store multiple values).
  89. """
  90. name = name.lower()
  91. try:
  92. old = self._cache[name]
  93. except KeyError:
  94. old = []
  95. if value is None:
  96. if old:
  97. del self._cache[name]
  98. self._do('--unset-all', name)
  99. elif isinstance(value, list):
  100. if len(value) == 0:
  101. self.SetString(name, None)
  102. elif len(value) == 1:
  103. self.SetString(name, value[0])
  104. elif old != value:
  105. self._cache[name] = list(value)
  106. self._do('--replace-all', name, value[0])
  107. for i in xrange(1, len(value)):
  108. self._do('--add', name, value[i])
  109. elif len(old) != 1 or old[0] != value:
  110. self._cache[name] = [value]
  111. self._do('--replace-all', name, value)
  112. def GetRemote(self, name):
  113. """Get the remote.$name.* configuration values as an object.
  114. """
  115. try:
  116. r = self._remotes[name]
  117. except KeyError:
  118. r = Remote(self, name)
  119. self._remotes[r.name] = r
  120. return r
  121. def GetBranch(self, name):
  122. """Get the branch.$name.* configuration values as an object.
  123. """
  124. try:
  125. b = self._branches[name]
  126. except KeyError:
  127. b = Branch(self, name)
  128. self._branches[b.name] = b
  129. return b
  130. @property
  131. def _cache(self):
  132. if self._cache_dict is None:
  133. self._cache_dict = self._Read()
  134. return self._cache_dict
  135. def _Read(self):
  136. d = self._do('--null', '--list')
  137. c = {}
  138. while d:
  139. lf = d.index('\n')
  140. nul = d.index('\0', lf + 1)
  141. key = d[0:lf]
  142. val = d[lf + 1:nul]
  143. if key in c:
  144. c[key].append(val)
  145. else:
  146. c[key] = [val]
  147. d = d[nul + 1:]
  148. return c
  149. def _do(self, *args):
  150. command = ['config', '--file', self.file]
  151. command.extend(args)
  152. p = GitCommand(None,
  153. command,
  154. capture_stdout = True,
  155. capture_stderr = True)
  156. if p.Wait() == 0:
  157. return p.stdout
  158. else:
  159. GitError('git config %s: %s' % (str(args), p.stderr))
  160. class RefSpec(object):
  161. """A Git refspec line, split into its components:
  162. forced: True if the line starts with '+'
  163. src: Left side of the line
  164. dst: Right side of the line
  165. """
  166. @classmethod
  167. def FromString(cls, rs):
  168. lhs, rhs = rs.split(':', 2)
  169. if lhs.startswith('+'):
  170. lhs = lhs[1:]
  171. forced = True
  172. else:
  173. forced = False
  174. return cls(forced, lhs, rhs)
  175. def __init__(self, forced, lhs, rhs):
  176. self.forced = forced
  177. self.src = lhs
  178. self.dst = rhs
  179. def SourceMatches(self, rev):
  180. if self.src:
  181. if rev == self.src:
  182. return True
  183. if self.src.endswith('/*') and rev.startswith(self.src[:-1]):
  184. return True
  185. return False
  186. def DestMatches(self, ref):
  187. if self.dst:
  188. if ref == self.dst:
  189. return True
  190. if self.dst.endswith('/*') and ref.startswith(self.dst[:-1]):
  191. return True
  192. return False
  193. def MapSource(self, rev):
  194. if self.src.endswith('/*'):
  195. return self.dst[:-1] + rev[len(self.src) - 1:]
  196. return self.dst
  197. def __str__(self):
  198. s = ''
  199. if self.forced:
  200. s += '+'
  201. if self.src:
  202. s += self.src
  203. if self.dst:
  204. s += ':'
  205. s += self.dst
  206. return s
  207. class Remote(object):
  208. """Configuration options related to a remote.
  209. """
  210. def __init__(self, config, name):
  211. self._config = config
  212. self.name = name
  213. self.url = self._Get('url')
  214. self.review = self._Get('review')
  215. self.fetch = map(lambda x: RefSpec.FromString(x),
  216. self._Get('fetch', all=True))
  217. def ToLocal(self, rev):
  218. """Convert a remote revision string to something we have locally.
  219. """
  220. if IsId(rev):
  221. return rev
  222. if rev.startswith(R_TAGS):
  223. return rev
  224. if not rev.startswith('refs/'):
  225. rev = R_HEADS + rev
  226. for spec in self.fetch:
  227. if spec.SourceMatches(rev):
  228. return spec.MapSource(rev)
  229. raise GitError('remote %s does not have %s' % (self.name, rev))
  230. def WritesTo(self, ref):
  231. """True if the remote stores to the tracking ref.
  232. """
  233. for spec in self.fetch:
  234. if spec.DestMatches(ref):
  235. return True
  236. return False
  237. def ResetFetch(self):
  238. """Set the fetch refspec to its default value.
  239. """
  240. self.fetch = [RefSpec(True,
  241. 'refs/heads/*',
  242. 'refs/remotes/%s/*' % self.name)]
  243. def Save(self):
  244. """Save this remote to the configuration.
  245. """
  246. self._Set('url', self.url)
  247. self._Set('review', self.review)
  248. self._Set('fetch', map(lambda x: str(x), self.fetch))
  249. def _Set(self, key, value):
  250. key = 'remote.%s.%s' % (self.name, key)
  251. return self._config.SetString(key, value)
  252. def _Get(self, key, all=False):
  253. key = 'remote.%s.%s' % (self.name, key)
  254. return self._config.GetString(key, all = all)
  255. class Branch(object):
  256. """Configuration options related to a single branch.
  257. """
  258. def __init__(self, config, name):
  259. self._config = config
  260. self.name = name
  261. self.merge = self._Get('merge')
  262. r = self._Get('remote')
  263. if r:
  264. self.remote = self._config.GetRemote(r)
  265. else:
  266. self.remote = None
  267. @property
  268. def LocalMerge(self):
  269. """Convert the merge spec to a local name.
  270. """
  271. if self.remote and self.merge:
  272. return self.remote.ToLocal(self.merge)
  273. return None
  274. def Save(self):
  275. """Save this branch back into the configuration.
  276. """
  277. self._Set('merge', self.merge)
  278. if self.remote:
  279. self._Set('remote', self.remote.name)
  280. else:
  281. self._Set('remote', None)
  282. def _Set(self, key, value):
  283. key = 'branch.%s.%s' % (self.name, key)
  284. return self._config.SetString(key, value)
  285. def _Get(self, key, all=False):
  286. key = 'branch.%s.%s' % (self.name, key)
  287. return self._config.GetString(key, all = all)