config.py 17 KB

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