config.py 10 KB

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