config.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. if i >= len(value):
  333. # Backslash at end of string - treat as literal backslash
  334. if whitespace:
  335. ret.extend(whitespace)
  336. whitespace = bytearray()
  337. ret.append(ord(b"\\"))
  338. else:
  339. try:
  340. v = _ESCAPE_TABLE[value[i]]
  341. if whitespace:
  342. ret.extend(whitespace)
  343. whitespace = bytearray()
  344. ret.append(v)
  345. except KeyError:
  346. # Unknown escape sequence - treat backslash as literal and process next char normally
  347. if whitespace:
  348. ret.extend(whitespace)
  349. whitespace = bytearray()
  350. ret.append(ord(b"\\"))
  351. i -= 1 # Reprocess the character after the backslash
  352. elif c == ord(b'"'):
  353. in_quotes = not in_quotes
  354. elif c in _COMMENT_CHARS and not in_quotes:
  355. # the rest of the line is a comment
  356. break
  357. elif c in _WHITESPACE_CHARS:
  358. whitespace.append(c)
  359. else:
  360. if whitespace:
  361. ret.extend(whitespace)
  362. whitespace = bytearray()
  363. ret.append(c)
  364. i += 1
  365. if in_quotes:
  366. raise ValueError("missing end quote")
  367. return bytes(ret)
  368. def _escape_value(value: bytes) -> bytes:
  369. """Escape a value."""
  370. value = value.replace(b"\\", b"\\\\")
  371. value = value.replace(b"\r", b"\\r")
  372. value = value.replace(b"\n", b"\\n")
  373. value = value.replace(b"\t", b"\\t")
  374. value = value.replace(b'"', b'\\"')
  375. return value
  376. def _check_variable_name(name: bytes) -> bool:
  377. for i in range(len(name)):
  378. c = name[i : i + 1]
  379. if not c.isalnum() and c != b"-":
  380. return False
  381. return True
  382. def _check_section_name(name: bytes) -> bool:
  383. for i in range(len(name)):
  384. c = name[i : i + 1]
  385. if not c.isalnum() and c not in (b"-", b"."):
  386. return False
  387. return True
  388. def _strip_comments(line: bytes) -> bytes:
  389. comment_bytes = {ord(b"#"), ord(b";")}
  390. quote = ord(b'"')
  391. string_open = False
  392. # Normalize line to bytearray for simple 2/3 compatibility
  393. for i, character in enumerate(bytearray(line)):
  394. # Comment characters outside balanced quotes denote comment start
  395. if character == quote:
  396. string_open = not string_open
  397. elif not string_open and character in comment_bytes:
  398. return line[:i]
  399. return line
  400. def _is_line_continuation(value: bytes) -> bool:
  401. """Check if a value ends with a line continuation backslash.
  402. A line continuation occurs when a line ends with a backslash that is:
  403. 1. Not escaped (not preceded by another backslash)
  404. 2. Not within quotes
  405. Args:
  406. value: The value to check
  407. Returns:
  408. True if the value ends with a line continuation backslash
  409. """
  410. if not value.endswith((b"\\\n", b"\\\r\n")):
  411. return False
  412. # Remove only the newline characters, keep the content including the backslash
  413. if value.endswith(b"\\\r\n"):
  414. content = value[:-2] # Remove \r\n, keep the \
  415. else:
  416. content = value[:-1] # Remove \n, keep the \
  417. if not content.endswith(b"\\"):
  418. return False
  419. # Count consecutive backslashes at the end
  420. backslash_count = 0
  421. for i in range(len(content) - 1, -1, -1):
  422. if content[i : i + 1] == b"\\":
  423. backslash_count += 1
  424. else:
  425. break
  426. # If we have an odd number of backslashes, the last one is a line continuation
  427. # If we have an even number, they are all escaped and there's no continuation
  428. return backslash_count % 2 == 1
  429. def _parse_section_header_line(line: bytes) -> tuple[Section, bytes]:
  430. # Parse section header ("[bla]")
  431. line = _strip_comments(line).rstrip()
  432. in_quotes = False
  433. escaped = False
  434. for i, c in enumerate(line):
  435. if escaped:
  436. escaped = False
  437. continue
  438. if c == ord(b'"'):
  439. in_quotes = not in_quotes
  440. if c == ord(b"\\"):
  441. escaped = True
  442. if c == ord(b"]") and not in_quotes:
  443. last = i
  444. break
  445. else:
  446. raise ValueError("expected trailing ]")
  447. pts = line[1:last].split(b" ", 1)
  448. line = line[last + 1 :]
  449. section: Section
  450. if len(pts) == 2:
  451. if pts[1][:1] != b'"' or pts[1][-1:] != b'"':
  452. raise ValueError(f"Invalid subsection {pts[1]!r}")
  453. else:
  454. pts[1] = pts[1][1:-1]
  455. if not _check_section_name(pts[0]):
  456. raise ValueError(f"invalid section name {pts[0]!r}")
  457. section = (pts[0], pts[1])
  458. else:
  459. if not _check_section_name(pts[0]):
  460. raise ValueError(f"invalid section name {pts[0]!r}")
  461. pts = pts[0].split(b".", 1)
  462. if len(pts) == 2:
  463. section = (pts[0], pts[1])
  464. else:
  465. section = (pts[0],)
  466. return section, line
  467. class ConfigFile(ConfigDict):
  468. """A Git configuration file, like .git/config or ~/.gitconfig."""
  469. def __init__(
  470. self,
  471. values: Union[
  472. MutableMapping[Section, MutableMapping[Name, Value]], None
  473. ] = None,
  474. encoding: Union[str, None] = None,
  475. ) -> None:
  476. super().__init__(values=values, encoding=encoding)
  477. self.path: Optional[str] = None
  478. @classmethod
  479. def from_file(cls, f: BinaryIO) -> "ConfigFile":
  480. """Read configuration from a file-like object."""
  481. ret = cls()
  482. section: Optional[Section] = None
  483. setting = None
  484. continuation = None
  485. for lineno, line in enumerate(f.readlines()):
  486. if lineno == 0 and line.startswith(b"\xef\xbb\xbf"):
  487. line = line[3:]
  488. line = line.lstrip()
  489. if setting is None:
  490. if len(line) > 0 and line[:1] == b"[":
  491. section, line = _parse_section_header_line(line)
  492. ret._values.setdefault(section)
  493. if _strip_comments(line).strip() == b"":
  494. continue
  495. if section is None:
  496. raise ValueError(f"setting {line!r} without section")
  497. try:
  498. setting, value = line.split(b"=", 1)
  499. except ValueError:
  500. setting = line
  501. value = b"true"
  502. setting = setting.strip()
  503. if not _check_variable_name(setting):
  504. raise ValueError(f"invalid variable name {setting!r}")
  505. if _is_line_continuation(value):
  506. if value.endswith(b"\\\r\n"):
  507. continuation = value[:-3]
  508. else:
  509. continuation = value[:-2]
  510. else:
  511. continuation = None
  512. value = _parse_string(value)
  513. ret._values[section][setting] = value
  514. setting = None
  515. else: # continuation line
  516. assert continuation is not None
  517. if _is_line_continuation(line):
  518. if line.endswith(b"\\\r\n"):
  519. continuation += line[:-3]
  520. else:
  521. continuation += line[:-2]
  522. else:
  523. continuation += line
  524. value = _parse_string(continuation)
  525. ret._values[section][setting] = value
  526. continuation = None
  527. setting = None
  528. return ret
  529. @classmethod
  530. def from_path(cls, path: Union[str, os.PathLike]) -> "ConfigFile":
  531. """Read configuration from a file on disk."""
  532. with GitFile(path, "rb") as f:
  533. ret = cls.from_file(f)
  534. ret.path = os.fspath(path)
  535. return ret
  536. def write_to_path(self, path: Optional[Union[str, os.PathLike]] = None) -> None:
  537. """Write configuration to a file on disk."""
  538. if path is None:
  539. if self.path is None:
  540. raise ValueError("No path specified and no default path available")
  541. path_to_use: Union[str, os.PathLike] = self.path
  542. else:
  543. path_to_use = path
  544. with GitFile(path_to_use, "wb") as f:
  545. self.write_to_file(f)
  546. def write_to_file(self, f: BinaryIO) -> None:
  547. """Write configuration to a file-like object."""
  548. for section, values in self._values.items():
  549. try:
  550. section_name, subsection_name = section
  551. except ValueError:
  552. (section_name,) = section
  553. subsection_name = None
  554. if subsection_name is None:
  555. f.write(b"[" + section_name + b"]\n")
  556. else:
  557. f.write(b"[" + section_name + b' "' + subsection_name + b'"]\n')
  558. for key, value in values.items():
  559. value = _format_string(value)
  560. f.write(b"\t" + key + b" = " + value + b"\n")
  561. def get_xdg_config_home_path(*path_segments):
  562. xdg_config_home = os.environ.get(
  563. "XDG_CONFIG_HOME",
  564. os.path.expanduser("~/.config/"),
  565. )
  566. return os.path.join(xdg_config_home, *path_segments)
  567. def _find_git_in_win_path():
  568. for exe in ("git.exe", "git.cmd"):
  569. for path in os.environ.get("PATH", "").split(";"):
  570. if os.path.exists(os.path.join(path, exe)):
  571. # in windows native shells (powershell/cmd) exe path is
  572. # .../Git/bin/git.exe or .../Git/cmd/git.exe
  573. #
  574. # in git-bash exe path is .../Git/mingw64/bin/git.exe
  575. git_dir, _bin_dir = os.path.split(path)
  576. yield git_dir
  577. parent_dir, basename = os.path.split(git_dir)
  578. if basename == "mingw32" or basename == "mingw64":
  579. yield parent_dir
  580. break
  581. def _find_git_in_win_reg():
  582. import platform
  583. import winreg
  584. if platform.machine() == "AMD64":
  585. subkey = (
  586. "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\"
  587. "CurrentVersion\\Uninstall\\Git_is1"
  588. )
  589. else:
  590. subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
  591. for key in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): # type: ignore
  592. with suppress(OSError):
  593. with winreg.OpenKey(key, subkey) as k: # type: ignore
  594. val, typ = winreg.QueryValueEx(k, "InstallLocation") # type: ignore
  595. if typ == winreg.REG_SZ: # type: ignore
  596. yield val
  597. # There is no set standard for system config dirs on windows. We try the
  598. # following:
  599. # - %PROGRAMDATA%/Git/config - (deprecated) Windows config dir per CGit docs
  600. # - %PROGRAMFILES%/Git/etc/gitconfig - Git for Windows (msysgit) config dir
  601. # Used if CGit installation (Git/bin/git.exe) is found in PATH in the
  602. # system registry
  603. def get_win_system_paths():
  604. if "PROGRAMDATA" in os.environ:
  605. yield os.path.join(os.environ["PROGRAMDATA"], "Git", "config")
  606. for git_dir in _find_git_in_win_path():
  607. yield os.path.join(git_dir, "etc", "gitconfig")
  608. for git_dir in _find_git_in_win_reg():
  609. yield os.path.join(git_dir, "etc", "gitconfig")
  610. class StackedConfig(Config):
  611. """Configuration which reads from multiple config files.."""
  612. def __init__(
  613. self, backends: list[ConfigFile], writable: Optional[ConfigFile] = None
  614. ) -> None:
  615. self.backends = backends
  616. self.writable = writable
  617. def __repr__(self) -> str:
  618. return f"<{self.__class__.__name__} for {self.backends!r}>"
  619. @classmethod
  620. def default(cls) -> "StackedConfig":
  621. return cls(cls.default_backends())
  622. @classmethod
  623. def default_backends(cls) -> list[ConfigFile]:
  624. """Retrieve the default configuration.
  625. See git-config(1) for details on the files searched.
  626. """
  627. paths = []
  628. paths.append(os.path.expanduser("~/.gitconfig"))
  629. paths.append(get_xdg_config_home_path("git", "config"))
  630. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  631. paths.append("/etc/gitconfig")
  632. if sys.platform == "win32":
  633. paths.extend(get_win_system_paths())
  634. backends = []
  635. for path in paths:
  636. try:
  637. cf = ConfigFile.from_path(path)
  638. except FileNotFoundError:
  639. continue
  640. backends.append(cf)
  641. return backends
  642. def get(self, section: SectionLike, name: NameLike) -> Value:
  643. if not isinstance(section, tuple):
  644. section = (section,)
  645. for backend in self.backends:
  646. try:
  647. return backend.get(section, name)
  648. except KeyError:
  649. pass
  650. raise KeyError(name)
  651. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  652. if not isinstance(section, tuple):
  653. section = (section,)
  654. for backend in self.backends:
  655. try:
  656. yield from backend.get_multivar(section, name)
  657. except KeyError:
  658. pass
  659. def set(
  660. self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool]
  661. ) -> None:
  662. if self.writable is None:
  663. raise NotImplementedError(self.set)
  664. return self.writable.set(section, name, value)
  665. def sections(self) -> Iterator[Section]:
  666. seen = set()
  667. for backend in self.backends:
  668. for section in backend.sections():
  669. if section not in seen:
  670. seen.add(section)
  671. yield section
  672. def read_submodules(
  673. path: Union[str, os.PathLike],
  674. ) -> Iterator[tuple[bytes, bytes, bytes]]:
  675. """Read a .gitmodules file."""
  676. cfg = ConfigFile.from_path(path)
  677. return parse_submodules(cfg)
  678. def parse_submodules(config: ConfigFile) -> Iterator[tuple[bytes, bytes, bytes]]:
  679. """Parse a gitmodules GitConfig file, returning submodules.
  680. Args:
  681. config: A `ConfigFile`
  682. Returns:
  683. list of tuples (submodule path, url, name),
  684. where name is quoted part of the section's name.
  685. """
  686. for section in config.keys():
  687. section_kind, section_name = section
  688. if section_kind == b"submodule":
  689. try:
  690. sm_path = config.get(section, b"path")
  691. sm_url = config.get(section, b"url")
  692. yield (sm_path, sm_url, section_name)
  693. except KeyError:
  694. # If either path or url is missing, just ignore this
  695. # submodule entry and move on to the next one. This is
  696. # how git itself handles malformed .gitmodule entries.
  697. pass
  698. def iter_instead_of(config: Config, push: bool = False) -> Iterable[tuple[str, str]]:
  699. """Iterate over insteadOf / pushInsteadOf values."""
  700. for section in config.sections():
  701. if section[0] != b"url":
  702. continue
  703. replacement = section[1]
  704. try:
  705. needles = list(config.get_multivar(section, "insteadOf"))
  706. except KeyError:
  707. needles = []
  708. if push:
  709. try:
  710. needles += list(config.get_multivar(section, "pushInsteadOf"))
  711. except KeyError:
  712. pass
  713. for needle in needles:
  714. assert isinstance(needle, bytes)
  715. yield needle.decode("utf-8"), replacement.decode("utf-8")
  716. def apply_instead_of(config: Config, orig_url: str, push: bool = False) -> str:
  717. """Apply insteadOf / pushInsteadOf to a URL."""
  718. longest_needle = ""
  719. updated_url = orig_url
  720. for needle, replacement in iter_instead_of(config, push):
  721. if not orig_url.startswith(needle):
  722. continue
  723. if len(longest_needle) < len(needle):
  724. longest_needle = needle
  725. updated_url = replacement + orig_url[len(needle) :]
  726. return updated_url