config.py 14 KB

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