config.py 11 KB

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