config.py 11 KB

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