config.py 12 KB

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