config.py 14 KB

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