config.py 51 KB

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