config.py 52 KB

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