config.py 53 KB

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