config.py 13 KB

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