config.py 11 KB

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