config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # config.py - Reading and writing Git config files
  2. # Copyright (C) 2011-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  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. import sys
  29. from collections import (
  30. OrderedDict,
  31. )
  32. try:
  33. from collections.abc import (
  34. Iterable,
  35. MutableMapping,
  36. )
  37. except ImportError: # python < 3.7
  38. from collections import (
  39. Iterable,
  40. MutableMapping,
  41. )
  42. from dulwich.file import GitFile
  43. SENTINAL = object()
  44. def lower_key(key):
  45. if isinstance(key, (bytes, str)):
  46. return key.lower()
  47. if isinstance(key, Iterable):
  48. return type(key)(
  49. map(lower_key, key)
  50. )
  51. return key
  52. class CaseInsensitiveDict(OrderedDict):
  53. @classmethod
  54. def make(cls, dict_in=None):
  55. if isinstance(dict_in, cls):
  56. return dict_in
  57. out = cls()
  58. if dict_in is None:
  59. return out
  60. if not isinstance(dict_in, MutableMapping):
  61. raise TypeError
  62. for key, value in dict_in.items():
  63. out[key] = value
  64. return out
  65. def __setitem__(self, key, value, **kwargs):
  66. key = lower_key(key)
  67. super(CaseInsensitiveDict, self).__setitem__(key, value, **kwargs)
  68. def __getitem__(self, item):
  69. key = lower_key(item)
  70. return super(CaseInsensitiveDict, self).__getitem__(key)
  71. def get(self, key, default=SENTINAL):
  72. try:
  73. return self[key]
  74. except KeyError:
  75. pass
  76. if default is SENTINAL:
  77. return type(self)()
  78. return default
  79. def setdefault(self, key, default=SENTINAL):
  80. try:
  81. return self[key]
  82. except KeyError:
  83. self[key] = self.get(key, default)
  84. return self[key]
  85. class Config(object):
  86. """A Git configuration."""
  87. def get(self, section, name):
  88. """Retrieve the contents of a configuration setting.
  89. :param section: Tuple with section name and optional subsection namee
  90. :param subsection: Subsection name
  91. :return: Contents of the setting
  92. :raise KeyError: if the value is not set
  93. """
  94. raise NotImplementedError(self.get)
  95. def get_boolean(self, section, name, default=None):
  96. """Retrieve a configuration setting as boolean.
  97. :param section: Tuple with section name and optional subsection name
  98. :param name: Name of the setting, including section and possible
  99. subsection.
  100. :return: Contents of the setting
  101. :raise KeyError: if the value is not set
  102. """
  103. try:
  104. value = self.get(section, name)
  105. except KeyError:
  106. return default
  107. if value.lower() == b"true":
  108. return True
  109. elif value.lower() == b"false":
  110. return False
  111. raise ValueError("not a valid boolean string: %r" % value)
  112. def set(self, section, name, value):
  113. """Set a configuration value.
  114. :param section: Tuple with section name and optional subsection namee
  115. :param name: Name of the configuration value, including section
  116. and optional subsection
  117. :param: Value of the setting
  118. """
  119. raise NotImplementedError(self.set)
  120. def iteritems(self, section):
  121. """Iterate over the configuration pairs for a specific section.
  122. :param section: Tuple with section name and optional subsection namee
  123. :return: Iterator over (name, value) pairs
  124. """
  125. raise NotImplementedError(self.iteritems)
  126. def itersections(self):
  127. """Iterate over the sections.
  128. :return: Iterator over section tuples
  129. """
  130. raise NotImplementedError(self.itersections)
  131. def has_section(self, name):
  132. """Check if a specified section exists.
  133. :param name: Name of section to check for
  134. :return: boolean indicating whether the section exists
  135. """
  136. return (name in self.itersections())
  137. class ConfigDict(Config, MutableMapping):
  138. """Git configuration stored in a dictionary."""
  139. def __init__(self, values=None, encoding=None):
  140. """Create a new ConfigDict."""
  141. if encoding is None:
  142. encoding = sys.getdefaultencoding()
  143. self.encoding = encoding
  144. self._values = CaseInsensitiveDict.make(values)
  145. def __repr__(self):
  146. return "%s(%r)" % (self.__class__.__name__, self._values)
  147. def __eq__(self, other):
  148. return (
  149. isinstance(other, self.__class__) and
  150. other._values == self._values)
  151. def __getitem__(self, key):
  152. return self._values.__getitem__(key)
  153. def __setitem__(self, key, value):
  154. return self._values.__setitem__(key, value)
  155. def __delitem__(self, key):
  156. return self._values.__delitem__(key)
  157. def __iter__(self):
  158. return self._values.__iter__()
  159. def __len__(self):
  160. return self._values.__len__()
  161. @classmethod
  162. def _parse_setting(cls, name):
  163. parts = name.split(".")
  164. if len(parts) == 3:
  165. return (parts[0], parts[1], parts[2])
  166. else:
  167. return (parts[0], None, parts[1])
  168. def _check_section_and_name(self, section, name):
  169. if not isinstance(section, tuple):
  170. section = (section, )
  171. section = tuple([
  172. subsection.encode(self.encoding)
  173. if not isinstance(subsection, bytes) else subsection
  174. for subsection in section
  175. ])
  176. if not isinstance(name, bytes):
  177. name = name.encode(self.encoding)
  178. return section, name
  179. def get(self, section, name):
  180. section, name = self._check_section_and_name(section, name)
  181. if len(section) > 1:
  182. try:
  183. return self._values[section][name]
  184. except KeyError:
  185. pass
  186. return self._values[(section[0],)][name]
  187. def set(self, section, name, value):
  188. section, name = self._check_section_and_name(section, name)
  189. if type(value) not in (bool, bytes):
  190. value = value.encode(self.encoding)
  191. self._values.setdefault(section)[name] = value
  192. def iteritems(self, section):
  193. return self._values.get(section).items()
  194. def itersections(self):
  195. return self._values.keys()
  196. def _format_string(value):
  197. if (value.startswith(b" ") or
  198. value.startswith(b"\t") or
  199. value.endswith(b" ") or
  200. b'#' in value or
  201. value.endswith(b"\t")):
  202. return b'"' + _escape_value(value) + b'"'
  203. else:
  204. return _escape_value(value)
  205. _ESCAPE_TABLE = {
  206. ord(b"\\"): ord(b"\\"),
  207. ord(b"\""): ord(b"\""),
  208. ord(b"n"): ord(b"\n"),
  209. ord(b"t"): ord(b"\t"),
  210. ord(b"b"): ord(b"\b"),
  211. }
  212. _COMMENT_CHARS = [ord(b"#"), ord(b";")]
  213. _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")]
  214. def _parse_string(value):
  215. value = bytearray(value.strip())
  216. ret = bytearray()
  217. whitespace = bytearray()
  218. in_quotes = False
  219. i = 0
  220. while i < len(value):
  221. c = value[i]
  222. if c == ord(b"\\"):
  223. i += 1
  224. try:
  225. v = _ESCAPE_TABLE[value[i]]
  226. except IndexError:
  227. raise ValueError(
  228. "escape character in %r at %d before end of string" %
  229. (value, i))
  230. except KeyError:
  231. raise ValueError(
  232. "escape character followed by unknown character "
  233. "%s at %d in %r" % (value[i], i, value))
  234. if whitespace:
  235. ret.extend(whitespace)
  236. whitespace = bytearray()
  237. ret.append(v)
  238. elif c == ord(b"\""):
  239. in_quotes = (not in_quotes)
  240. elif c in _COMMENT_CHARS and not in_quotes:
  241. # the rest of the line is a comment
  242. break
  243. elif c in _WHITESPACE_CHARS:
  244. whitespace.append(c)
  245. else:
  246. if whitespace:
  247. ret.extend(whitespace)
  248. whitespace = bytearray()
  249. ret.append(c)
  250. i += 1
  251. if in_quotes:
  252. raise ValueError("missing end quote")
  253. return bytes(ret)
  254. def _escape_value(value):
  255. """Escape a value."""
  256. value = value.replace(b"\\", b"\\\\")
  257. value = value.replace(b"\n", b"\\n")
  258. value = value.replace(b"\t", b"\\t")
  259. value = value.replace(b"\"", b"\\\"")
  260. return value
  261. def _check_variable_name(name):
  262. for i in range(len(name)):
  263. c = name[i:i+1]
  264. if not c.isalnum() and c != b'-':
  265. return False
  266. return True
  267. def _check_section_name(name):
  268. for i in range(len(name)):
  269. c = name[i:i+1]
  270. if not c.isalnum() and c not in (b'-', b'.'):
  271. return False
  272. return True
  273. def _strip_comments(line):
  274. comment_bytes = {ord(b"#"), ord(b";")}
  275. quote = ord(b'"')
  276. string_open = False
  277. # Normalize line to bytearray for simple 2/3 compatibility
  278. for i, character in enumerate(bytearray(line)):
  279. # Comment characters outside balanced quotes denote comment start
  280. if character == quote:
  281. string_open = not string_open
  282. elif not string_open and character in comment_bytes:
  283. return line[:i]
  284. return line
  285. class ConfigFile(ConfigDict):
  286. """A Git configuration file, like .git/config or ~/.gitconfig.
  287. """
  288. @classmethod
  289. def from_file(cls, f):
  290. """Read configuration from a file-like object."""
  291. ret = cls()
  292. section = None
  293. setting = None
  294. for lineno, line in enumerate(f.readlines()):
  295. line = line.lstrip()
  296. if setting is None:
  297. # Parse section header ("[bla]")
  298. if len(line) > 0 and line[:1] == b"[":
  299. line = _strip_comments(line).rstrip()
  300. try:
  301. last = line.index(b"]")
  302. except ValueError:
  303. raise ValueError("expected trailing ]")
  304. pts = line[1:last].split(b" ", 1)
  305. line = line[last+1:]
  306. if len(pts) == 2:
  307. if pts[1][:1] != b"\"" or pts[1][-1:] != b"\"":
  308. raise ValueError(
  309. "Invalid subsection %r" % pts[1])
  310. else:
  311. pts[1] = pts[1][1:-1]
  312. if not _check_section_name(pts[0]):
  313. raise ValueError("invalid section name %r" %
  314. pts[0])
  315. section = (pts[0], pts[1])
  316. else:
  317. if not _check_section_name(pts[0]):
  318. raise ValueError(
  319. "invalid section name %r" % pts[0])
  320. pts = pts[0].split(b".", 1)
  321. if len(pts) == 2:
  322. section = (pts[0], pts[1])
  323. else:
  324. section = (pts[0], )
  325. ret._values.setdefault(section)
  326. if _strip_comments(line).strip() == b"":
  327. continue
  328. if section is None:
  329. raise ValueError("setting %r without section" % line)
  330. try:
  331. setting, value = line.split(b"=", 1)
  332. except ValueError:
  333. setting = line
  334. value = b"true"
  335. setting = setting.strip()
  336. if not _check_variable_name(setting):
  337. raise ValueError("invalid variable name %s" % setting)
  338. if value.endswith(b"\\\n"):
  339. continuation = value[:-2]
  340. else:
  341. continuation = None
  342. value = _parse_string(value)
  343. ret._values[section][setting] = value
  344. setting = None
  345. else: # continuation line
  346. if line.endswith(b"\\\n"):
  347. continuation += line[:-2]
  348. else:
  349. continuation += line
  350. value = _parse_string(continuation)
  351. ret._values[section][setting] = value
  352. continuation = None
  353. setting = None
  354. return ret
  355. @classmethod
  356. def from_path(cls, path):
  357. """Read configuration from a file on disk."""
  358. with GitFile(path, 'rb') as f:
  359. ret = cls.from_file(f)
  360. ret.path = path
  361. return ret
  362. def write_to_path(self, path=None):
  363. """Write configuration to a file on disk."""
  364. if path is None:
  365. path = self.path
  366. with GitFile(path, 'wb') as f:
  367. self.write_to_file(f)
  368. def write_to_file(self, f):
  369. """Write configuration to a file-like object."""
  370. for section, values in self._values.items():
  371. try:
  372. section_name, subsection_name = section
  373. except ValueError:
  374. (section_name, ) = section
  375. subsection_name = None
  376. if subsection_name is None:
  377. f.write(b"[" + section_name + b"]\n")
  378. else:
  379. f.write(b"[" + section_name +
  380. b" \"" + subsection_name + b"\"]\n")
  381. for key, value in values.items():
  382. if value is True:
  383. value = b"true"
  384. elif value is False:
  385. value = b"false"
  386. else:
  387. value = _format_string(value)
  388. f.write(b"\t" + key + b" = " + value + b"\n")
  389. class StackedConfig(Config):
  390. """Configuration which reads from multiple config files.."""
  391. def __init__(self, backends, writable=None):
  392. self.backends = backends
  393. self.writable = writable
  394. def __repr__(self):
  395. return "<%s for %r>" % (self.__class__.__name__, self.backends)
  396. @classmethod
  397. def default(cls):
  398. return cls(cls.default_backends())
  399. @classmethod
  400. def default_backends(cls):
  401. """Retrieve the default configuration.
  402. See git-config(1) for details on the files searched.
  403. """
  404. paths = []
  405. paths.append(os.path.expanduser("~/.gitconfig"))
  406. xdg_config_home = os.environ.get(
  407. "XDG_CONFIG_HOME", os.path.expanduser("~/.config/"),
  408. )
  409. paths.append(os.path.join(xdg_config_home, "git", "config"))
  410. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  411. paths.append("/etc/gitconfig")
  412. backends = []
  413. for path in paths:
  414. try:
  415. cf = ConfigFile.from_path(path)
  416. except (IOError, OSError) as e:
  417. if e.errno != errno.ENOENT:
  418. raise
  419. else:
  420. continue
  421. backends.append(cf)
  422. return backends
  423. def get(self, section, name):
  424. if not isinstance(section, tuple):
  425. section = (section, )
  426. for backend in self.backends:
  427. try:
  428. return backend.get(section, name)
  429. except KeyError:
  430. pass
  431. raise KeyError(name)
  432. def set(self, section, name, value):
  433. if self.writable is None:
  434. raise NotImplementedError(self.set)
  435. return self.writable.set(section, name, value)
  436. def parse_submodules(config):
  437. """Parse a gitmodules GitConfig file, returning submodules.
  438. :param config: A `ConfigFile`
  439. :return: list of tuples (submodule path, url, name),
  440. where name is quoted part of the section's name.
  441. """
  442. for section in config.keys():
  443. section_kind, section_name = section
  444. if section_kind == b'submodule':
  445. sm_path = config.get(section, b'path')
  446. sm_url = config.get(section, b'url')
  447. yield (sm_path, sm_url, section_name)