config.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. # config.py - Reading and writing Git config files
  2. # Copyright (C) 2011-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Reading and writing Git configuration files.
  22. Todo:
  23. * preserve formatting when updating configuration files
  24. """
  25. import os
  26. import sys
  27. from collections.abc import Iterable, Iterator, KeysView, MutableMapping
  28. from contextlib import suppress
  29. from typing import (
  30. Any,
  31. BinaryIO,
  32. Optional,
  33. Union,
  34. overload,
  35. )
  36. from .file import GitFile
  37. SENTINEL = object()
  38. def lower_key(key):
  39. if isinstance(key, (bytes, str)):
  40. return key.lower()
  41. if isinstance(key, Iterable):
  42. # For config sections, only lowercase the section name (first element)
  43. # but preserve the case of subsection names (remaining elements)
  44. if len(key) > 0:
  45. return (key[0].lower(),) + key[1:]
  46. return key
  47. return key
  48. class CaseInsensitiveOrderedMultiDict(MutableMapping):
  49. def __init__(self) -> None:
  50. self._real: list[Any] = []
  51. self._keyed: dict[Any, Any] = {}
  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 __len__(self) -> int:
  65. return len(self._keyed)
  66. def keys(self) -> KeysView[tuple[bytes, ...]]:
  67. return self._keyed.keys()
  68. def items(self):
  69. return iter(self._real)
  70. def __iter__(self):
  71. return self._keyed.__iter__()
  72. def values(self):
  73. return self._keyed.values()
  74. def __setitem__(self, key, value) -> None:
  75. self._real.append((key, value))
  76. self._keyed[lower_key(key)] = value
  77. def set(self, key, value) -> None:
  78. # This method replaces all existing values for the key
  79. lower = lower_key(key)
  80. self._real = [(k, v) for k, v in self._real if lower_key(k) != lower]
  81. self._real.append((key, value))
  82. self._keyed[lower] = value
  83. def __delitem__(self, key) -> None:
  84. key = lower_key(key)
  85. del self._keyed[key]
  86. for i, (actual, unused_value) in reversed(list(enumerate(self._real))):
  87. if lower_key(actual) == key:
  88. del self._real[i]
  89. def __getitem__(self, item):
  90. return self._keyed[lower_key(item)]
  91. def get(self, key, default=SENTINEL):
  92. try:
  93. return self[key]
  94. except KeyError:
  95. pass
  96. if default is SENTINEL:
  97. return type(self)()
  98. return default
  99. def get_all(self, key):
  100. key = lower_key(key)
  101. for actual, value in self._real:
  102. if lower_key(actual) == key:
  103. yield value
  104. def setdefault(self, key, default=SENTINEL):
  105. try:
  106. return self[key]
  107. except KeyError:
  108. self[key] = self.get(key, default)
  109. return self[key]
  110. Name = bytes
  111. NameLike = Union[bytes, str]
  112. Section = tuple[bytes, ...]
  113. SectionLike = Union[bytes, str, tuple[Union[bytes, str], ...]]
  114. Value = bytes
  115. ValueLike = Union[bytes, str]
  116. class Config:
  117. """A Git configuration."""
  118. def get(self, section: SectionLike, name: NameLike) -> Value:
  119. """Retrieve the contents of a configuration setting.
  120. Args:
  121. section: Tuple with section name and optional subsection name
  122. name: Variable name
  123. Returns:
  124. Contents of the setting
  125. Raises:
  126. KeyError: if the value is not set
  127. """
  128. raise NotImplementedError(self.get)
  129. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  130. """Retrieve the contents of a multivar configuration setting.
  131. Args:
  132. section: Tuple with section name and optional subsection namee
  133. name: Variable name
  134. Returns:
  135. Contents of the setting as iterable
  136. Raises:
  137. KeyError: if the value is not set
  138. """
  139. raise NotImplementedError(self.get_multivar)
  140. @overload
  141. def get_boolean(
  142. self, section: SectionLike, name: NameLike, default: bool
  143. ) -> bool: ...
  144. @overload
  145. def get_boolean(self, section: SectionLike, name: NameLike) -> Optional[bool]: ...
  146. def get_boolean(
  147. self, section: SectionLike, name: NameLike, default: Optional[bool] = None
  148. ) -> Optional[bool]:
  149. """Retrieve a configuration setting as boolean.
  150. Args:
  151. section: Tuple with section name and optional subsection name
  152. name: Name of the setting, including section and possible
  153. subsection.
  154. Returns:
  155. Contents of the setting
  156. """
  157. try:
  158. value = self.get(section, name)
  159. except KeyError:
  160. return default
  161. if value.lower() == b"true":
  162. return True
  163. elif value.lower() == b"false":
  164. return False
  165. raise ValueError(f"not a valid boolean string: {value!r}")
  166. def set(
  167. self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool]
  168. ) -> None:
  169. """Set a configuration value.
  170. Args:
  171. section: Tuple with section name and optional subsection namee
  172. name: Name of the configuration value, including section
  173. and optional subsection
  174. value: value of the setting
  175. """
  176. raise NotImplementedError(self.set)
  177. def items(self, section: SectionLike) -> Iterator[tuple[Name, Value]]:
  178. """Iterate over the configuration pairs for a specific section.
  179. Args:
  180. section: Tuple with section name and optional subsection namee
  181. Returns:
  182. Iterator over (name, value) pairs
  183. """
  184. raise NotImplementedError(self.items)
  185. def sections(self) -> Iterator[Section]:
  186. """Iterate over the sections.
  187. Returns: Iterator over section tuples
  188. """
  189. raise NotImplementedError(self.sections)
  190. def has_section(self, name: Section) -> bool:
  191. """Check if a specified section exists.
  192. Args:
  193. name: Name of section to check for
  194. Returns:
  195. boolean indicating whether the section exists
  196. """
  197. return name in self.sections()
  198. class ConfigDict(Config, MutableMapping[Section, MutableMapping[Name, Value]]):
  199. """Git configuration stored in a dictionary."""
  200. def __init__(
  201. self,
  202. values: Union[
  203. MutableMapping[Section, MutableMapping[Name, Value]], None
  204. ] = None,
  205. encoding: Union[str, None] = None,
  206. ) -> None:
  207. """Create a new ConfigDict."""
  208. if encoding is None:
  209. encoding = sys.getdefaultencoding()
  210. self.encoding = encoding
  211. self._values = CaseInsensitiveOrderedMultiDict.make(values)
  212. def __repr__(self) -> str:
  213. return f"{self.__class__.__name__}({self._values!r})"
  214. def __eq__(self, other: object) -> bool:
  215. return isinstance(other, self.__class__) and other._values == self._values
  216. def __getitem__(self, key: Section) -> MutableMapping[Name, Value]:
  217. return self._values.__getitem__(key)
  218. def __setitem__(self, key: Section, value: MutableMapping[Name, Value]) -> None:
  219. return self._values.__setitem__(key, value)
  220. def __delitem__(self, key: Section) -> None:
  221. return self._values.__delitem__(key)
  222. def __iter__(self) -> Iterator[Section]:
  223. return self._values.__iter__()
  224. def __len__(self) -> int:
  225. return self._values.__len__()
  226. @classmethod
  227. def _parse_setting(cls, name: str):
  228. parts = name.split(".")
  229. if len(parts) == 3:
  230. return (parts[0], parts[1], parts[2])
  231. else:
  232. return (parts[0], None, parts[1])
  233. def _check_section_and_name(
  234. self, section: SectionLike, name: NameLike
  235. ) -> tuple[Section, Name]:
  236. if not isinstance(section, tuple):
  237. section = (section,)
  238. checked_section = tuple(
  239. [
  240. subsection.encode(self.encoding)
  241. if not isinstance(subsection, bytes)
  242. else subsection
  243. for subsection in section
  244. ]
  245. )
  246. if not isinstance(name, bytes):
  247. name = name.encode(self.encoding)
  248. return checked_section, name
  249. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  250. section, name = self._check_section_and_name(section, name)
  251. if len(section) > 1:
  252. try:
  253. return self._values[section].get_all(name)
  254. except KeyError:
  255. pass
  256. return self._values[(section[0],)].get_all(name)
  257. def get( # type: ignore[override]
  258. self,
  259. section: SectionLike,
  260. name: NameLike,
  261. ) -> Value:
  262. section, name = self._check_section_and_name(section, name)
  263. if len(section) > 1:
  264. try:
  265. return self._values[section][name]
  266. except KeyError:
  267. pass
  268. return self._values[(section[0],)][name]
  269. def set(
  270. self,
  271. section: SectionLike,
  272. name: NameLike,
  273. value: Union[ValueLike, bool],
  274. ) -> None:
  275. section, name = self._check_section_and_name(section, name)
  276. if isinstance(value, bool):
  277. value = b"true" if value else b"false"
  278. if not isinstance(value, bytes):
  279. value = value.encode(self.encoding)
  280. section_dict = self._values.setdefault(section)
  281. if hasattr(section_dict, "set"):
  282. section_dict.set(name, value)
  283. else:
  284. section_dict[name] = value
  285. def add(
  286. self,
  287. section: SectionLike,
  288. name: NameLike,
  289. value: Union[ValueLike, bool],
  290. ) -> None:
  291. """Add a value to a configuration setting, creating a multivar if needed."""
  292. section, name = self._check_section_and_name(section, name)
  293. if isinstance(value, bool):
  294. value = b"true" if value else b"false"
  295. if not isinstance(value, bytes):
  296. value = value.encode(self.encoding)
  297. self._values.setdefault(section)[name] = value
  298. def items( # type: ignore[override]
  299. self, section: Section
  300. ) -> Iterator[tuple[Name, Value]]:
  301. return self._values.get(section).items()
  302. def sections(self) -> Iterator[Section]:
  303. return self._values.keys()
  304. def _format_string(value: bytes) -> bytes:
  305. if (
  306. value.startswith((b" ", b"\t"))
  307. or value.endswith((b" ", b"\t"))
  308. or b"#" in value
  309. ):
  310. return b'"' + _escape_value(value) + b'"'
  311. else:
  312. return _escape_value(value)
  313. _ESCAPE_TABLE = {
  314. ord(b"\\"): ord(b"\\"),
  315. ord(b'"'): ord(b'"'),
  316. ord(b"n"): ord(b"\n"),
  317. ord(b"t"): ord(b"\t"),
  318. ord(b"b"): ord(b"\b"),
  319. }
  320. _COMMENT_CHARS = [ord(b"#"), ord(b";")]
  321. _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")]
  322. def _parse_string(value: bytes) -> bytes:
  323. value = bytearray(value.strip())
  324. ret = bytearray()
  325. whitespace = bytearray()
  326. in_quotes = False
  327. i = 0
  328. while i < len(value):
  329. c = value[i]
  330. if c == ord(b"\\"):
  331. i += 1
  332. try:
  333. v = _ESCAPE_TABLE[value[i]]
  334. except IndexError as exc:
  335. raise ValueError(
  336. f"escape character in {value!r} at {i} before end of string"
  337. ) from exc
  338. except KeyError as exc:
  339. raise ValueError(
  340. f"escape character followed by unknown character {value[i]!r} at {i} in {value!r}"
  341. ) from exc
  342. if whitespace:
  343. ret.extend(whitespace)
  344. whitespace = bytearray()
  345. ret.append(v)
  346. elif c == ord(b'"'):
  347. in_quotes = not in_quotes
  348. elif c in _COMMENT_CHARS and not in_quotes:
  349. # the rest of the line is a comment
  350. break
  351. elif c in _WHITESPACE_CHARS:
  352. whitespace.append(c)
  353. else:
  354. if whitespace:
  355. ret.extend(whitespace)
  356. whitespace = bytearray()
  357. ret.append(c)
  358. i += 1
  359. if in_quotes:
  360. raise ValueError("missing end quote")
  361. return bytes(ret)
  362. def _escape_value(value: bytes) -> bytes:
  363. """Escape a value."""
  364. value = value.replace(b"\\", b"\\\\")
  365. value = value.replace(b"\r", b"\\r")
  366. value = value.replace(b"\n", b"\\n")
  367. value = value.replace(b"\t", b"\\t")
  368. value = value.replace(b'"', b'\\"')
  369. return value
  370. def _check_variable_name(name: bytes) -> bool:
  371. for i in range(len(name)):
  372. c = name[i : i + 1]
  373. if not c.isalnum() and c != b"-":
  374. return False
  375. return True
  376. def _check_section_name(name: bytes) -> bool:
  377. for i in range(len(name)):
  378. c = name[i : i + 1]
  379. if not c.isalnum() and c not in (b"-", b"."):
  380. return False
  381. return True
  382. def _strip_comments(line: bytes) -> bytes:
  383. comment_bytes = {ord(b"#"), ord(b";")}
  384. quote = ord(b'"')
  385. string_open = False
  386. # Normalize line to bytearray for simple 2/3 compatibility
  387. for i, character in enumerate(bytearray(line)):
  388. # Comment characters outside balanced quotes denote comment start
  389. if character == quote:
  390. string_open = not string_open
  391. elif not string_open and character in comment_bytes:
  392. return line[:i]
  393. return line
  394. def _parse_section_header_line(line: bytes) -> tuple[Section, bytes]:
  395. # Parse section header ("[bla]")
  396. line = _strip_comments(line).rstrip()
  397. in_quotes = False
  398. escaped = False
  399. for i, c in enumerate(line):
  400. if escaped:
  401. escaped = False
  402. continue
  403. if c == ord(b'"'):
  404. in_quotes = not in_quotes
  405. if c == ord(b"\\"):
  406. escaped = True
  407. if c == ord(b"]") and not in_quotes:
  408. last = i
  409. break
  410. else:
  411. raise ValueError("expected trailing ]")
  412. pts = line[1:last].split(b" ", 1)
  413. line = line[last + 1 :]
  414. section: Section
  415. if len(pts) == 2:
  416. if pts[1][:1] != b'"' or pts[1][-1:] != b'"':
  417. raise ValueError(f"Invalid subsection {pts[1]!r}")
  418. else:
  419. pts[1] = pts[1][1:-1]
  420. if not _check_section_name(pts[0]):
  421. raise ValueError(f"invalid section name {pts[0]!r}")
  422. section = (pts[0], pts[1])
  423. else:
  424. if not _check_section_name(pts[0]):
  425. raise ValueError(f"invalid section name {pts[0]!r}")
  426. pts = pts[0].split(b".", 1)
  427. if len(pts) == 2:
  428. section = (pts[0], pts[1])
  429. else:
  430. section = (pts[0],)
  431. return section, line
  432. class ConfigFile(ConfigDict):
  433. """A Git configuration file, like .git/config or ~/.gitconfig."""
  434. def __init__(
  435. self,
  436. values: Union[
  437. MutableMapping[Section, MutableMapping[Name, Value]], None
  438. ] = None,
  439. encoding: Union[str, None] = None,
  440. ) -> None:
  441. super().__init__(values=values, encoding=encoding)
  442. self.path: Optional[str] = None
  443. @classmethod
  444. def from_file(cls, f: BinaryIO) -> "ConfigFile":
  445. """Read configuration from a file-like object."""
  446. ret = cls()
  447. section: Optional[Section] = None
  448. setting = None
  449. continuation = None
  450. for lineno, line in enumerate(f.readlines()):
  451. if lineno == 0 and line.startswith(b"\xef\xbb\xbf"):
  452. line = line[3:]
  453. line = line.lstrip()
  454. if setting is None:
  455. if len(line) > 0 and line[:1] == b"[":
  456. section, line = _parse_section_header_line(line)
  457. ret._values.setdefault(section)
  458. if _strip_comments(line).strip() == b"":
  459. continue
  460. if section is None:
  461. raise ValueError(f"setting {line!r} without section")
  462. try:
  463. setting, value = line.split(b"=", 1)
  464. except ValueError:
  465. setting = line
  466. value = b"true"
  467. setting = setting.strip()
  468. if not _check_variable_name(setting):
  469. raise ValueError(f"invalid variable name {setting!r}")
  470. if value.endswith(b"\\\n"):
  471. continuation = value[:-2]
  472. elif value.endswith(b"\\\r\n"):
  473. continuation = value[:-3]
  474. else:
  475. continuation = None
  476. value = _parse_string(value)
  477. ret._values[section][setting] = value
  478. setting = None
  479. else: # continuation line
  480. assert continuation is not None
  481. if line.endswith(b"\\\n"):
  482. continuation += line[:-2]
  483. elif line.endswith(b"\\\r\n"):
  484. continuation += line[:-3]
  485. else:
  486. continuation += line
  487. value = _parse_string(continuation)
  488. ret._values[section][setting] = value
  489. continuation = None
  490. setting = None
  491. return ret
  492. @classmethod
  493. def from_path(cls, path: str) -> "ConfigFile":
  494. """Read configuration from a file on disk."""
  495. with GitFile(path, "rb") as f:
  496. ret = cls.from_file(f)
  497. ret.path = path
  498. return ret
  499. def write_to_path(self, path: Optional[str] = None) -> None:
  500. """Write configuration to a file on disk."""
  501. if path is None:
  502. path = self.path
  503. with GitFile(path, "wb") as f:
  504. self.write_to_file(f)
  505. def write_to_file(self, f: BinaryIO) -> None:
  506. """Write configuration to a file-like object."""
  507. for section, values in self._values.items():
  508. try:
  509. section_name, subsection_name = section
  510. except ValueError:
  511. (section_name,) = section
  512. subsection_name = None
  513. if subsection_name is None:
  514. f.write(b"[" + section_name + b"]\n")
  515. else:
  516. f.write(b"[" + section_name + b' "' + subsection_name + b'"]\n')
  517. for key, value in values.items():
  518. value = _format_string(value)
  519. f.write(b"\t" + key + b" = " + value + b"\n")
  520. def get_xdg_config_home_path(*path_segments):
  521. xdg_config_home = os.environ.get(
  522. "XDG_CONFIG_HOME",
  523. os.path.expanduser("~/.config/"),
  524. )
  525. return os.path.join(xdg_config_home, *path_segments)
  526. def _find_git_in_win_path():
  527. for exe in ("git.exe", "git.cmd"):
  528. for path in os.environ.get("PATH", "").split(";"):
  529. if os.path.exists(os.path.join(path, exe)):
  530. # in windows native shells (powershell/cmd) exe path is
  531. # .../Git/bin/git.exe or .../Git/cmd/git.exe
  532. #
  533. # in git-bash exe path is .../Git/mingw64/bin/git.exe
  534. git_dir, _bin_dir = os.path.split(path)
  535. yield git_dir
  536. parent_dir, basename = os.path.split(git_dir)
  537. if basename == "mingw32" or basename == "mingw64":
  538. yield parent_dir
  539. break
  540. def _find_git_in_win_reg():
  541. import platform
  542. import winreg
  543. if platform.machine() == "AMD64":
  544. subkey = (
  545. "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\"
  546. "CurrentVersion\\Uninstall\\Git_is1"
  547. )
  548. else:
  549. subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
  550. for key in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): # type: ignore
  551. with suppress(OSError):
  552. with winreg.OpenKey(key, subkey) as k: # type: ignore
  553. val, typ = winreg.QueryValueEx(k, "InstallLocation") # type: ignore
  554. if typ == winreg.REG_SZ: # type: ignore
  555. yield val
  556. # There is no set standard for system config dirs on windows. We try the
  557. # following:
  558. # - %PROGRAMDATA%/Git/config - (deprecated) Windows config dir per CGit docs
  559. # - %PROGRAMFILES%/Git/etc/gitconfig - Git for Windows (msysgit) config dir
  560. # Used if CGit installation (Git/bin/git.exe) is found in PATH in the
  561. # system registry
  562. def get_win_system_paths():
  563. if "PROGRAMDATA" in os.environ:
  564. yield os.path.join(os.environ["PROGRAMDATA"], "Git", "config")
  565. for git_dir in _find_git_in_win_path():
  566. yield os.path.join(git_dir, "etc", "gitconfig")
  567. for git_dir in _find_git_in_win_reg():
  568. yield os.path.join(git_dir, "etc", "gitconfig")
  569. class StackedConfig(Config):
  570. """Configuration which reads from multiple config files.."""
  571. def __init__(
  572. self, backends: list[ConfigFile], writable: Optional[ConfigFile] = None
  573. ) -> None:
  574. self.backends = backends
  575. self.writable = writable
  576. def __repr__(self) -> str:
  577. return f"<{self.__class__.__name__} for {self.backends!r}>"
  578. @classmethod
  579. def default(cls) -> "StackedConfig":
  580. return cls(cls.default_backends())
  581. @classmethod
  582. def default_backends(cls) -> list[ConfigFile]:
  583. """Retrieve the default configuration.
  584. See git-config(1) for details on the files searched.
  585. """
  586. paths = []
  587. paths.append(os.path.expanduser("~/.gitconfig"))
  588. paths.append(get_xdg_config_home_path("git", "config"))
  589. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  590. paths.append("/etc/gitconfig")
  591. if sys.platform == "win32":
  592. paths.extend(get_win_system_paths())
  593. backends = []
  594. for path in paths:
  595. try:
  596. cf = ConfigFile.from_path(path)
  597. except FileNotFoundError:
  598. continue
  599. backends.append(cf)
  600. return backends
  601. def get(self, section: SectionLike, name: NameLike) -> Value:
  602. if not isinstance(section, tuple):
  603. section = (section,)
  604. for backend in self.backends:
  605. try:
  606. return backend.get(section, name)
  607. except KeyError:
  608. pass
  609. raise KeyError(name)
  610. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  611. if not isinstance(section, tuple):
  612. section = (section,)
  613. for backend in self.backends:
  614. try:
  615. yield from backend.get_multivar(section, name)
  616. except KeyError:
  617. pass
  618. def set(
  619. self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool]
  620. ) -> None:
  621. if self.writable is None:
  622. raise NotImplementedError(self.set)
  623. return self.writable.set(section, name, value)
  624. def sections(self) -> Iterator[Section]:
  625. seen = set()
  626. for backend in self.backends:
  627. for section in backend.sections():
  628. if section not in seen:
  629. seen.add(section)
  630. yield section
  631. def read_submodules(path: str) -> Iterator[tuple[bytes, bytes, bytes]]:
  632. """Read a .gitmodules file."""
  633. cfg = ConfigFile.from_path(path)
  634. return parse_submodules(cfg)
  635. def parse_submodules(config: ConfigFile) -> Iterator[tuple[bytes, bytes, bytes]]:
  636. """Parse a gitmodules GitConfig file, returning submodules.
  637. Args:
  638. config: A `ConfigFile`
  639. Returns:
  640. list of tuples (submodule path, url, name),
  641. where name is quoted part of the section's name.
  642. """
  643. for section in config.keys():
  644. section_kind, section_name = section
  645. if section_kind == b"submodule":
  646. try:
  647. sm_path = config.get(section, b"path")
  648. sm_url = config.get(section, b"url")
  649. yield (sm_path, sm_url, section_name)
  650. except KeyError:
  651. # If either path or url is missing, just ignore this
  652. # submodule entry and move on to the next one. This is
  653. # how git itself handles malformed .gitmodule entries.
  654. pass
  655. def iter_instead_of(config: Config, push: bool = False) -> Iterable[tuple[str, str]]:
  656. """Iterate over insteadOf / pushInsteadOf values."""
  657. for section in config.sections():
  658. if section[0] != b"url":
  659. continue
  660. replacement = section[1]
  661. try:
  662. needles = list(config.get_multivar(section, "insteadOf"))
  663. except KeyError:
  664. needles = []
  665. if push:
  666. try:
  667. needles += list(config.get_multivar(section, "pushInsteadOf"))
  668. except KeyError:
  669. pass
  670. for needle in needles:
  671. assert isinstance(needle, bytes)
  672. yield needle.decode("utf-8"), replacement.decode("utf-8")
  673. def apply_instead_of(config: Config, orig_url: str, push: bool = False) -> str:
  674. """Apply insteadOf / pushInsteadOf to a URL."""
  675. longest_needle = ""
  676. updated_url = orig_url
  677. for needle, replacement in iter_instead_of(config, push):
  678. if not orig_url.startswith(needle):
  679. continue
  680. if len(longest_needle) < len(needle):
  681. longest_needle = needle
  682. updated_url = replacement + orig_url[len(needle) :]
  683. return updated_url