config.py 13 KB

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