config.py 17 KB

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