config.py 12 KB

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