config.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # config.py - Reading and writing Git config files
  2. # Copyright (C) 2011 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) a later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Reading and writing Git configuration files.
  19. TODO:
  20. * preserve formatting when updating configuration files
  21. * treat subsection names as case-insensitive for [branch.foo] style
  22. subsections
  23. """
  24. import errno
  25. import os
  26. import re
  27. from UserDict import DictMixin
  28. from dulwich.file import GitFile
  29. class Config(object):
  30. """A Git configuration."""
  31. def get(self, section, name):
  32. """Retrieve the contents of a configuration setting.
  33. :param section: Tuple with section name and optional subsection namee
  34. :param subsection: Subsection name
  35. :return: Contents of the setting
  36. :raise KeyError: if the value is not set
  37. """
  38. raise NotImplementedError(self.get)
  39. def get_boolean(self, section, name, default=None):
  40. """Retrieve a configuration setting as boolean.
  41. :param section: Tuple with section name and optional subsection namee
  42. :param name: Name of the setting, including section and possible
  43. subsection.
  44. :return: Contents of the setting
  45. :raise KeyError: if the value is not set
  46. """
  47. try:
  48. value = self.get(section, name)
  49. except KeyError:
  50. return default
  51. if value.lower() == "true":
  52. return True
  53. elif value.lower() == "false":
  54. return False
  55. raise ValueError("not a valid boolean string: %r" % value)
  56. def set(self, section, name, value):
  57. """Set a configuration value.
  58. :param name: Name of the configuration value, including section
  59. and optional subsection
  60. :param: Value of the setting
  61. """
  62. raise NotImplementedError(self.set)
  63. class ConfigDict(Config, DictMixin):
  64. """Git configuration stored in a dictionary."""
  65. def __init__(self, values=None):
  66. """Create a new ConfigDict."""
  67. if values is None:
  68. values = {}
  69. self._values = values
  70. def __repr__(self):
  71. return "%s(%r)" % (self.__class__.__name__, self._values)
  72. def __eq__(self, other):
  73. return (
  74. isinstance(other, self.__class__) and
  75. other._values == self._values)
  76. def __getitem__(self, key):
  77. return self._values[key]
  78. def __setitem__(self, key, value):
  79. self._values[key] = value
  80. def keys(self):
  81. return self._values.keys()
  82. @classmethod
  83. def _parse_setting(cls, name):
  84. parts = name.split(".")
  85. if len(parts) == 3:
  86. return (parts[0], parts[1], parts[2])
  87. else:
  88. return (parts[0], None, parts[1])
  89. def get(self, section, name):
  90. if isinstance(section, basestring):
  91. section = (section, )
  92. if len(section) > 1:
  93. try:
  94. return self._values[section][name]
  95. except KeyError:
  96. pass
  97. return self._values[(section[0],)][name]
  98. def set(self, section, name, value):
  99. if isinstance(section, basestring):
  100. section = (section, )
  101. self._values.setdefault(section, {})[name] = value
  102. def _format_string(value):
  103. if (value.startswith(" ") or
  104. value.startswith("\t") or
  105. value.endswith(" ") or
  106. value.endswith("\t")):
  107. return '"%s"' % _escape_value(value)
  108. return _escape_value(value)
  109. def _parse_string(value):
  110. value = value.strip()
  111. ret = []
  112. block = []
  113. in_quotes = False
  114. for c in value:
  115. if c == "\"":
  116. in_quotes = (not in_quotes)
  117. ret.append(_unescape_value("".join(block)))
  118. block = []
  119. elif c in ("#", ";") and not in_quotes:
  120. # the rest of the line is a comment
  121. break
  122. else:
  123. block.append(c)
  124. if in_quotes:
  125. raise ValueError("value starts with quote but lacks end quote")
  126. ret.append(_unescape_value("".join(block)).rstrip())
  127. return "".join(ret)
  128. def _unescape_value(value):
  129. """Unescape a value."""
  130. def unescape(c):
  131. return {
  132. "\\\\": "\\",
  133. "\\\"": "\"",
  134. "\\n": "\n",
  135. "\\t": "\t",
  136. "\\b": "\b",
  137. }[c.group(0)]
  138. return re.sub(r"(\\.)", unescape, value)
  139. def _escape_value(value):
  140. """Escape a value."""
  141. return value.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"")
  142. def _check_variable_name(name):
  143. for c in name:
  144. if not c.isalnum() and c != '-':
  145. return False
  146. return True
  147. def _check_section_name(name):
  148. for c in name:
  149. if not c.isalnum() and c not in ('-', '.'):
  150. return False
  151. return True
  152. def _strip_comments(line):
  153. line = line.split("#")[0]
  154. line = line.split(";")[0]
  155. return line
  156. class ConfigFile(ConfigDict):
  157. """A Git configuration file, like .git/config or ~/.gitconfig.
  158. """
  159. @classmethod
  160. def from_file(cls, f):
  161. """Read configuration from a file-like object."""
  162. ret = cls()
  163. section = None
  164. setting = None
  165. for lineno, line in enumerate(f.readlines()):
  166. line = line.lstrip()
  167. if setting is None:
  168. if len(line) > 0 and line[0] == "[":
  169. line = _strip_comments(line).rstrip()
  170. last = line.index("]")
  171. if last == -1:
  172. raise ValueError("expected trailing ]")
  173. pts = line[1:last].split(" ", 1)
  174. line = line[last+1:]
  175. pts[0] = pts[0].lower()
  176. if len(pts) == 2:
  177. if pts[1][0] != "\"" or pts[1][-1] != "\"":
  178. raise ValueError(
  179. "Invalid subsection " + pts[1])
  180. else:
  181. pts[1] = pts[1][1:-1]
  182. if not _check_section_name(pts[0]):
  183. raise ValueError("invalid section name %s" %
  184. pts[0])
  185. section = (pts[0], pts[1])
  186. else:
  187. if not _check_section_name(pts[0]):
  188. raise ValueError("invalid section name %s" %
  189. pts[0])
  190. pts = pts[0].split(".", 1)
  191. if len(pts) == 2:
  192. section = (pts[0], pts[1])
  193. else:
  194. section = (pts[0], )
  195. ret._values[section] = {}
  196. if _strip_comments(line).strip() == "":
  197. continue
  198. if section is None:
  199. raise ValueError("setting %r without section" % line)
  200. try:
  201. setting, value = line.split("=", 1)
  202. except ValueError:
  203. setting = line
  204. value = "true"
  205. setting = setting.strip().lower()
  206. if not _check_variable_name(setting):
  207. raise ValueError("invalid variable name %s" % setting)
  208. if value.endswith("\\\n"):
  209. value = value[:-2]
  210. continuation = True
  211. else:
  212. continuation = False
  213. value = _parse_string(value)
  214. ret._values[section][setting] = value
  215. if not continuation:
  216. setting = None
  217. else: # continuation line
  218. if line.endswith("\\\n"):
  219. line = line[:-2]
  220. continuation = True
  221. else:
  222. continuation = False
  223. value = _parse_string(line)
  224. ret._values[section][setting] += value
  225. if not continuation:
  226. setting = None
  227. return ret
  228. @classmethod
  229. def from_path(cls, path):
  230. """Read configuration from a file on disk."""
  231. f = GitFile(path, 'rb')
  232. try:
  233. ret = cls.from_file(f)
  234. ret.path = path
  235. return ret
  236. finally:
  237. f.close()
  238. def write_to_path(self, path=None):
  239. """Write configuration to a file on disk."""
  240. if path is None:
  241. path = self.path
  242. f = GitFile(path, 'wb')
  243. try:
  244. self.write_to_file(f)
  245. finally:
  246. f.close()
  247. def write_to_file(self, f):
  248. """Write configuration to a file-like object."""
  249. for section, values in self._values.iteritems():
  250. try:
  251. section_name, subsection_name = section
  252. except ValueError:
  253. (section_name, ) = section
  254. subsection_name = None
  255. if subsection_name is None:
  256. f.write("[%s]\n" % section_name)
  257. else:
  258. f.write("[%s \"%s\"]\n" % (section_name, subsection_name))
  259. for key, value in values.iteritems():
  260. f.write("%s = %s\n" % (key, _escape_value(value)))
  261. class StackedConfig(Config):
  262. """Configuration which reads from multiple config files.."""
  263. def __init__(self, backends, writable=None):
  264. self.backends = backends
  265. self.writable = writable
  266. def __repr__(self):
  267. return "<%s for %r>" % (self.__class__.__name__, self.backends)
  268. @classmethod
  269. def default_backends(cls):
  270. """Retrieve the default configuration.
  271. This will look in the repository configuration (if for_path is
  272. specified), the users' home directory and the system
  273. configuration.
  274. """
  275. paths = []
  276. paths.append(os.path.expanduser("~/.gitconfig"))
  277. paths.append("/etc/gitconfig")
  278. backends = []
  279. for path in paths:
  280. try:
  281. cf = ConfigFile.from_path(path)
  282. except (IOError, OSError), e:
  283. if e.errno != errno.ENOENT:
  284. raise
  285. else:
  286. continue
  287. backends.append(cf)
  288. return backends
  289. def get(self, section, name):
  290. for backend in self.backends:
  291. try:
  292. return backend.get(section, name)
  293. except KeyError:
  294. pass
  295. raise KeyError(name)
  296. def set(self, section, name, value):
  297. if self.writable is None:
  298. raise NotImplementedError(self.set)
  299. return self.writable.set(section, name, value)