2
0

config.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. _ESCAPE_TABLE = {
  138. ord(b"\\"): ord(b"\\"),
  139. ord(b"\""): ord(b"\""),
  140. ord(b"n"): ord(b"\n"),
  141. ord(b"t"): ord(b"\t"),
  142. ord(b"b"): ord(b"\b"),
  143. }
  144. _COMMENT_CHARS = [ord(b"#"), ord(b";")]
  145. _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")]
  146. def _parse_string(value):
  147. value = bytearray(value.strip())
  148. ret = bytearray()
  149. whitespace = bytearray()
  150. in_quotes = False
  151. i = 0
  152. while i < len(value):
  153. c = value[i]
  154. if c == ord(b"\\"):
  155. i += 1
  156. try:
  157. v = _ESCAPE_TABLE[value[i]]
  158. except IndexError:
  159. raise ValueError(
  160. "escape character in %r at %d before end of string" %
  161. (value, i))
  162. except KeyError:
  163. raise ValueError(
  164. "escape character followed by unknown character %s at %d in %r" %
  165. (value[i], i, value))
  166. if whitespace:
  167. ret.extend(whitespace)
  168. whitespace = bytearray()
  169. ret.append(v)
  170. elif c == ord(b"\""):
  171. in_quotes = (not in_quotes)
  172. elif c in _COMMENT_CHARS and not in_quotes:
  173. # the rest of the line is a comment
  174. break
  175. elif c in _WHITESPACE_CHARS:
  176. whitespace.append(c)
  177. else:
  178. if whitespace:
  179. ret.extend(whitespace)
  180. whitespace = bytearray()
  181. ret.append(c)
  182. i += 1
  183. if in_quotes:
  184. raise ValueError("missing end quote")
  185. return bytes(ret)
  186. def _unescape_value(value):
  187. """Unescape a value."""
  188. ret = bytearray()
  189. i = 0
  190. return ret
  191. def _escape_value(value):
  192. """Escape a value."""
  193. return value.replace(b"\\", b"\\\\").replace(b"\n", b"\\n").replace(b"\t", b"\\t").replace(b"\"", b"\\\"")
  194. def _check_variable_name(name):
  195. for i in range(len(name)):
  196. c = name[i:i+1]
  197. if not c.isalnum() and c != b'-':
  198. return False
  199. return True
  200. def _check_section_name(name):
  201. for i in range(len(name)):
  202. c = name[i:i+1]
  203. if not c.isalnum() and c not in (b'-', b'.'):
  204. return False
  205. return True
  206. def _strip_comments(line):
  207. line = line.split(b"#")[0]
  208. line = line.split(b";")[0]
  209. return line
  210. class ConfigFile(ConfigDict):
  211. """A Git configuration file, like .git/config or ~/.gitconfig.
  212. """
  213. @classmethod
  214. def from_file(cls, f):
  215. """Read configuration from a file-like object."""
  216. ret = cls()
  217. section = None
  218. setting = None
  219. for lineno, line in enumerate(f.readlines()):
  220. line = line.lstrip()
  221. if setting is None:
  222. # Parse section header ("[bla]")
  223. if len(line) > 0 and line[:1] == b"[":
  224. line = _strip_comments(line).rstrip()
  225. last = line.index(b"]")
  226. if last == -1:
  227. raise ValueError("expected trailing ]")
  228. pts = line[1:last].split(b" ", 1)
  229. line = line[last+1:]
  230. pts[0] = pts[0].lower()
  231. if len(pts) == 2:
  232. if pts[1][:1] != b"\"" or pts[1][-1:] != b"\"":
  233. raise ValueError(
  234. "Invalid subsection %r" % pts[1])
  235. else:
  236. pts[1] = pts[1][1:-1]
  237. if not _check_section_name(pts[0]):
  238. raise ValueError("invalid section name %r" %
  239. pts[0])
  240. section = (pts[0], pts[1])
  241. else:
  242. if not _check_section_name(pts[0]):
  243. raise ValueError("invalid section name %r" %
  244. pts[0])
  245. pts = pts[0].split(b".", 1)
  246. if len(pts) == 2:
  247. section = (pts[0], pts[1])
  248. else:
  249. section = (pts[0], )
  250. ret._values[section] = OrderedDict()
  251. if _strip_comments(line).strip() == b"":
  252. continue
  253. if section is None:
  254. raise ValueError("setting %r without section" % line)
  255. try:
  256. setting, value = line.split(b"=", 1)
  257. except ValueError:
  258. setting = line
  259. value = b"true"
  260. setting = setting.strip().lower()
  261. if not _check_variable_name(setting):
  262. raise ValueError("invalid variable name %s" % setting)
  263. if value.endswith(b"\\\n"):
  264. value = value[:-2]
  265. continuation = True
  266. else:
  267. continuation = False
  268. value = _parse_string(value)
  269. ret._values[section][setting] = value
  270. if not continuation:
  271. setting = None
  272. else: # continuation line
  273. if line.endswith(b"\\\n"):
  274. line = line[:-2]
  275. continuation = True
  276. else:
  277. continuation = False
  278. value = _parse_string(line)
  279. ret._values[section][setting] += value
  280. if not continuation:
  281. setting = None
  282. return ret
  283. @classmethod
  284. def from_path(cls, path):
  285. """Read configuration from a file on disk."""
  286. with GitFile(path, 'rb') as f:
  287. ret = cls.from_file(f)
  288. ret.path = path
  289. return ret
  290. def write_to_path(self, path=None):
  291. """Write configuration to a file on disk."""
  292. if path is None:
  293. path = self.path
  294. with GitFile(path, 'wb') as f:
  295. self.write_to_file(f)
  296. def write_to_file(self, f):
  297. """Write configuration to a file-like object."""
  298. for section, values in self._values.items():
  299. try:
  300. section_name, subsection_name = section
  301. except ValueError:
  302. (section_name, ) = section
  303. subsection_name = None
  304. if subsection_name is None:
  305. f.write(b"[" + section_name + b"]\n")
  306. else:
  307. f.write(b"[" + section_name + b" \"" + subsection_name + b"\"]\n")
  308. for key, value in values.items():
  309. if value is True:
  310. value = b"true"
  311. elif value is False:
  312. value = b"false"
  313. else:
  314. value = _escape_value(value)
  315. f.write(b"\t" + key + b" = " + value + b"\n")
  316. class StackedConfig(Config):
  317. """Configuration which reads from multiple config files.."""
  318. def __init__(self, backends, writable=None):
  319. self.backends = backends
  320. self.writable = writable
  321. def __repr__(self):
  322. return "<%s for %r>" % (self.__class__.__name__, self.backends)
  323. @classmethod
  324. def default_backends(cls):
  325. """Retrieve the default configuration.
  326. This will look in the users' home directory and the system
  327. configuration.
  328. """
  329. paths = []
  330. paths.append(os.path.expanduser("~/.gitconfig"))
  331. paths.append("/etc/gitconfig")
  332. backends = []
  333. for path in paths:
  334. try:
  335. cf = ConfigFile.from_path(path)
  336. except (IOError, OSError) as e:
  337. if e.errno != errno.ENOENT:
  338. raise
  339. else:
  340. continue
  341. backends.append(cf)
  342. return backends
  343. def get(self, section, name):
  344. for backend in self.backends:
  345. try:
  346. return backend.get(section, name)
  347. except KeyError:
  348. pass
  349. raise KeyError(name)
  350. def set(self, section, name, value):
  351. if self.writable is None:
  352. raise NotImplementedError(self.set)
  353. return self.writable.set(section, name, value)