2
0

config.py 53 KB

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