config.py 14 KB

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