config.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  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 published 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. __all__ = [
  26. "DEFAULT_MAX_INCLUDE_DEPTH",
  27. "MAX_INCLUDE_FILE_SIZE",
  28. "CaseInsensitiveOrderedMultiDict",
  29. "ConditionMatcher",
  30. "Config",
  31. "ConfigDict",
  32. "ConfigFile",
  33. "ConfigKey",
  34. "ConfigValue",
  35. "FileOpener",
  36. "StackedConfig",
  37. "apply_instead_of",
  38. "get_win_legacy_system_paths",
  39. "get_win_system_paths",
  40. "get_xdg_config_home_path",
  41. "iter_instead_of",
  42. "lower_key",
  43. "match_glob_pattern",
  44. "parse_submodules",
  45. "read_submodules",
  46. ]
  47. import logging
  48. import os
  49. import re
  50. import sys
  51. from collections.abc import (
  52. Callable,
  53. ItemsView,
  54. Iterable,
  55. Iterator,
  56. KeysView,
  57. Mapping,
  58. MutableMapping,
  59. ValuesView,
  60. )
  61. from contextlib import suppress
  62. from pathlib import Path
  63. from typing import (
  64. IO,
  65. Generic,
  66. TypeVar,
  67. overload,
  68. )
  69. from .file import GitFile, _GitFile
  70. ConfigKey = str | bytes | tuple[str | bytes, ...]
  71. ConfigValue = str | bytes | bool | int
  72. logger = logging.getLogger(__name__)
  73. # Type for file opener callback
  74. FileOpener = Callable[[str | os.PathLike[str]], IO[bytes]]
  75. # Type for includeIf condition matcher
  76. # Takes the condition value (e.g., "main" for onbranch:main) and returns bool
  77. ConditionMatcher = Callable[[str], bool]
  78. # Security limits for include files
  79. MAX_INCLUDE_FILE_SIZE = 1024 * 1024 # 1MB max for included config files
  80. DEFAULT_MAX_INCLUDE_DEPTH = 10 # Maximum recursion depth for includes
  81. def _match_gitdir_pattern(
  82. path: bytes, pattern: bytes, ignorecase: bool = False
  83. ) -> bool:
  84. """Simple gitdir pattern matching for includeIf conditions.
  85. This handles the basic gitdir patterns used in includeIf directives.
  86. """
  87. # Convert to strings for easier manipulation
  88. path_str = path.decode("utf-8", errors="replace")
  89. pattern_str = pattern.decode("utf-8", errors="replace")
  90. # Normalize paths to use forward slashes for consistent matching
  91. path_str = path_str.replace("\\", "/")
  92. pattern_str = pattern_str.replace("\\", "/")
  93. if ignorecase:
  94. path_str = path_str.lower()
  95. pattern_str = pattern_str.lower()
  96. # Handle the common cases for gitdir patterns
  97. if pattern_str.startswith("**/") and pattern_str.endswith("/**"):
  98. # Pattern like **/dirname/** should match any path containing dirname
  99. dirname = pattern_str[3:-3] # Remove **/ and /**
  100. # Check if path contains the directory name as a path component
  101. return ("/" + dirname + "/") in path_str or path_str.endswith("/" + dirname)
  102. elif pattern_str.startswith("**/"):
  103. # Pattern like **/filename
  104. suffix = pattern_str[3:] # Remove **/
  105. return suffix in path_str or path_str.endswith("/" + suffix)
  106. elif pattern_str.endswith("/**"):
  107. # Pattern like /path/to/dir/** should match /path/to/dir and any subdirectory
  108. base_pattern = pattern_str[:-3] # Remove /**
  109. return path_str == base_pattern or path_str.startswith(base_pattern + "/")
  110. elif "**" in pattern_str:
  111. # Handle patterns with ** in the middle
  112. parts = pattern_str.split("**")
  113. if len(parts) == 2:
  114. prefix, suffix = parts
  115. # Path must start with prefix and end with suffix (if any)
  116. if prefix and not path_str.startswith(prefix):
  117. return False
  118. if suffix and not path_str.endswith(suffix):
  119. return False
  120. return True
  121. # Direct match or simple glob pattern
  122. if "*" in pattern_str or "?" in pattern_str or "[" in pattern_str:
  123. import fnmatch
  124. return fnmatch.fnmatch(path_str, pattern_str)
  125. else:
  126. return path_str == pattern_str
  127. def match_glob_pattern(value: str, pattern: str) -> bool:
  128. r"""Match a value against a glob pattern.
  129. Supports simple glob patterns like ``*`` and ``**``.
  130. Raises:
  131. ValueError: If the pattern is invalid
  132. """
  133. # Convert glob pattern to regex
  134. pattern_escaped = re.escape(pattern)
  135. # Replace escaped \*\* with .* (match anything)
  136. pattern_escaped = pattern_escaped.replace(r"\*\*", ".*")
  137. # Replace escaped \* with [^/]* (match anything except /)
  138. pattern_escaped = pattern_escaped.replace(r"\*", "[^/]*")
  139. # Anchor the pattern
  140. pattern_regex = f"^{pattern_escaped}$"
  141. try:
  142. return bool(re.match(pattern_regex, value))
  143. except re.error as e:
  144. raise ValueError(f"Invalid glob pattern {pattern!r}: {e}")
  145. def lower_key(key: ConfigKey) -> ConfigKey:
  146. """Convert a config key to lowercase, preserving subsection case.
  147. Args:
  148. key: Configuration key (str, bytes, or tuple)
  149. Returns:
  150. Key with section names lowercased, subsection names preserved
  151. Raises:
  152. TypeError: If key is not str, bytes, or tuple
  153. """
  154. if isinstance(key, (bytes, str)):
  155. return key.lower()
  156. if isinstance(key, tuple):
  157. # For config sections, only lowercase the section name (first element)
  158. # but preserve the case of subsection names (remaining elements)
  159. if len(key) > 0:
  160. first = key[0]
  161. assert isinstance(first, (bytes, str))
  162. return (first.lower(), *key[1:])
  163. return key
  164. raise TypeError(key)
  165. K = TypeVar("K", bound=ConfigKey) # Key type must be ConfigKey
  166. V = TypeVar("V") # Value type
  167. _T = TypeVar("_T") # For get() default parameter
  168. class CaseInsensitiveOrderedMultiDict(MutableMapping[K, V], Generic[K, V]):
  169. """A case-insensitive ordered dictionary that can store multiple values per key.
  170. This class maintains the order of insertions and allows multiple values
  171. for the same key. Keys are compared case-insensitively.
  172. """
  173. def __init__(self, default_factory: Callable[[], V] | None = None) -> None:
  174. """Initialize a CaseInsensitiveOrderedMultiDict.
  175. Args:
  176. default_factory: Optional factory function for default values
  177. """
  178. self._real: list[tuple[K, V]] = []
  179. self._keyed: dict[ConfigKey, V] = {}
  180. self._default_factory = default_factory
  181. @classmethod
  182. def make(
  183. cls,
  184. dict_in: "MutableMapping[K, V] | CaseInsensitiveOrderedMultiDict[K, V] | None" = None,
  185. default_factory: Callable[[], V] | None = None,
  186. ) -> "CaseInsensitiveOrderedMultiDict[K, V]":
  187. """Create a CaseInsensitiveOrderedMultiDict from an existing mapping.
  188. Args:
  189. dict_in: Optional mapping to initialize from
  190. default_factory: Optional factory function for default values
  191. Returns:
  192. New CaseInsensitiveOrderedMultiDict instance
  193. Raises:
  194. TypeError: If dict_in is not a mapping or None
  195. """
  196. if isinstance(dict_in, cls):
  197. return dict_in
  198. out = cls(default_factory=default_factory)
  199. if dict_in is None:
  200. return out
  201. if not isinstance(dict_in, MutableMapping):
  202. raise TypeError
  203. for key, value in dict_in.items():
  204. out[key] = value
  205. return out
  206. def __len__(self) -> int:
  207. """Return the number of unique keys in the dictionary."""
  208. return len(self._keyed)
  209. def keys(self) -> KeysView[K]:
  210. """Return a view of the dictionary's keys."""
  211. # Return a view of the original keys (not lowercased)
  212. # We need to deduplicate since _real can have duplicates
  213. seen = set()
  214. unique_keys = []
  215. for k, _ in self._real:
  216. lower = lower_key(k)
  217. if lower not in seen:
  218. seen.add(lower)
  219. unique_keys.append(k)
  220. from collections.abc import KeysView as ABCKeysView
  221. class UniqueKeysView(ABCKeysView[K]):
  222. def __init__(self, keys: list[K]):
  223. self._keys = keys
  224. def __contains__(self, key: object) -> bool:
  225. return key in self._keys
  226. def __iter__(self) -> Iterator[K]:
  227. return iter(self._keys)
  228. def __len__(self) -> int:
  229. return len(self._keys)
  230. return UniqueKeysView(unique_keys)
  231. def items(self) -> ItemsView[K, V]:
  232. """Return a view of the dictionary's (key, value) pairs in insertion order."""
  233. # Return a view that iterates over the real list to preserve order
  234. class OrderedItemsView(ItemsView[K, V]):
  235. """Items view that preserves insertion order."""
  236. def __init__(self, mapping: CaseInsensitiveOrderedMultiDict[K, V]):
  237. self._mapping = mapping
  238. def __iter__(self) -> Iterator[tuple[K, V]]:
  239. return iter(self._mapping._real)
  240. def __len__(self) -> int:
  241. return len(self._mapping._real)
  242. def __contains__(self, item: object) -> bool:
  243. if not isinstance(item, tuple) or len(item) != 2:
  244. return False
  245. key, value = item
  246. return any(k == key and v == value for k, v in self._mapping._real)
  247. return OrderedItemsView(self)
  248. def __iter__(self) -> Iterator[K]:
  249. """Iterate over the dictionary's keys."""
  250. # Return iterator over original keys (not lowercased), deduplicated
  251. seen = set()
  252. for k, _ in self._real:
  253. lower = lower_key(k)
  254. if lower not in seen:
  255. seen.add(lower)
  256. yield k
  257. def values(self) -> ValuesView[V]:
  258. """Return a view of the dictionary's values."""
  259. return self._keyed.values()
  260. def __setitem__(self, key: K, value: V) -> None:
  261. """Set a value for a key, appending to existing values."""
  262. self._real.append((key, value))
  263. self._keyed[lower_key(key)] = value
  264. def set(self, key: K, value: V) -> None:
  265. """Set a value for a key, replacing all existing values.
  266. Args:
  267. key: The key to set
  268. value: The value to set
  269. """
  270. # This method replaces all existing values for the key
  271. lower = lower_key(key)
  272. self._real = [(k, v) for k, v in self._real if lower_key(k) != lower]
  273. self._real.append((key, value))
  274. self._keyed[lower] = value
  275. def __delitem__(self, key: K) -> None:
  276. """Delete all values for a key.
  277. Raises:
  278. KeyError: If the key is not found
  279. """
  280. lower_k = lower_key(key)
  281. del self._keyed[lower_k]
  282. for i, (actual, unused_value) in reversed(list(enumerate(self._real))):
  283. if lower_key(actual) == lower_k:
  284. del self._real[i]
  285. def __getitem__(self, item: K) -> V:
  286. """Get the last value for a key.
  287. Raises:
  288. KeyError: If the key is not found
  289. """
  290. return self._keyed[lower_key(item)]
  291. def get(self, key: K, /, default: V | _T | None = None) -> V | _T | None: # type: ignore[override]
  292. """Get the last value for a key, or a default if not found.
  293. Args:
  294. key: The key to look up
  295. default: Default value to return if key not found
  296. Returns:
  297. The value for the key, or default/default_factory result if not found
  298. """
  299. try:
  300. return self[key]
  301. except KeyError:
  302. if default is not None:
  303. return default
  304. elif self._default_factory is not None:
  305. return self._default_factory()
  306. else:
  307. return None
  308. def get_all(self, key: K) -> Iterator[V]:
  309. """Get all values for a key in insertion order.
  310. Args:
  311. key: The key to look up
  312. Returns:
  313. Iterator of all values for the key
  314. """
  315. lowered_key = lower_key(key)
  316. for actual, value in self._real:
  317. if lower_key(actual) == lowered_key:
  318. yield value
  319. def setdefault(self, key: K, default: V | None = None) -> V:
  320. """Get value for key, setting it to default if not present.
  321. Args:
  322. key: The key to look up
  323. default: Default value to set if key not found
  324. Returns:
  325. The existing value or the newly set default
  326. Raises:
  327. KeyError: If key not found and no default or default_factory
  328. """
  329. try:
  330. return self[key]
  331. except KeyError:
  332. if default is not None:
  333. self[key] = default
  334. return default
  335. elif self._default_factory is not None:
  336. value = self._default_factory()
  337. self[key] = value
  338. return value
  339. else:
  340. raise
  341. Name = bytes
  342. NameLike = bytes | str
  343. Section = tuple[bytes, ...]
  344. SectionLike = bytes | str | tuple[bytes | str, ...]
  345. Value = bytes
  346. ValueLike = bytes | str
  347. class Config:
  348. """A Git configuration."""
  349. def get(self, section: SectionLike, name: NameLike) -> Value:
  350. """Retrieve the contents of a configuration setting.
  351. Args:
  352. section: Tuple with section name and optional subsection name
  353. name: Variable name
  354. Returns:
  355. Contents of the setting
  356. Raises:
  357. KeyError: if the value is not set
  358. """
  359. raise NotImplementedError(self.get)
  360. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  361. """Retrieve the contents of a multivar configuration setting.
  362. Args:
  363. section: Tuple with section name and optional subsection namee
  364. name: Variable name
  365. Returns:
  366. Contents of the setting as iterable
  367. Raises:
  368. KeyError: if the value is not set
  369. """
  370. raise NotImplementedError(self.get_multivar)
  371. @overload
  372. def get_boolean(
  373. self, section: SectionLike, name: NameLike, default: bool
  374. ) -> bool: ...
  375. @overload
  376. def get_boolean(self, section: SectionLike, name: NameLike) -> bool | None: ...
  377. def get_boolean(
  378. self, section: SectionLike, name: NameLike, default: bool | None = None
  379. ) -> bool | None:
  380. """Retrieve a configuration setting as boolean.
  381. Args:
  382. section: Tuple with section name and optional subsection name
  383. name: Name of the setting, including section and possible
  384. subsection.
  385. default: Default value if setting is not found
  386. Returns:
  387. Contents of the setting
  388. """
  389. try:
  390. value = self.get(section, name)
  391. except KeyError:
  392. return default
  393. if value.lower() == b"true":
  394. return True
  395. elif value.lower() == b"false":
  396. return False
  397. raise ValueError(f"not a valid boolean string: {value!r}")
  398. def set(
  399. self, section: SectionLike, name: NameLike, value: ValueLike | bool
  400. ) -> None:
  401. """Set a configuration value.
  402. Args:
  403. section: Tuple with section name and optional subsection namee
  404. name: Name of the configuration value, including section
  405. and optional subsection
  406. value: value of the setting
  407. """
  408. raise NotImplementedError(self.set)
  409. def items(self, section: SectionLike) -> Iterator[tuple[Name, Value]]:
  410. """Iterate over the configuration pairs for a specific section.
  411. Args:
  412. section: Tuple with section name and optional subsection namee
  413. Returns:
  414. Iterator over (name, value) pairs
  415. """
  416. raise NotImplementedError(self.items)
  417. def sections(self) -> Iterator[Section]:
  418. """Iterate over the sections.
  419. Returns: Iterator over section tuples
  420. """
  421. raise NotImplementedError(self.sections)
  422. def has_section(self, name: Section) -> bool:
  423. """Check if a specified section exists.
  424. Args:
  425. name: Name of section to check for
  426. Returns:
  427. boolean indicating whether the section exists
  428. """
  429. return name in self.sections()
  430. class ConfigDict(Config):
  431. """Git configuration stored in a dictionary."""
  432. def __init__(
  433. self,
  434. values: MutableMapping[Section, CaseInsensitiveOrderedMultiDict[Name, Value]]
  435. | None = None,
  436. encoding: str | None = None,
  437. ) -> None:
  438. """Create a new ConfigDict."""
  439. if encoding is None:
  440. encoding = sys.getdefaultencoding()
  441. self.encoding = encoding
  442. self._values: CaseInsensitiveOrderedMultiDict[
  443. Section, CaseInsensitiveOrderedMultiDict[Name, Value]
  444. ] = CaseInsensitiveOrderedMultiDict.make(
  445. values, default_factory=CaseInsensitiveOrderedMultiDict
  446. )
  447. def __repr__(self) -> str:
  448. """Return string representation of ConfigDict."""
  449. return f"{self.__class__.__name__}({self._values!r})"
  450. def __eq__(self, other: object) -> bool:
  451. """Check equality with another ConfigDict."""
  452. return isinstance(other, self.__class__) and other._values == self._values
  453. def __getitem__(self, key: Section) -> CaseInsensitiveOrderedMultiDict[Name, Value]:
  454. """Get configuration values for a section.
  455. Raises:
  456. KeyError: If section not found
  457. """
  458. return self._values.__getitem__(key)
  459. def __setitem__(
  460. self, key: Section, value: CaseInsensitiveOrderedMultiDict[Name, Value]
  461. ) -> None:
  462. """Set configuration values for a section."""
  463. return self._values.__setitem__(key, value)
  464. def __delitem__(self, key: Section) -> None:
  465. """Delete a configuration section.
  466. Raises:
  467. KeyError: If section not found
  468. """
  469. return self._values.__delitem__(key)
  470. def __iter__(self) -> Iterator[Section]:
  471. """Iterate over configuration sections."""
  472. return self._values.__iter__()
  473. def __len__(self) -> int:
  474. """Return the number of sections."""
  475. return self._values.__len__()
  476. def keys(self) -> KeysView[Section]:
  477. """Return a view of section names."""
  478. return self._values.keys()
  479. @classmethod
  480. def _parse_setting(cls, name: str) -> tuple[str, str | None, str]:
  481. parts = name.split(".")
  482. if len(parts) == 3:
  483. return (parts[0], parts[1], parts[2])
  484. else:
  485. return (parts[0], None, parts[1])
  486. def _check_section_and_name(
  487. self, section: SectionLike, name: NameLike
  488. ) -> tuple[Section, Name]:
  489. if not isinstance(section, tuple):
  490. section = (section,)
  491. checked_section = tuple(
  492. [
  493. subsection.encode(self.encoding)
  494. if not isinstance(subsection, bytes)
  495. else subsection
  496. for subsection in section
  497. ]
  498. )
  499. if not isinstance(name, bytes):
  500. name = name.encode(self.encoding)
  501. return checked_section, name
  502. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  503. """Get multiple values for a configuration setting.
  504. Args:
  505. section: Section name
  506. name: Setting name
  507. Returns:
  508. Iterator of configuration values
  509. """
  510. section, name = self._check_section_and_name(section, name)
  511. if len(section) > 1:
  512. try:
  513. return self._values[section].get_all(name)
  514. except KeyError:
  515. pass
  516. return self._values[(section[0],)].get_all(name)
  517. def get(
  518. self,
  519. section: SectionLike,
  520. name: NameLike,
  521. ) -> Value:
  522. """Get a configuration value.
  523. Args:
  524. section: Section name
  525. name: Setting name
  526. Returns:
  527. Configuration value
  528. Raises:
  529. KeyError: if the value is not set
  530. """
  531. section, name = self._check_section_and_name(section, name)
  532. if len(section) > 1:
  533. try:
  534. return self._values[section][name]
  535. except KeyError:
  536. pass
  537. return self._values[(section[0],)][name]
  538. def set(
  539. self,
  540. section: SectionLike,
  541. name: NameLike,
  542. value: ValueLike | bool,
  543. ) -> None:
  544. """Set a configuration value.
  545. Args:
  546. section: Section name
  547. name: Setting name
  548. value: Configuration value
  549. """
  550. section, name = self._check_section_and_name(section, name)
  551. if isinstance(value, bool):
  552. value = b"true" if value else b"false"
  553. if not isinstance(value, bytes):
  554. value = value.encode(self.encoding)
  555. section_dict = self._values.setdefault(section)
  556. if hasattr(section_dict, "set"):
  557. section_dict.set(name, value)
  558. else:
  559. section_dict[name] = value
  560. def add(
  561. self,
  562. section: SectionLike,
  563. name: NameLike,
  564. value: ValueLike | bool,
  565. ) -> None:
  566. """Add a value to a configuration setting, creating a multivar if needed."""
  567. section, name = self._check_section_and_name(section, name)
  568. if isinstance(value, bool):
  569. value = b"true" if value else b"false"
  570. if not isinstance(value, bytes):
  571. value = value.encode(self.encoding)
  572. self._values.setdefault(section)[name] = value
  573. def items(self, section: SectionLike) -> Iterator[tuple[Name, Value]]:
  574. """Get items in a section."""
  575. section_bytes, _ = self._check_section_and_name(section, b"")
  576. section_dict = self._values.get(section_bytes)
  577. if section_dict is not None:
  578. return iter(section_dict.items())
  579. return iter([])
  580. def sections(self) -> Iterator[Section]:
  581. """Get all sections."""
  582. return iter(self._values.keys())
  583. def _format_string(value: bytes) -> bytes:
  584. if (
  585. value.startswith((b" ", b"\t"))
  586. or value.endswith((b" ", b"\t"))
  587. or b"#" in value
  588. ):
  589. return b'"' + _escape_value(value) + b'"'
  590. else:
  591. return _escape_value(value)
  592. _ESCAPE_TABLE = {
  593. ord(b"\\"): ord(b"\\"),
  594. ord(b'"'): ord(b'"'),
  595. ord(b"n"): ord(b"\n"),
  596. ord(b"t"): ord(b"\t"),
  597. ord(b"b"): ord(b"\b"),
  598. }
  599. _COMMENT_CHARS = [ord(b"#"), ord(b";")]
  600. _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")]
  601. def _parse_string(value: bytes) -> bytes:
  602. value_array = bytearray(value.strip())
  603. ret = bytearray()
  604. whitespace = bytearray()
  605. in_quotes = False
  606. i = 0
  607. while i < len(value_array):
  608. c = value_array[i]
  609. if c == ord(b"\\"):
  610. i += 1
  611. if i >= len(value_array):
  612. # Backslash at end of string - treat as literal backslash
  613. if whitespace:
  614. ret.extend(whitespace)
  615. whitespace = bytearray()
  616. ret.append(ord(b"\\"))
  617. else:
  618. try:
  619. v = _ESCAPE_TABLE[value_array[i]]
  620. if whitespace:
  621. ret.extend(whitespace)
  622. whitespace = bytearray()
  623. ret.append(v)
  624. except KeyError:
  625. # Unknown escape sequence - treat backslash as literal and process next char normally
  626. if whitespace:
  627. ret.extend(whitespace)
  628. whitespace = bytearray()
  629. ret.append(ord(b"\\"))
  630. i -= 1 # Reprocess the character after the backslash
  631. elif c == ord(b'"'):
  632. in_quotes = not in_quotes
  633. elif c in _COMMENT_CHARS and not in_quotes:
  634. # the rest of the line is a comment
  635. break
  636. elif c in _WHITESPACE_CHARS:
  637. whitespace.append(c)
  638. else:
  639. if whitespace:
  640. ret.extend(whitespace)
  641. whitespace = bytearray()
  642. ret.append(c)
  643. i += 1
  644. if in_quotes:
  645. raise ValueError("missing end quote")
  646. return bytes(ret)
  647. def _escape_value(value: bytes) -> bytes:
  648. """Escape a value."""
  649. value = value.replace(b"\\", b"\\\\")
  650. value = value.replace(b"\r", b"\\r")
  651. value = value.replace(b"\n", b"\\n")
  652. value = value.replace(b"\t", b"\\t")
  653. value = value.replace(b'"', b'\\"')
  654. return value
  655. def _check_variable_name(name: bytes) -> bool:
  656. for i in range(len(name)):
  657. c = name[i : i + 1]
  658. if not c.isalnum() and c != b"-":
  659. return False
  660. return True
  661. def _check_section_name(name: bytes) -> bool:
  662. for i in range(len(name)):
  663. c = name[i : i + 1]
  664. if not c.isalnum() and c not in (b"-", b"."):
  665. return False
  666. return True
  667. def _strip_comments(line: bytes) -> bytes:
  668. comment_bytes = {ord(b"#"), ord(b";")}
  669. quote = ord(b'"')
  670. string_open = False
  671. # Normalize line to bytearray for simple 2/3 compatibility
  672. for i, character in enumerate(bytearray(line)):
  673. # Comment characters outside balanced quotes denote comment start
  674. if character == quote:
  675. string_open = not string_open
  676. elif not string_open and character in comment_bytes:
  677. return line[:i]
  678. return line
  679. def _is_line_continuation(value: bytes) -> bool:
  680. """Check if a value ends with a line continuation backslash.
  681. A line continuation occurs when a line ends with a backslash that is:
  682. 1. Not escaped (not preceded by another backslash)
  683. 2. Not within quotes
  684. Args:
  685. value: The value to check
  686. Returns:
  687. True if the value ends with a line continuation backslash
  688. """
  689. if not value.endswith((b"\\\n", b"\\\r\n")):
  690. return False
  691. # Remove only the newline characters, keep the content including the backslash
  692. if value.endswith(b"\\\r\n"):
  693. content = value[:-2] # Remove \r\n, keep the \
  694. else:
  695. content = value[:-1] # Remove \n, keep the \
  696. if not content.endswith(b"\\"):
  697. return False
  698. # Count consecutive backslashes at the end
  699. backslash_count = 0
  700. for i in range(len(content) - 1, -1, -1):
  701. if content[i : i + 1] == b"\\":
  702. backslash_count += 1
  703. else:
  704. break
  705. # If we have an odd number of backslashes, the last one is a line continuation
  706. # If we have an even number, they are all escaped and there's no continuation
  707. return backslash_count % 2 == 1
  708. def _parse_section_header_line(line: bytes) -> tuple[Section, bytes]:
  709. # Parse section header ("[bla]")
  710. line = _strip_comments(line).rstrip()
  711. in_quotes = False
  712. escaped = False
  713. for i, c in enumerate(line):
  714. if escaped:
  715. escaped = False
  716. continue
  717. if c == ord(b'"'):
  718. in_quotes = not in_quotes
  719. if c == ord(b"\\"):
  720. escaped = True
  721. if c == ord(b"]") and not in_quotes:
  722. last = i
  723. break
  724. else:
  725. raise ValueError("expected trailing ]")
  726. pts = line[1:last].split(b" ", 1)
  727. line = line[last + 1 :]
  728. section: Section
  729. if len(pts) == 2:
  730. # Handle subsections - Git allows more complex syntax for certain sections like includeIf
  731. if pts[1][:1] == b'"' and pts[1][-1:] == b'"':
  732. # Standard quoted subsection
  733. pts[1] = pts[1][1:-1]
  734. elif pts[0] == b"includeIf":
  735. # Special handling for includeIf sections which can have complex conditions
  736. # Git allows these without strict quote validation
  737. pts[1] = pts[1].strip()
  738. if pts[1][:1] == b'"' and pts[1][-1:] == b'"':
  739. pts[1] = pts[1][1:-1]
  740. else:
  741. # Other sections must have quoted subsections
  742. raise ValueError(f"Invalid subsection {pts[1]!r}")
  743. if not _check_section_name(pts[0]):
  744. raise ValueError(f"invalid section name {pts[0]!r}")
  745. section = (pts[0], pts[1])
  746. else:
  747. if not _check_section_name(pts[0]):
  748. raise ValueError(f"invalid section name {pts[0]!r}")
  749. pts = pts[0].split(b".", 1)
  750. if len(pts) == 2:
  751. section = (pts[0], pts[1])
  752. else:
  753. section = (pts[0],)
  754. return section, line
  755. class ConfigFile(ConfigDict):
  756. """A Git configuration file, like .git/config or ~/.gitconfig."""
  757. def __init__(
  758. self,
  759. values: MutableMapping[Section, CaseInsensitiveOrderedMultiDict[Name, Value]]
  760. | None = None,
  761. encoding: str | None = None,
  762. ) -> None:
  763. """Initialize a ConfigFile.
  764. Args:
  765. values: Optional mapping of configuration values
  766. encoding: Optional encoding for the file (defaults to system encoding)
  767. """
  768. super().__init__(values=values, encoding=encoding)
  769. self.path: str | None = None
  770. self._included_paths: set[str] = set() # Track included files to prevent cycles
  771. @classmethod
  772. def from_file(
  773. cls,
  774. f: IO[bytes],
  775. *,
  776. config_dir: str | None = None,
  777. included_paths: set[str] | None = None,
  778. include_depth: int = 0,
  779. max_include_depth: int = DEFAULT_MAX_INCLUDE_DEPTH,
  780. file_opener: FileOpener | None = None,
  781. condition_matchers: Mapping[str, ConditionMatcher] | None = None,
  782. ) -> "ConfigFile":
  783. """Read configuration from a file-like object.
  784. Args:
  785. f: File-like object to read from
  786. config_dir: Directory containing the config file (for relative includes)
  787. included_paths: Set of already included paths (to prevent cycles)
  788. include_depth: Current include depth (to prevent infinite recursion)
  789. max_include_depth: Maximum allowed include depth
  790. file_opener: Optional callback to open included files
  791. condition_matchers: Optional dict of condition matchers for includeIf
  792. """
  793. if include_depth > max_include_depth:
  794. # Prevent excessive recursion
  795. raise ValueError(f"Maximum include depth ({max_include_depth}) exceeded")
  796. ret = cls()
  797. if included_paths is not None:
  798. ret._included_paths = included_paths.copy()
  799. section: Section | None = None
  800. setting = None
  801. continuation = None
  802. for lineno, line in enumerate(f.readlines()):
  803. if lineno == 0 and line.startswith(b"\xef\xbb\xbf"):
  804. line = line[3:]
  805. line = line.lstrip()
  806. if setting is None:
  807. if len(line) > 0 and line[:1] == b"[":
  808. section, line = _parse_section_header_line(line)
  809. ret._values.setdefault(section)
  810. if _strip_comments(line).strip() == b"":
  811. continue
  812. if section is None:
  813. raise ValueError(f"setting {line!r} without section")
  814. try:
  815. setting, value = line.split(b"=", 1)
  816. except ValueError:
  817. setting = line
  818. value = b"true"
  819. setting = setting.strip()
  820. if not _check_variable_name(setting):
  821. raise ValueError(f"invalid variable name {setting!r}")
  822. if _is_line_continuation(value):
  823. if value.endswith(b"\\\r\n"):
  824. continuation = value[:-3]
  825. else:
  826. continuation = value[:-2]
  827. else:
  828. continuation = None
  829. value = _parse_string(value)
  830. ret._values[section][setting] = value
  831. # Process include/includeIf directives
  832. ret._handle_include_directive(
  833. section,
  834. setting,
  835. value,
  836. config_dir=config_dir,
  837. include_depth=include_depth,
  838. max_include_depth=max_include_depth,
  839. file_opener=file_opener,
  840. condition_matchers=condition_matchers,
  841. )
  842. setting = None
  843. else: # continuation line
  844. assert continuation is not None
  845. if _is_line_continuation(line):
  846. if line.endswith(b"\\\r\n"):
  847. continuation += line[:-3]
  848. else:
  849. continuation += line[:-2]
  850. else:
  851. continuation += line
  852. value = _parse_string(continuation)
  853. assert section is not None # Already checked above
  854. ret._values[section][setting] = value
  855. # Process include/includeIf directives
  856. ret._handle_include_directive(
  857. section,
  858. setting,
  859. value,
  860. config_dir=config_dir,
  861. include_depth=include_depth,
  862. max_include_depth=max_include_depth,
  863. file_opener=file_opener,
  864. condition_matchers=condition_matchers,
  865. )
  866. continuation = None
  867. setting = None
  868. return ret
  869. def _handle_include_directive(
  870. self,
  871. section: Section | None,
  872. setting: bytes,
  873. value: bytes,
  874. *,
  875. config_dir: str | None,
  876. include_depth: int,
  877. max_include_depth: int,
  878. file_opener: FileOpener | None,
  879. condition_matchers: Mapping[str, ConditionMatcher] | None,
  880. ) -> None:
  881. """Handle include/includeIf directives during config parsing."""
  882. if (
  883. section is not None
  884. and setting == b"path"
  885. and (
  886. section[0].lower() == b"include"
  887. or (len(section) > 1 and section[0].lower() == b"includeif")
  888. )
  889. ):
  890. self._process_include(
  891. section,
  892. value,
  893. config_dir=config_dir,
  894. include_depth=include_depth,
  895. max_include_depth=max_include_depth,
  896. file_opener=file_opener,
  897. condition_matchers=condition_matchers,
  898. )
  899. def _process_include(
  900. self,
  901. section: Section,
  902. path_value: bytes,
  903. *,
  904. config_dir: str | None,
  905. include_depth: int,
  906. max_include_depth: int,
  907. file_opener: FileOpener | None,
  908. condition_matchers: Mapping[str, ConditionMatcher] | None,
  909. ) -> None:
  910. """Process an include or includeIf directive."""
  911. path_str = path_value.decode(self.encoding, errors="replace")
  912. # Handle includeIf conditions
  913. if len(section) > 1 and section[0].lower() == b"includeif":
  914. condition = section[1].decode(self.encoding, errors="replace")
  915. if not self._evaluate_includeif_condition(
  916. condition, config_dir, condition_matchers
  917. ):
  918. return
  919. # Resolve the include path
  920. include_path = self._resolve_include_path(path_str, config_dir)
  921. if not include_path:
  922. return
  923. # Check for circular includes
  924. try:
  925. abs_path = str(Path(include_path).resolve())
  926. except (OSError, ValueError) as e:
  927. # Invalid path - log and skip
  928. logger.debug("Invalid include path %r: %s", include_path, e)
  929. return
  930. if abs_path in self._included_paths:
  931. return
  932. # Load and merge the included file
  933. try:
  934. # Use provided file opener or default to GitFile
  935. opener: FileOpener
  936. if file_opener is None:
  937. def opener(path: str | os.PathLike[str]) -> IO[bytes]:
  938. return GitFile(path, "rb")
  939. else:
  940. opener = file_opener
  941. f = opener(include_path)
  942. except (OSError, ValueError) as e:
  943. # Git silently ignores missing or unreadable include files
  944. # Log for debugging purposes
  945. logger.debug("Invalid include path %r: %s", include_path, e)
  946. else:
  947. with f as included_file:
  948. # Track this path to prevent cycles
  949. self._included_paths.add(abs_path)
  950. # Parse the included file
  951. included_config = ConfigFile.from_file(
  952. included_file,
  953. config_dir=os.path.dirname(include_path),
  954. included_paths=self._included_paths,
  955. include_depth=include_depth + 1,
  956. max_include_depth=max_include_depth,
  957. file_opener=file_opener,
  958. condition_matchers=condition_matchers,
  959. )
  960. # Merge the included configuration
  961. self._merge_config(included_config)
  962. def _merge_config(self, other: "ConfigFile") -> None:
  963. """Merge another config file into this one."""
  964. for section, values in other._values.items():
  965. if section not in self._values:
  966. self._values[section] = CaseInsensitiveOrderedMultiDict()
  967. for key, value in values.items():
  968. self._values[section][key] = value
  969. def _resolve_include_path(self, path: str, config_dir: str | None) -> str | None:
  970. """Resolve an include path to an absolute path."""
  971. # Expand ~ to home directory
  972. path = os.path.expanduser(path)
  973. # If path is relative and we have a config directory, make it relative to that
  974. if not os.path.isabs(path) and config_dir:
  975. path = os.path.join(config_dir, path)
  976. return path
  977. def _evaluate_includeif_condition(
  978. self,
  979. condition: str,
  980. config_dir: str | None = None,
  981. condition_matchers: Mapping[str, ConditionMatcher] | None = None,
  982. ) -> bool:
  983. """Evaluate an includeIf condition."""
  984. # Try custom matchers first if provided
  985. if condition_matchers:
  986. for prefix, matcher in condition_matchers.items():
  987. if condition.startswith(prefix):
  988. return matcher(condition[len(prefix) :])
  989. # Fall back to built-in matchers
  990. if condition.startswith("hasconfig:"):
  991. return self._evaluate_hasconfig_condition(condition[10:])
  992. else:
  993. # Unknown condition type - log and ignore (Git behavior)
  994. logger.debug("Unknown includeIf condition: %r", condition)
  995. return False
  996. def _evaluate_hasconfig_condition(self, condition: str) -> bool:
  997. """Evaluate a hasconfig condition.
  998. Format: hasconfig:config.key:pattern
  999. Example: hasconfig:remote.*.url:ssh://org-*@github.com/**
  1000. """
  1001. # Split on the first colon to separate config key from pattern
  1002. parts = condition.split(":", 1)
  1003. if len(parts) != 2:
  1004. logger.debug("Invalid hasconfig condition format: %r", condition)
  1005. return False
  1006. config_key, pattern = parts
  1007. # Parse the config key to get section and name
  1008. key_parts = config_key.split(".", 2)
  1009. if len(key_parts) < 2:
  1010. logger.debug("Invalid hasconfig config key: %r", config_key)
  1011. return False
  1012. # Handle wildcards in section names (e.g., remote.*)
  1013. if len(key_parts) == 3 and key_parts[1] == "*":
  1014. # Match any subsection
  1015. section_prefix = key_parts[0].encode(self.encoding)
  1016. name = key_parts[2].encode(self.encoding)
  1017. # Check all sections that match the pattern
  1018. for section in self.sections():
  1019. if len(section) == 2 and section[0] == section_prefix:
  1020. try:
  1021. values = list(self.get_multivar(section, name))
  1022. for value in values:
  1023. if self._match_hasconfig_pattern(value, pattern):
  1024. return True
  1025. except KeyError:
  1026. continue
  1027. else:
  1028. # Direct section lookup
  1029. if len(key_parts) == 2:
  1030. section = (key_parts[0].encode(self.encoding),)
  1031. name = key_parts[1].encode(self.encoding)
  1032. else:
  1033. section = (
  1034. key_parts[0].encode(self.encoding),
  1035. key_parts[1].encode(self.encoding),
  1036. )
  1037. name = key_parts[2].encode(self.encoding)
  1038. try:
  1039. values = list(self.get_multivar(section, name))
  1040. for value in values:
  1041. if self._match_hasconfig_pattern(value, pattern):
  1042. return True
  1043. except KeyError:
  1044. pass
  1045. return False
  1046. def _match_hasconfig_pattern(self, value: bytes, pattern: str) -> bool:
  1047. """Match a config value against a hasconfig pattern.
  1048. Supports simple glob patterns like ``*`` and ``**``.
  1049. """
  1050. value_str = value.decode(self.encoding, errors="replace")
  1051. return match_glob_pattern(value_str, pattern)
  1052. @classmethod
  1053. def from_path(
  1054. cls,
  1055. path: str | os.PathLike[str],
  1056. *,
  1057. max_include_depth: int = DEFAULT_MAX_INCLUDE_DEPTH,
  1058. file_opener: FileOpener | None = None,
  1059. condition_matchers: Mapping[str, ConditionMatcher] | None = None,
  1060. ) -> "ConfigFile":
  1061. """Read configuration from a file on disk.
  1062. Args:
  1063. path: Path to the configuration file
  1064. max_include_depth: Maximum allowed include depth
  1065. file_opener: Optional callback to open included files
  1066. condition_matchers: Optional dict of condition matchers for includeIf
  1067. """
  1068. abs_path = os.fspath(path)
  1069. config_dir = os.path.dirname(abs_path)
  1070. # Use provided file opener or default to GitFile
  1071. opener: FileOpener
  1072. if file_opener is None:
  1073. def opener(p: str | os.PathLike[str]) -> IO[bytes]:
  1074. return GitFile(p, "rb")
  1075. else:
  1076. opener = file_opener
  1077. with opener(abs_path) as f:
  1078. ret = cls.from_file(
  1079. f,
  1080. config_dir=config_dir,
  1081. max_include_depth=max_include_depth,
  1082. file_opener=file_opener,
  1083. condition_matchers=condition_matchers,
  1084. )
  1085. ret.path = abs_path
  1086. return ret
  1087. def write_to_path(self, path: str | os.PathLike[str] | None = None) -> None:
  1088. """Write configuration to a file on disk."""
  1089. if path is None:
  1090. if self.path is None:
  1091. raise ValueError("No path specified and no default path available")
  1092. path_to_use: str | os.PathLike[str] = self.path
  1093. else:
  1094. path_to_use = path
  1095. with GitFile(path_to_use, "wb") as f:
  1096. self.write_to_file(f)
  1097. def write_to_file(self, f: IO[bytes] | _GitFile) -> None:
  1098. """Write configuration to a file-like object."""
  1099. for section, values in self._values.items():
  1100. try:
  1101. section_name, subsection_name = section
  1102. except ValueError:
  1103. (section_name,) = section
  1104. subsection_name = None
  1105. if subsection_name is None:
  1106. f.write(b"[" + section_name + b"]\n")
  1107. else:
  1108. f.write(b"[" + section_name + b' "' + subsection_name + b'"]\n')
  1109. for key, value in values.items():
  1110. value = _format_string(value)
  1111. f.write(b"\t" + key + b" = " + value + b"\n")
  1112. def get_xdg_config_home_path(*path_segments: str) -> str:
  1113. """Get a path in the XDG config home directory.
  1114. Args:
  1115. *path_segments: Path segments to join to the XDG config home
  1116. Returns:
  1117. Full path in XDG config home directory
  1118. """
  1119. xdg_config_home = os.environ.get(
  1120. "XDG_CONFIG_HOME",
  1121. os.path.expanduser("~/.config/"),
  1122. )
  1123. return os.path.join(xdg_config_home, *path_segments)
  1124. def _find_git_in_win_path() -> Iterator[str]:
  1125. for exe in ("git.exe", "git.cmd"):
  1126. for path in os.environ.get("PATH", "").split(";"):
  1127. if os.path.exists(os.path.join(path, exe)):
  1128. # in windows native shells (powershell/cmd) exe path is
  1129. # .../Git/bin/git.exe or .../Git/cmd/git.exe
  1130. #
  1131. # in git-bash exe path is .../Git/mingw64/bin/git.exe
  1132. git_dir, _bin_dir = os.path.split(path)
  1133. yield git_dir
  1134. parent_dir, basename = os.path.split(git_dir)
  1135. if basename == "mingw32" or basename == "mingw64":
  1136. yield parent_dir
  1137. break
  1138. def _find_git_in_win_reg() -> Iterator[str]:
  1139. import platform
  1140. import winreg
  1141. if platform.machine() == "AMD64":
  1142. subkey = (
  1143. "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\"
  1144. "CurrentVersion\\Uninstall\\Git_is1"
  1145. )
  1146. else:
  1147. subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
  1148. for key in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): # type: ignore[attr-defined,unused-ignore]
  1149. with suppress(OSError):
  1150. with winreg.OpenKey(key, subkey) as k: # type: ignore[attr-defined,unused-ignore]
  1151. val, typ = winreg.QueryValueEx(k, "InstallLocation") # type: ignore[attr-defined,unused-ignore]
  1152. if typ == winreg.REG_SZ: # type: ignore[attr-defined,unused-ignore]
  1153. yield val
  1154. # There is no set standard for system config dirs on windows. We try the
  1155. # following:
  1156. # - %PROGRAMFILES%/Git/etc/gitconfig - Git for Windows (msysgit) config dir
  1157. # Used if CGit installation (Git/bin/git.exe) is found in PATH in the
  1158. # system registry
  1159. def get_win_system_paths() -> Iterator[str]:
  1160. """Get current Windows system Git config paths.
  1161. Only returns the current Git for Windows config location, not legacy paths.
  1162. """
  1163. # Try to find Git installation from PATH first
  1164. for git_dir in _find_git_in_win_path():
  1165. yield os.path.join(git_dir, "etc", "gitconfig")
  1166. return # Only use the first found path
  1167. # Fall back to registry if not found in PATH
  1168. for git_dir in _find_git_in_win_reg():
  1169. yield os.path.join(git_dir, "etc", "gitconfig")
  1170. return # Only use the first found path
  1171. def get_win_legacy_system_paths() -> Iterator[str]:
  1172. """Get legacy Windows system Git config paths.
  1173. Returns all possible config paths including deprecated locations.
  1174. This function can be used for diagnostics or migration purposes.
  1175. """
  1176. # Include deprecated PROGRAMDATA location
  1177. if "PROGRAMDATA" in os.environ:
  1178. yield os.path.join(os.environ["PROGRAMDATA"], "Git", "config")
  1179. # Include all Git installations found
  1180. for git_dir in _find_git_in_win_path():
  1181. yield os.path.join(git_dir, "etc", "gitconfig")
  1182. for git_dir in _find_git_in_win_reg():
  1183. yield os.path.join(git_dir, "etc", "gitconfig")
  1184. class StackedConfig(Config):
  1185. """Configuration which reads from multiple config files.."""
  1186. def __init__(
  1187. self, backends: list[ConfigFile], writable: ConfigFile | None = None
  1188. ) -> None:
  1189. """Initialize a StackedConfig.
  1190. Args:
  1191. backends: List of config files to read from (in order of precedence)
  1192. writable: Optional config file to write changes to
  1193. """
  1194. self.backends = backends
  1195. self.writable = writable
  1196. def __repr__(self) -> str:
  1197. """Return string representation of StackedConfig."""
  1198. return f"<{self.__class__.__name__} for {self.backends!r}>"
  1199. @classmethod
  1200. def default(cls) -> "StackedConfig":
  1201. """Create a StackedConfig with default system/user config files.
  1202. Returns:
  1203. StackedConfig with default configuration files loaded
  1204. """
  1205. return cls(cls.default_backends())
  1206. @classmethod
  1207. def default_backends(cls) -> list[ConfigFile]:
  1208. """Retrieve the default configuration.
  1209. See git-config(1) for details on the files searched.
  1210. """
  1211. paths = []
  1212. # Handle GIT_CONFIG_GLOBAL - overrides user config paths
  1213. try:
  1214. paths.append(os.environ["GIT_CONFIG_GLOBAL"])
  1215. except KeyError:
  1216. paths.append(os.path.expanduser("~/.gitconfig"))
  1217. paths.append(get_xdg_config_home_path("git", "config"))
  1218. # Handle GIT_CONFIG_SYSTEM and GIT_CONFIG_NOSYSTEM
  1219. try:
  1220. paths.append(os.environ["GIT_CONFIG_SYSTEM"])
  1221. except KeyError:
  1222. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  1223. paths.append("/etc/gitconfig")
  1224. if sys.platform == "win32":
  1225. paths.extend(get_win_system_paths())
  1226. logger.debug("Loading gitconfig from paths: %s", paths)
  1227. backends = []
  1228. for path in paths:
  1229. try:
  1230. cf = ConfigFile.from_path(path)
  1231. logger.debug("Successfully loaded gitconfig from: %s", path)
  1232. except FileNotFoundError:
  1233. logger.debug("Gitconfig file not found: %s", path)
  1234. continue
  1235. backends.append(cf)
  1236. return backends
  1237. def get(self, section: SectionLike, name: NameLike) -> Value:
  1238. """Get value from configuration."""
  1239. if not isinstance(section, tuple):
  1240. section = (section,)
  1241. for backend in self.backends:
  1242. try:
  1243. return backend.get(section, name)
  1244. except KeyError:
  1245. pass
  1246. raise KeyError(name)
  1247. def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]:
  1248. """Get multiple values from configuration."""
  1249. if not isinstance(section, tuple):
  1250. section = (section,)
  1251. for backend in self.backends:
  1252. try:
  1253. yield from backend.get_multivar(section, name)
  1254. except KeyError:
  1255. pass
  1256. def set(
  1257. self, section: SectionLike, name: NameLike, value: ValueLike | bool
  1258. ) -> None:
  1259. """Set value in configuration."""
  1260. if self.writable is None:
  1261. raise NotImplementedError(self.set)
  1262. return self.writable.set(section, name, value)
  1263. def sections(self) -> Iterator[Section]:
  1264. """Get all sections."""
  1265. seen = set()
  1266. for backend in self.backends:
  1267. for section in backend.sections():
  1268. if section not in seen:
  1269. seen.add(section)
  1270. yield section
  1271. def read_submodules(
  1272. path: str | os.PathLike[str],
  1273. ) -> Iterator[tuple[bytes, bytes, bytes]]:
  1274. """Read a .gitmodules file."""
  1275. cfg = ConfigFile.from_path(path)
  1276. return parse_submodules(cfg)
  1277. def parse_submodules(config: ConfigFile) -> Iterator[tuple[bytes, bytes, bytes]]:
  1278. """Parse a gitmodules GitConfig file, returning submodules.
  1279. Args:
  1280. config: A `ConfigFile`
  1281. Returns:
  1282. list of tuples (submodule path, url, name),
  1283. where name is quoted part of the section's name.
  1284. """
  1285. for section in config.sections():
  1286. section_kind, section_name = section
  1287. if section_kind == b"submodule":
  1288. try:
  1289. sm_path = config.get(section, b"path")
  1290. sm_url = config.get(section, b"url")
  1291. yield (sm_path, sm_url, section_name)
  1292. except KeyError:
  1293. # If either path or url is missing, just ignore this
  1294. # submodule entry and move on to the next one. This is
  1295. # how git itself handles malformed .gitmodule entries.
  1296. pass
  1297. def iter_instead_of(config: Config, push: bool = False) -> Iterable[tuple[str, str]]:
  1298. """Iterate over insteadOf / pushInsteadOf values."""
  1299. for section in config.sections():
  1300. if section[0] != b"url":
  1301. continue
  1302. replacement = section[1]
  1303. try:
  1304. needles = list(config.get_multivar(section, "insteadOf"))
  1305. except KeyError:
  1306. needles = []
  1307. if push:
  1308. try:
  1309. needles += list(config.get_multivar(section, "pushInsteadOf"))
  1310. except KeyError:
  1311. pass
  1312. for needle in needles:
  1313. assert isinstance(needle, bytes)
  1314. yield needle.decode("utf-8"), replacement.decode("utf-8")
  1315. def apply_instead_of(config: Config, orig_url: str, push: bool = False) -> str:
  1316. """Apply insteadOf / pushInsteadOf to a URL."""
  1317. longest_needle = ""
  1318. updated_url = orig_url
  1319. for needle, replacement in iter_instead_of(config, push):
  1320. if not orig_url.startswith(needle):
  1321. continue
  1322. if len(longest_needle) < len(needle):
  1323. longest_needle = needle
  1324. updated_url = replacement + orig_url[len(needle) :]
  1325. return updated_url