config.py 12 KB

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