2
0

config.py 14 KB

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