config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. if not isinstance(name, bytes):
  122. raise TypeError(name)
  123. if type(value) not in (bool, bytes):
  124. raise TypeError(value)
  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 _escape_value(value):
  187. """Escape a value."""
  188. return value.replace(b"\\", b"\\\\").replace(b"\n", b"\\n").replace(b"\t", b"\\t").replace(b"\"", b"\\\"")
  189. def _check_variable_name(name):
  190. for i in range(len(name)):
  191. c = name[i:i+1]
  192. if not c.isalnum() and c != b'-':
  193. return False
  194. return True
  195. def _check_section_name(name):
  196. for i in range(len(name)):
  197. c = name[i:i+1]
  198. if not c.isalnum() and c not in (b'-', b'.'):
  199. return False
  200. return True
  201. def _strip_comments(line):
  202. line = line.split(b"#")[0]
  203. line = line.split(b";")[0]
  204. return line
  205. class ConfigFile(ConfigDict):
  206. """A Git configuration file, like .git/config or ~/.gitconfig.
  207. """
  208. @classmethod
  209. def from_file(cls, f):
  210. """Read configuration from a file-like object."""
  211. ret = cls()
  212. section = None
  213. setting = None
  214. for lineno, line in enumerate(f.readlines()):
  215. line = line.lstrip()
  216. if setting is None:
  217. # Parse section header ("[bla]")
  218. if len(line) > 0 and line[:1] == b"[":
  219. line = _strip_comments(line).rstrip()
  220. last = line.index(b"]")
  221. if last == -1:
  222. raise ValueError("expected trailing ]")
  223. pts = line[1:last].split(b" ", 1)
  224. line = line[last+1:]
  225. pts[0] = pts[0].lower()
  226. if len(pts) == 2:
  227. if pts[1][:1] != b"\"" or pts[1][-1:] != b"\"":
  228. raise ValueError(
  229. "Invalid subsection %r" % pts[1])
  230. else:
  231. pts[1] = pts[1][1:-1]
  232. if not _check_section_name(pts[0]):
  233. raise ValueError("invalid section name %r" %
  234. pts[0])
  235. section = (pts[0], pts[1])
  236. else:
  237. if not _check_section_name(pts[0]):
  238. raise ValueError("invalid section name %r" %
  239. pts[0])
  240. pts = pts[0].split(b".", 1)
  241. if len(pts) == 2:
  242. section = (pts[0], pts[1])
  243. else:
  244. section = (pts[0], )
  245. ret._values[section] = OrderedDict()
  246. if _strip_comments(line).strip() == b"":
  247. continue
  248. if section is None:
  249. raise ValueError("setting %r without section" % line)
  250. try:
  251. setting, value = line.split(b"=", 1)
  252. except ValueError:
  253. setting = line
  254. value = b"true"
  255. setting = setting.strip().lower()
  256. if not _check_variable_name(setting):
  257. raise ValueError("invalid variable name %s" % setting)
  258. if value.endswith(b"\\\n"):
  259. value = value[:-2]
  260. continuation = True
  261. else:
  262. continuation = False
  263. value = _parse_string(value)
  264. ret._values[section][setting] = value
  265. if not continuation:
  266. setting = None
  267. else: # continuation line
  268. if line.endswith(b"\\\n"):
  269. line = line[:-2]
  270. continuation = True
  271. else:
  272. continuation = False
  273. value = _parse_string(line)
  274. ret._values[section][setting] += value
  275. if not continuation:
  276. setting = None
  277. return ret
  278. @classmethod
  279. def from_path(cls, path):
  280. """Read configuration from a file on disk."""
  281. with GitFile(path, 'rb') as f:
  282. ret = cls.from_file(f)
  283. ret.path = path
  284. return ret
  285. def write_to_path(self, path=None):
  286. """Write configuration to a file on disk."""
  287. if path is None:
  288. path = self.path
  289. with GitFile(path, 'wb') as f:
  290. self.write_to_file(f)
  291. def write_to_file(self, f):
  292. """Write configuration to a file-like object."""
  293. for section, values in self._values.items():
  294. try:
  295. section_name, subsection_name = section
  296. except ValueError:
  297. (section_name, ) = section
  298. subsection_name = None
  299. if subsection_name is None:
  300. f.write(b"[" + section_name + b"]\n")
  301. else:
  302. f.write(b"[" + section_name + b" \"" + subsection_name + b"\"]\n")
  303. for key, value in values.items():
  304. if value is True:
  305. value = b"true"
  306. elif value is False:
  307. value = b"false"
  308. else:
  309. value = _escape_value(value)
  310. f.write(b"\t" + key + b" = " + value + b"\n")
  311. class StackedConfig(Config):
  312. """Configuration which reads from multiple config files.."""
  313. def __init__(self, backends, writable=None):
  314. self.backends = backends
  315. self.writable = writable
  316. def __repr__(self):
  317. return "<%s for %r>" % (self.__class__.__name__, self.backends)
  318. @classmethod
  319. def default_backends(cls):
  320. """Retrieve the default configuration.
  321. See git-config(1) for details on the files searched.
  322. """
  323. paths = []
  324. paths.append(os.path.expanduser("~/.gitconfig"))
  325. xdg_config_home = os.environ.get(
  326. "XDG_CONFIG_HOME", os.path.expanduser("~/.config/"),
  327. )
  328. paths.append(os.path.join(xdg_config_home, "git", "config"))
  329. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  330. paths.append("/etc/gitconfig")
  331. backends = []
  332. for path in paths:
  333. try:
  334. cf = ConfigFile.from_path(path)
  335. except (IOError, OSError) as e:
  336. if e.errno != errno.ENOENT:
  337. raise
  338. else:
  339. continue
  340. backends.append(cf)
  341. return backends
  342. def get(self, section, name):
  343. for backend in self.backends:
  344. try:
  345. return backend.get(section, name)
  346. except KeyError:
  347. pass
  348. raise KeyError(name)
  349. def set(self, section, name, value):
  350. if self.writable is None:
  351. raise NotImplementedError(self.set)
  352. return self.writable.set(section, name, value)
  353. def parse_submodules(config):
  354. """Parse a gitmodules GitConfig file, returning submodules.
  355. :param config: A `ConfigFile`
  356. :return: list of tuples (submodule path, url, name),
  357. where name is quoted part of the section's name.
  358. """
  359. for section in config.keys():
  360. section_kind, section_name = section
  361. if section_kind == b'submodule':
  362. sm_path = config.get(section, b'path')
  363. sm_url = config.get(section, b'url')
  364. yield (sm_path, sm_url, section_name)