repo.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. # repo.py -- For dealing with git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as published by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Repository access.
  23. This module contains the base class for git repositories
  24. (BaseRepo) and an implementation which uses a repository on
  25. local disk (Repo).
  26. """
  27. import os
  28. import stat
  29. import sys
  30. import time
  31. import warnings
  32. from collections.abc import Generator, Iterable, Iterator
  33. from io import BytesIO
  34. from types import TracebackType
  35. from typing import (
  36. TYPE_CHECKING,
  37. Any,
  38. BinaryIO,
  39. Callable,
  40. Optional,
  41. TypeVar,
  42. Union,
  43. )
  44. if TYPE_CHECKING:
  45. # There are no circular imports here, but we try to defer imports as long
  46. # as possible to reduce start-up time for anything that doesn't need
  47. # these imports.
  48. from .attrs import GitAttributes
  49. from .config import ConditionMatcher, ConfigFile, StackedConfig
  50. from .diff_tree import RenameDetector
  51. from .filters import FilterBlobNormalizer, FilterContext
  52. from .index import Index
  53. from .notes import Notes
  54. from .object_store import BaseObjectStore, GraphWalker
  55. from .pack import UnpackedObject
  56. from .rebase import RebaseStateManager
  57. from .walk import Walker
  58. from .worktree import WorkTree
  59. from . import reflog, replace_me
  60. from .errors import (
  61. NoIndexPresent,
  62. NotBlobError,
  63. NotCommitError,
  64. NotGitRepository,
  65. NotTagError,
  66. NotTreeError,
  67. RefFormatError,
  68. )
  69. from .file import GitFile
  70. from .hooks import (
  71. CommitMsgShellHook,
  72. Hook,
  73. PostCommitShellHook,
  74. PostReceiveShellHook,
  75. PreCommitShellHook,
  76. )
  77. from .object_store import (
  78. DiskObjectStore,
  79. MemoryObjectStore,
  80. MissingObjectFinder,
  81. ObjectStoreGraphWalker,
  82. PackBasedObjectStore,
  83. find_shallow,
  84. peel_sha,
  85. )
  86. from .objects import (
  87. Blob,
  88. Commit,
  89. ObjectID,
  90. ShaFile,
  91. Tag,
  92. Tree,
  93. check_hexsha,
  94. valid_hexsha,
  95. )
  96. from .pack import generate_unpacked_objects
  97. from .refs import (
  98. ANNOTATED_TAG_SUFFIX, # noqa: F401
  99. LOCAL_BRANCH_PREFIX,
  100. LOCAL_TAG_PREFIX, # noqa: F401
  101. SYMREF, # noqa: F401
  102. DictRefsContainer,
  103. DiskRefsContainer,
  104. InfoRefsContainer, # noqa: F401
  105. Ref,
  106. RefsContainer,
  107. _set_default_branch,
  108. _set_head,
  109. _set_origin_head,
  110. check_ref_format, # noqa: F401
  111. is_per_worktree_ref,
  112. read_packed_refs, # noqa: F401
  113. read_packed_refs_with_peeled, # noqa: F401
  114. serialize_refs,
  115. write_packed_refs, # noqa: F401
  116. )
  117. CONTROLDIR = ".git"
  118. OBJECTDIR = "objects"
  119. DEFAULT_OFS_DELTA = True
  120. T = TypeVar("T", bound="ShaFile")
  121. REFSDIR = "refs"
  122. REFSDIR_TAGS = "tags"
  123. REFSDIR_HEADS = "heads"
  124. INDEX_FILENAME = "index"
  125. COMMONDIR = "commondir"
  126. GITDIR = "gitdir"
  127. WORKTREES = "worktrees"
  128. BASE_DIRECTORIES = [
  129. ["branches"],
  130. [REFSDIR],
  131. [REFSDIR, REFSDIR_TAGS],
  132. [REFSDIR, REFSDIR_HEADS],
  133. ["hooks"],
  134. ["info"],
  135. ]
  136. DEFAULT_BRANCH = b"master"
  137. class InvalidUserIdentity(Exception):
  138. """User identity is not of the format 'user <email>'."""
  139. def __init__(self, identity: str) -> None:
  140. """Initialize InvalidUserIdentity exception."""
  141. self.identity = identity
  142. class DefaultIdentityNotFound(Exception):
  143. """Default identity could not be determined."""
  144. # TODO(jelmer): Cache?
  145. def _get_default_identity() -> tuple[str, str]:
  146. import socket
  147. for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
  148. username = os.environ.get(name)
  149. if username:
  150. break
  151. else:
  152. username = None
  153. try:
  154. import pwd
  155. except ImportError:
  156. fullname = None
  157. else:
  158. try:
  159. entry = pwd.getpwuid(os.getuid()) # type: ignore[attr-defined,unused-ignore]
  160. except KeyError:
  161. fullname = None
  162. else:
  163. if getattr(entry, "gecos", None):
  164. fullname = entry.pw_gecos.split(",")[0]
  165. else:
  166. fullname = None
  167. if username is None:
  168. username = entry.pw_name
  169. if not fullname:
  170. if username is None:
  171. raise DefaultIdentityNotFound("no username found")
  172. fullname = username
  173. email = os.environ.get("EMAIL")
  174. if email is None:
  175. if username is None:
  176. raise DefaultIdentityNotFound("no username found")
  177. email = f"{username}@{socket.gethostname()}"
  178. return (fullname, email)
  179. def get_user_identity(config: "StackedConfig", kind: Optional[str] = None) -> bytes:
  180. """Determine the identity to use for new commits.
  181. If kind is set, this first checks
  182. GIT_${KIND}_NAME and GIT_${KIND}_EMAIL.
  183. If those variables are not set, then it will fall back
  184. to reading the user.name and user.email settings from
  185. the specified configuration.
  186. If that also fails, then it will fall back to using
  187. the current users' identity as obtained from the host
  188. system (e.g. the gecos field, $EMAIL, $USER@$(hostname -f).
  189. Args:
  190. config: Configuration stack to read from
  191. kind: Optional kind to return identity for,
  192. usually either "AUTHOR" or "COMMITTER".
  193. Returns:
  194. A user identity
  195. """
  196. user: Optional[bytes] = None
  197. email: Optional[bytes] = None
  198. if kind:
  199. user_uc = os.environ.get("GIT_" + kind + "_NAME")
  200. if user_uc is not None:
  201. user = user_uc.encode("utf-8")
  202. email_uc = os.environ.get("GIT_" + kind + "_EMAIL")
  203. if email_uc is not None:
  204. email = email_uc.encode("utf-8")
  205. if user is None:
  206. try:
  207. user = config.get(("user",), "name")
  208. except KeyError:
  209. user = None
  210. if email is None:
  211. try:
  212. email = config.get(("user",), "email")
  213. except KeyError:
  214. email = None
  215. default_user, default_email = _get_default_identity()
  216. if user is None:
  217. user = default_user.encode("utf-8")
  218. if email is None:
  219. email = default_email.encode("utf-8")
  220. if email.startswith(b"<") and email.endswith(b">"):
  221. email = email[1:-1]
  222. return user + b" <" + email + b">"
  223. def check_user_identity(identity: bytes) -> None:
  224. """Verify that a user identity is formatted correctly.
  225. Args:
  226. identity: User identity bytestring
  227. Raises:
  228. InvalidUserIdentity: Raised when identity is invalid
  229. """
  230. try:
  231. _fst, snd = identity.split(b" <", 1)
  232. except ValueError as exc:
  233. raise InvalidUserIdentity(identity.decode("utf-8", "replace")) from exc
  234. if b">" not in snd:
  235. raise InvalidUserIdentity(identity.decode("utf-8", "replace"))
  236. if b"\0" in identity or b"\n" in identity:
  237. raise InvalidUserIdentity(identity.decode("utf-8", "replace"))
  238. def parse_graftpoints(
  239. graftpoints: Iterable[bytes],
  240. ) -> dict[bytes, list[bytes]]:
  241. """Convert a list of graftpoints into a dict.
  242. Args:
  243. graftpoints: Iterator of graftpoint lines
  244. Each line is formatted as:
  245. <commit sha1> <parent sha1> [<parent sha1>]*
  246. Resulting dictionary is:
  247. <commit sha1>: [<parent sha1>*]
  248. https://git.wiki.kernel.org/index.php/GraftPoint
  249. """
  250. grafts = {}
  251. for line in graftpoints:
  252. raw_graft = line.split(None, 1)
  253. commit = raw_graft[0]
  254. if len(raw_graft) == 2:
  255. parents = raw_graft[1].split()
  256. else:
  257. parents = []
  258. for sha in [commit, *parents]:
  259. check_hexsha(sha, "Invalid graftpoint")
  260. grafts[commit] = parents
  261. return grafts
  262. def serialize_graftpoints(graftpoints: dict[bytes, list[bytes]]) -> bytes:
  263. """Convert a dictionary of grafts into string.
  264. The graft dictionary is:
  265. <commit sha1>: [<parent sha1>*]
  266. Each line is formatted as:
  267. <commit sha1> <parent sha1> [<parent sha1>]*
  268. https://git.wiki.kernel.org/index.php/GraftPoint
  269. """
  270. graft_lines = []
  271. for commit, parents in graftpoints.items():
  272. if parents:
  273. graft_lines.append(commit + b" " + b" ".join(parents))
  274. else:
  275. graft_lines.append(commit)
  276. return b"\n".join(graft_lines)
  277. def _set_filesystem_hidden(path: str) -> None:
  278. """Mark path as to be hidden if supported by platform and filesystem.
  279. On win32 uses SetFileAttributesW api:
  280. <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
  281. """
  282. if sys.platform == "win32":
  283. import ctypes
  284. from ctypes.wintypes import BOOL, DWORD, LPCWSTR
  285. FILE_ATTRIBUTE_HIDDEN = 2
  286. SetFileAttributesW = ctypes.WINFUNCTYPE(BOOL, LPCWSTR, DWORD)(
  287. ("SetFileAttributesW", ctypes.windll.kernel32)
  288. )
  289. if isinstance(path, bytes):
  290. path = os.fsdecode(path)
  291. if not SetFileAttributesW(path, FILE_ATTRIBUTE_HIDDEN):
  292. pass # Could raise or log `ctypes.WinError()` here
  293. # Could implement other platform specific filesystem hiding here
  294. class ParentsProvider:
  295. """Provider for commit parent information."""
  296. def __init__(
  297. self,
  298. store: "BaseObjectStore",
  299. grafts: dict[bytes, list[bytes]] = {},
  300. shallows: Iterable[bytes] = [],
  301. ) -> None:
  302. """Initialize ParentsProvider.
  303. Args:
  304. store: Object store to use
  305. grafts: Graft information
  306. shallows: Shallow commit SHAs
  307. """
  308. self.store = store
  309. self.grafts = grafts
  310. self.shallows = set(shallows)
  311. # Get commit graph once at initialization for performance
  312. self.commit_graph = store.get_commit_graph()
  313. def get_parents(
  314. self, commit_id: bytes, commit: Optional[Commit] = None
  315. ) -> list[bytes]:
  316. """Get parents for a commit using the parents provider."""
  317. try:
  318. return self.grafts[commit_id]
  319. except KeyError:
  320. pass
  321. if commit_id in self.shallows:
  322. return []
  323. # Try to use commit graph for faster parent lookup
  324. if self.commit_graph:
  325. parents = self.commit_graph.get_parents(commit_id)
  326. if parents is not None:
  327. return parents
  328. # Fallback to reading the commit object
  329. if commit is None:
  330. obj = self.store[commit_id]
  331. assert isinstance(obj, Commit)
  332. commit = obj
  333. parents = commit.parents
  334. assert isinstance(parents, list)
  335. return parents
  336. class BaseRepo:
  337. """Base class for a git repository.
  338. This base class is meant to be used for Repository implementations that e.g.
  339. work on top of a different transport than a standard filesystem path.
  340. Attributes:
  341. object_store: Dictionary-like object for accessing
  342. the objects
  343. refs: Dictionary-like object with the refs in this
  344. repository
  345. """
  346. def __init__(self, object_store: PackBasedObjectStore, refs: RefsContainer) -> None:
  347. """Open a repository.
  348. This shouldn't be called directly, but rather through one of the
  349. base classes, such as MemoryRepo or Repo.
  350. Args:
  351. object_store: Object store to use
  352. refs: Refs container to use
  353. """
  354. self.object_store = object_store
  355. self.refs = refs
  356. self._graftpoints: dict[bytes, list[bytes]] = {}
  357. self.hooks: dict[str, Hook] = {}
  358. def _determine_file_mode(self) -> bool:
  359. """Probe the file-system to determine whether permissions can be trusted.
  360. Returns: True if permissions can be trusted, False otherwise.
  361. """
  362. raise NotImplementedError(self._determine_file_mode)
  363. def _determine_symlinks(self) -> bool:
  364. """Probe the filesystem to determine whether symlinks can be created.
  365. Returns: True if symlinks can be created, False otherwise.
  366. """
  367. # For now, just mimic the old behaviour
  368. return sys.platform != "win32"
  369. def _init_files(
  370. self, bare: bool, symlinks: Optional[bool] = None, format: Optional[int] = None
  371. ) -> None:
  372. """Initialize a default set of named files."""
  373. from .config import ConfigFile
  374. self._put_named_file("description", b"Unnamed repository")
  375. f = BytesIO()
  376. cf = ConfigFile()
  377. if format is None:
  378. format = 0
  379. if format not in (0, 1):
  380. raise ValueError(f"Unsupported repository format version: {format}")
  381. cf.set("core", "repositoryformatversion", str(format))
  382. if self._determine_file_mode():
  383. cf.set("core", "filemode", True)
  384. else:
  385. cf.set("core", "filemode", False)
  386. if symlinks is None and not bare:
  387. symlinks = self._determine_symlinks()
  388. if symlinks is False:
  389. cf.set("core", "symlinks", symlinks)
  390. cf.set("core", "bare", bare)
  391. cf.set("core", "logallrefupdates", True)
  392. cf.write_to_file(f)
  393. self._put_named_file("config", f.getvalue())
  394. self._put_named_file(os.path.join("info", "exclude"), b"")
  395. def get_named_file(self, path: str) -> Optional[BinaryIO]:
  396. """Get a file from the control dir with a specific name.
  397. Although the filename should be interpreted as a filename relative to
  398. the control dir in a disk-based Repo, the object returned need not be
  399. pointing to a file in that location.
  400. Args:
  401. path: The path to the file, relative to the control dir.
  402. Returns: An open file object, or None if the file does not exist.
  403. """
  404. raise NotImplementedError(self.get_named_file)
  405. def _put_named_file(self, path: str, contents: bytes) -> None:
  406. """Write a file to the control dir with the given name and contents.
  407. Args:
  408. path: The path to the file, relative to the control dir.
  409. contents: A string to write to the file.
  410. """
  411. raise NotImplementedError(self._put_named_file)
  412. def _del_named_file(self, path: str) -> None:
  413. """Delete a file in the control directory with the given name."""
  414. raise NotImplementedError(self._del_named_file)
  415. def open_index(self) -> "Index":
  416. """Open the index for this repository.
  417. Raises:
  418. NoIndexPresent: If no index is present
  419. Returns: The matching `Index`
  420. """
  421. raise NotImplementedError(self.open_index)
  422. def fetch(
  423. self,
  424. target: "BaseRepo",
  425. determine_wants: Optional[
  426. Callable[[dict[bytes, bytes], Optional[int]], list[bytes]]
  427. ] = None,
  428. progress: Optional[Callable[..., None]] = None,
  429. depth: Optional[int] = None,
  430. ) -> dict[bytes, bytes]:
  431. """Fetch objects into another repository.
  432. Args:
  433. target: The target repository
  434. determine_wants: Optional function to determine what refs to
  435. fetch.
  436. progress: Optional progress function
  437. depth: Optional shallow fetch depth
  438. Returns: The local refs
  439. """
  440. if determine_wants is None:
  441. determine_wants = target.object_store.determine_wants_all
  442. count, pack_data = self.fetch_pack_data(
  443. determine_wants,
  444. target.get_graph_walker(),
  445. progress=progress,
  446. depth=depth,
  447. )
  448. target.object_store.add_pack_data(count, pack_data, progress)
  449. return self.get_refs()
  450. def fetch_pack_data(
  451. self,
  452. determine_wants: Callable[[dict[bytes, bytes], Optional[int]], list[bytes]],
  453. graph_walker: "GraphWalker",
  454. progress: Optional[Callable[[bytes], None]],
  455. *,
  456. get_tagged: Optional[Callable[[], dict[bytes, bytes]]] = None,
  457. depth: Optional[int] = None,
  458. ) -> tuple[int, Iterator["UnpackedObject"]]:
  459. """Fetch the pack data required for a set of revisions.
  460. Args:
  461. determine_wants: Function that takes a dictionary with heads
  462. and returns the list of heads to fetch.
  463. graph_walker: Object that can iterate over the list of revisions
  464. to fetch and has an "ack" method that will be called to acknowledge
  465. that a revision is present.
  466. progress: Simple progress function that will be called with
  467. updated progress strings.
  468. get_tagged: Function that returns a dict of pointed-to sha ->
  469. tag sha for including tags.
  470. depth: Shallow fetch depth
  471. Returns: count and iterator over pack data
  472. """
  473. missing_objects = self.find_missing_objects(
  474. determine_wants, graph_walker, progress, get_tagged=get_tagged, depth=depth
  475. )
  476. if missing_objects is None:
  477. return 0, iter([])
  478. remote_has = missing_objects.get_remote_has()
  479. object_ids = list(missing_objects)
  480. return len(object_ids), generate_unpacked_objects(
  481. self.object_store, object_ids, progress=progress, other_haves=remote_has
  482. )
  483. def find_missing_objects(
  484. self,
  485. determine_wants: Callable[[dict[bytes, bytes], Optional[int]], list[bytes]],
  486. graph_walker: "GraphWalker",
  487. progress: Optional[Callable[[bytes], None]],
  488. *,
  489. get_tagged: Optional[Callable[[], dict[bytes, bytes]]] = None,
  490. depth: Optional[int] = None,
  491. ) -> Optional[MissingObjectFinder]:
  492. """Fetch the missing objects required for a set of revisions.
  493. Args:
  494. determine_wants: Function that takes a dictionary with heads
  495. and returns the list of heads to fetch.
  496. graph_walker: Object that can iterate over the list of revisions
  497. to fetch and has an "ack" method that will be called to acknowledge
  498. that a revision is present.
  499. progress: Simple progress function that will be called with
  500. updated progress strings.
  501. get_tagged: Function that returns a dict of pointed-to sha ->
  502. tag sha for including tags.
  503. depth: Shallow fetch depth
  504. Returns: iterator over objects, with __len__ implemented
  505. """
  506. refs = serialize_refs(self.object_store, self.get_refs())
  507. wants = determine_wants(refs, depth)
  508. if not isinstance(wants, list):
  509. raise TypeError("determine_wants() did not return a list")
  510. current_shallow = set(getattr(graph_walker, "shallow", set()))
  511. if depth not in (None, 0):
  512. assert depth is not None
  513. shallow, not_shallow = find_shallow(self.object_store, wants, depth)
  514. # Only update if graph_walker has shallow attribute
  515. if hasattr(graph_walker, "shallow"):
  516. graph_walker.shallow.update(shallow - not_shallow)
  517. new_shallow = graph_walker.shallow - current_shallow
  518. unshallow = graph_walker.unshallow = not_shallow & current_shallow # type: ignore[attr-defined]
  519. if hasattr(graph_walker, "update_shallow"):
  520. graph_walker.update_shallow(new_shallow, unshallow)
  521. else:
  522. unshallow = getattr(graph_walker, "unshallow", set())
  523. if wants == []:
  524. # TODO(dborowitz): find a way to short-circuit that doesn't change
  525. # this interface.
  526. if getattr(graph_walker, "shallow", set()) or unshallow:
  527. # Do not send a pack in shallow short-circuit path
  528. return None
  529. class DummyMissingObjectFinder:
  530. """Dummy finder that returns no missing objects."""
  531. def get_remote_has(self) -> None:
  532. """Get remote has (always returns None).
  533. Returns:
  534. None
  535. """
  536. return None
  537. def __len__(self) -> int:
  538. return 0
  539. def __iter__(self) -> Iterator[tuple[bytes, Optional[bytes]]]:
  540. yield from []
  541. return DummyMissingObjectFinder() # type: ignore
  542. # If the graph walker is set up with an implementation that can
  543. # ACK/NAK to the wire, it will write data to the client through
  544. # this call as a side-effect.
  545. haves = self.object_store.find_common_revisions(graph_walker)
  546. # Deal with shallow requests separately because the haves do
  547. # not reflect what objects are missing
  548. if getattr(graph_walker, "shallow", set()) or unshallow:
  549. # TODO: filter the haves commits from iter_shas. the specific
  550. # commits aren't missing.
  551. haves = []
  552. parents_provider = ParentsProvider(self.object_store, shallows=current_shallow)
  553. def get_parents(commit: Commit) -> list[bytes]:
  554. """Get parents for a commit using the parents provider.
  555. Args:
  556. commit: Commit object
  557. Returns:
  558. List of parent commit SHAs
  559. """
  560. return parents_provider.get_parents(commit.id, commit)
  561. return MissingObjectFinder(
  562. self.object_store,
  563. haves=haves,
  564. wants=wants,
  565. shallow=getattr(graph_walker, "shallow", set()),
  566. progress=progress,
  567. get_tagged=get_tagged,
  568. get_parents=get_parents,
  569. )
  570. def generate_pack_data(
  571. self,
  572. have: set[ObjectID],
  573. want: set[ObjectID],
  574. progress: Optional[Callable[[str], None]] = None,
  575. ofs_delta: Optional[bool] = None,
  576. ) -> tuple[int, Iterator["UnpackedObject"]]:
  577. """Generate pack data objects for a set of wants/haves.
  578. Args:
  579. have: List of SHA1s of objects that should not be sent
  580. want: List of SHA1s of objects that should be sent
  581. ofs_delta: Whether OFS deltas can be included
  582. progress: Optional progress reporting method
  583. """
  584. return self.object_store.generate_pack_data(
  585. have,
  586. want,
  587. shallow=self.get_shallow(),
  588. progress=progress,
  589. ofs_delta=ofs_delta if ofs_delta is not None else DEFAULT_OFS_DELTA,
  590. )
  591. def get_graph_walker(
  592. self, heads: Optional[list[ObjectID]] = None
  593. ) -> ObjectStoreGraphWalker:
  594. """Retrieve a graph walker.
  595. A graph walker is used by a remote repository (or proxy)
  596. to find out which objects are present in this repository.
  597. Args:
  598. heads: Repository heads to use (optional)
  599. Returns: A graph walker object
  600. """
  601. if heads is None:
  602. heads = [
  603. sha
  604. for sha in self.refs.as_dict(b"refs/heads").values()
  605. if sha in self.object_store
  606. ]
  607. parents_provider = ParentsProvider(self.object_store)
  608. return ObjectStoreGraphWalker(
  609. heads,
  610. parents_provider.get_parents,
  611. shallow=self.get_shallow(),
  612. update_shallow=self.update_shallow,
  613. )
  614. def get_refs(self) -> dict[bytes, bytes]:
  615. """Get dictionary with all refs.
  616. Returns: A ``dict`` mapping ref names to SHA1s
  617. """
  618. return self.refs.as_dict()
  619. def head(self) -> bytes:
  620. """Return the SHA1 pointed at by HEAD."""
  621. # TODO: move this method to WorkTree
  622. return self.refs[b"HEAD"]
  623. def _get_object(self, sha: bytes, cls: type[T]) -> T:
  624. assert len(sha) in (20, 40)
  625. ret = self.get_object(sha)
  626. if not isinstance(ret, cls):
  627. if cls is Commit:
  628. raise NotCommitError(ret.id)
  629. elif cls is Blob:
  630. raise NotBlobError(ret.id)
  631. elif cls is Tree:
  632. raise NotTreeError(ret.id)
  633. elif cls is Tag:
  634. raise NotTagError(ret.id)
  635. else:
  636. raise Exception(f"Type invalid: {ret.type_name!r} != {cls.type_name!r}")
  637. return ret
  638. def get_object(self, sha: bytes) -> ShaFile:
  639. """Retrieve the object with the specified SHA.
  640. Args:
  641. sha: SHA to retrieve
  642. Returns: A ShaFile object
  643. Raises:
  644. KeyError: when the object can not be found
  645. """
  646. return self.object_store[sha]
  647. def parents_provider(self) -> ParentsProvider:
  648. """Get a parents provider for this repository.
  649. Returns:
  650. ParentsProvider instance configured with grafts and shallows
  651. """
  652. return ParentsProvider(
  653. self.object_store,
  654. grafts=self._graftpoints,
  655. shallows=self.get_shallow(),
  656. )
  657. def get_parents(self, sha: bytes, commit: Optional[Commit] = None) -> list[bytes]:
  658. """Retrieve the parents of a specific commit.
  659. If the specific commit is a graftpoint, the graft parents
  660. will be returned instead.
  661. Args:
  662. sha: SHA of the commit for which to retrieve the parents
  663. commit: Optional commit matching the sha
  664. Returns: List of parents
  665. """
  666. return self.parents_provider().get_parents(sha, commit)
  667. def get_config(self) -> "ConfigFile":
  668. """Retrieve the config object.
  669. Returns: `ConfigFile` object for the ``.git/config`` file.
  670. """
  671. raise NotImplementedError(self.get_config)
  672. def get_worktree_config(self) -> "ConfigFile":
  673. """Retrieve the worktree config object."""
  674. raise NotImplementedError(self.get_worktree_config)
  675. def get_description(self) -> Optional[bytes]:
  676. """Retrieve the description for this repository.
  677. Returns: Bytes with the description of the repository
  678. as set by the user.
  679. """
  680. raise NotImplementedError(self.get_description)
  681. def set_description(self, description: bytes) -> None:
  682. """Set the description for this repository.
  683. Args:
  684. description: Text to set as description for this repository.
  685. """
  686. raise NotImplementedError(self.set_description)
  687. def get_rebase_state_manager(self) -> "RebaseStateManager":
  688. """Get the appropriate rebase state manager for this repository.
  689. Returns: RebaseStateManager instance
  690. """
  691. raise NotImplementedError(self.get_rebase_state_manager)
  692. def get_blob_normalizer(self) -> "FilterBlobNormalizer":
  693. """Return a BlobNormalizer object for checkin/checkout operations.
  694. Returns: BlobNormalizer instance
  695. """
  696. raise NotImplementedError(self.get_blob_normalizer)
  697. def get_gitattributes(self, tree: Optional[bytes] = None) -> "GitAttributes":
  698. """Read gitattributes for the repository.
  699. Args:
  700. tree: Tree SHA to read .gitattributes from (defaults to HEAD)
  701. Returns:
  702. GitAttributes object that can be used to match paths
  703. """
  704. raise NotImplementedError(self.get_gitattributes)
  705. def get_config_stack(self) -> "StackedConfig":
  706. """Return a config stack for this repository.
  707. This stack accesses the configuration for both this repository
  708. itself (.git/config) and the global configuration, which usually
  709. lives in ~/.gitconfig.
  710. Returns: `Config` instance for this repository
  711. """
  712. from .config import ConfigFile, StackedConfig
  713. local_config = self.get_config()
  714. backends: list[ConfigFile] = [local_config]
  715. if local_config.get_boolean((b"extensions",), b"worktreeconfig", False):
  716. backends.append(self.get_worktree_config())
  717. backends += StackedConfig.default_backends()
  718. return StackedConfig(backends, writable=local_config)
  719. def get_shallow(self) -> set[ObjectID]:
  720. """Get the set of shallow commits.
  721. Returns: Set of shallow commits.
  722. """
  723. f = self.get_named_file("shallow")
  724. if f is None:
  725. return set()
  726. with f:
  727. return {line.strip() for line in f}
  728. def update_shallow(
  729. self, new_shallow: Optional[set[bytes]], new_unshallow: Optional[set[bytes]]
  730. ) -> None:
  731. """Update the list of shallow objects.
  732. Args:
  733. new_shallow: Newly shallow objects
  734. new_unshallow: Newly no longer shallow objects
  735. """
  736. shallow = self.get_shallow()
  737. if new_shallow:
  738. shallow.update(new_shallow)
  739. if new_unshallow:
  740. shallow.difference_update(new_unshallow)
  741. if shallow:
  742. self._put_named_file("shallow", b"".join([sha + b"\n" for sha in shallow]))
  743. else:
  744. self._del_named_file("shallow")
  745. def get_peeled(self, ref: Ref) -> ObjectID:
  746. """Get the peeled value of a ref.
  747. Args:
  748. ref: The refname to peel.
  749. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  750. intermediate tags; if the original ref does not point to a tag,
  751. this will equal the original SHA1.
  752. """
  753. cached = self.refs.get_peeled(ref)
  754. if cached is not None:
  755. return cached
  756. return peel_sha(self.object_store, self.refs[ref])[1].id
  757. @property
  758. def notes(self) -> "Notes":
  759. """Access notes functionality for this repository.
  760. Returns:
  761. Notes object for accessing notes
  762. """
  763. from .notes import Notes
  764. return Notes(self.object_store, self.refs)
  765. def get_walker(
  766. self,
  767. include: Optional[list[bytes]] = None,
  768. exclude: Optional[list[bytes]] = None,
  769. order: str = "date",
  770. reverse: bool = False,
  771. max_entries: Optional[int] = None,
  772. paths: Optional[list[bytes]] = None,
  773. rename_detector: Optional["RenameDetector"] = None,
  774. follow: bool = False,
  775. since: Optional[int] = None,
  776. until: Optional[int] = None,
  777. queue_cls: Optional[type] = None,
  778. ) -> "Walker":
  779. """Obtain a walker for this repository.
  780. Args:
  781. include: Iterable of SHAs of commits to include along with their
  782. ancestors. Defaults to [HEAD]
  783. exclude: Iterable of SHAs of commits to exclude along with their
  784. ancestors, overriding includes.
  785. order: ORDER_* constant specifying the order of results.
  786. Anything other than ORDER_DATE may result in O(n) memory usage.
  787. reverse: If True, reverse the order of output, requiring O(n)
  788. memory.
  789. max_entries: The maximum number of entries to yield, or None for
  790. no limit.
  791. paths: Iterable of file or subtree paths to show entries for.
  792. rename_detector: diff.RenameDetector object for detecting
  793. renames.
  794. follow: If True, follow path across renames/copies. Forces a
  795. default rename_detector.
  796. since: Timestamp to list commits after.
  797. until: Timestamp to list commits before.
  798. queue_cls: A class to use for a queue of commits, supporting the
  799. iterator protocol. The constructor takes a single argument, the Walker.
  800. **kwargs: Additional keyword arguments
  801. Returns: A `Walker` object
  802. """
  803. from .walk import Walker, _CommitTimeQueue
  804. if include is None:
  805. include = [self.head()]
  806. # Pass all arguments to Walker explicitly to avoid type issues with **kwargs
  807. return Walker(
  808. self.object_store,
  809. include,
  810. exclude=exclude,
  811. order=order,
  812. reverse=reverse,
  813. max_entries=max_entries,
  814. paths=paths,
  815. rename_detector=rename_detector,
  816. follow=follow,
  817. since=since,
  818. until=until,
  819. get_parents=lambda commit: self.get_parents(commit.id, commit),
  820. queue_cls=queue_cls if queue_cls is not None else _CommitTimeQueue,
  821. )
  822. def __getitem__(self, name: Union[ObjectID, Ref]) -> "ShaFile":
  823. """Retrieve a Git object by SHA1 or ref.
  824. Args:
  825. name: A Git object SHA1 or a ref name
  826. Returns: A `ShaFile` object, such as a Commit or Blob
  827. Raises:
  828. KeyError: when the specified ref or object does not exist
  829. """
  830. if not isinstance(name, bytes):
  831. raise TypeError(f"'name' must be bytestring, not {type(name).__name__:.80}")
  832. if len(name) in (20, 40):
  833. try:
  834. return self.object_store[name]
  835. except (KeyError, ValueError):
  836. pass
  837. try:
  838. return self.object_store[self.refs[name]]
  839. except RefFormatError as exc:
  840. raise KeyError(name) from exc
  841. def __contains__(self, name: bytes) -> bool:
  842. """Check if a specific Git object or ref is present.
  843. Args:
  844. name: Git object SHA1 or ref name
  845. """
  846. if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)):
  847. return name in self.object_store or name in self.refs
  848. else:
  849. return name in self.refs
  850. def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]) -> None:
  851. """Set a ref.
  852. Args:
  853. name: ref name
  854. value: Ref value - either a ShaFile object, or a hex sha
  855. """
  856. if name.startswith(b"refs/") or name == b"HEAD":
  857. if isinstance(value, ShaFile):
  858. self.refs[name] = value.id
  859. elif isinstance(value, bytes):
  860. self.refs[name] = value
  861. else:
  862. raise TypeError(value)
  863. else:
  864. raise ValueError(name)
  865. def __delitem__(self, name: bytes) -> None:
  866. """Remove a ref.
  867. Args:
  868. name: Name of the ref to remove
  869. """
  870. if name.startswith(b"refs/") or name == b"HEAD":
  871. del self.refs[name]
  872. else:
  873. raise ValueError(name)
  874. def _get_user_identity(
  875. self, config: "StackedConfig", kind: Optional[str] = None
  876. ) -> bytes:
  877. """Determine the identity to use for new commits."""
  878. warnings.warn(
  879. "use get_user_identity() rather than Repo._get_user_identity",
  880. DeprecationWarning,
  881. )
  882. return get_user_identity(config)
  883. def _add_graftpoints(self, updated_graftpoints: dict[bytes, list[bytes]]) -> None:
  884. """Add or modify graftpoints.
  885. Args:
  886. updated_graftpoints: Dict of commit shas to list of parent shas
  887. """
  888. # Simple validation
  889. for commit, parents in updated_graftpoints.items():
  890. for sha in [commit, *parents]:
  891. check_hexsha(sha, "Invalid graftpoint")
  892. self._graftpoints.update(updated_graftpoints)
  893. def _remove_graftpoints(self, to_remove: list[bytes] = []) -> None:
  894. """Remove graftpoints.
  895. Args:
  896. to_remove: List of commit shas
  897. """
  898. for sha in to_remove:
  899. del self._graftpoints[sha]
  900. def _read_heads(self, name: str) -> list[bytes]:
  901. f = self.get_named_file(name)
  902. if f is None:
  903. return []
  904. with f:
  905. return [line.strip() for line in f.readlines() if line.strip()]
  906. def get_worktree(self) -> "WorkTree":
  907. """Get the working tree for this repository.
  908. Returns:
  909. WorkTree instance for performing working tree operations
  910. Raises:
  911. NotImplementedError: If the repository doesn't support working trees
  912. """
  913. raise NotImplementedError(
  914. "Working tree operations not supported by this repository type"
  915. )
  916. @replace_me(remove_in="0.26.0")
  917. def do_commit(
  918. self,
  919. message: Optional[bytes] = None,
  920. committer: Optional[bytes] = None,
  921. author: Optional[bytes] = None,
  922. commit_timestamp: Optional[float] = None,
  923. commit_timezone: Optional[int] = None,
  924. author_timestamp: Optional[float] = None,
  925. author_timezone: Optional[int] = None,
  926. tree: Optional[ObjectID] = None,
  927. encoding: Optional[bytes] = None,
  928. ref: Optional[Ref] = b"HEAD",
  929. merge_heads: Optional[list[ObjectID]] = None,
  930. no_verify: bool = False,
  931. sign: bool = False,
  932. ) -> bytes:
  933. """Create a new commit.
  934. If not specified, committer and author default to
  935. get_user_identity(..., 'COMMITTER')
  936. and get_user_identity(..., 'AUTHOR') respectively.
  937. Args:
  938. message: Commit message (bytes or callable that takes (repo, commit)
  939. and returns bytes)
  940. committer: Committer fullname
  941. author: Author fullname
  942. commit_timestamp: Commit timestamp (defaults to now)
  943. commit_timezone: Commit timestamp timezone (defaults to GMT)
  944. author_timestamp: Author timestamp (defaults to commit
  945. timestamp)
  946. author_timezone: Author timestamp timezone
  947. (defaults to commit timestamp timezone)
  948. tree: SHA1 of the tree root to use (if not specified the
  949. current index will be committed).
  950. encoding: Encoding
  951. ref: Optional ref to commit to (defaults to current branch).
  952. If None, creates a dangling commit without updating any ref.
  953. merge_heads: Merge heads (defaults to .git/MERGE_HEAD)
  954. no_verify: Skip pre-commit and commit-msg hooks
  955. sign: GPG Sign the commit (bool, defaults to False,
  956. pass True to use default GPG key,
  957. pass a str containing Key ID to use a specific GPG key)
  958. Returns:
  959. New commit SHA1
  960. """
  961. return self.get_worktree().commit(
  962. message=message,
  963. committer=committer,
  964. author=author,
  965. commit_timestamp=commit_timestamp,
  966. commit_timezone=commit_timezone,
  967. author_timestamp=author_timestamp,
  968. author_timezone=author_timezone,
  969. tree=tree,
  970. encoding=encoding,
  971. ref=ref,
  972. merge_heads=merge_heads,
  973. no_verify=no_verify,
  974. sign=sign,
  975. )
  976. def read_gitfile(f: BinaryIO) -> str:
  977. """Read a ``.git`` file.
  978. The first line of the file should start with "gitdir: "
  979. Args:
  980. f: File-like object to read from
  981. Returns: A path
  982. """
  983. cs = f.read()
  984. if not cs.startswith(b"gitdir: "):
  985. raise ValueError("Expected file to start with 'gitdir: '")
  986. return cs[len(b"gitdir: ") :].rstrip(b"\n").decode("utf-8")
  987. class UnsupportedVersion(Exception):
  988. """Unsupported repository version."""
  989. def __init__(self, version: int) -> None:
  990. """Initialize UnsupportedVersion exception.
  991. Args:
  992. version: The unsupported repository version
  993. """
  994. self.version = version
  995. class UnsupportedExtension(Exception):
  996. """Unsupported repository extension."""
  997. def __init__(self, extension: str) -> None:
  998. """Initialize UnsupportedExtension exception.
  999. Args:
  1000. extension: The unsupported repository extension
  1001. """
  1002. self.extension = extension
  1003. class Repo(BaseRepo):
  1004. """A git repository backed by local disk.
  1005. To open an existing repository, call the constructor with
  1006. the path of the repository.
  1007. To create a new repository, use the Repo.init class method.
  1008. Note that a repository object may hold on to resources such
  1009. as file handles for performance reasons; call .close() to free
  1010. up those resources.
  1011. Attributes:
  1012. path: Path to the working copy (if it exists) or repository control
  1013. directory (if the repository is bare)
  1014. bare: Whether this is a bare repository
  1015. """
  1016. path: str
  1017. bare: bool
  1018. object_store: DiskObjectStore
  1019. filter_context: Optional["FilterContext"]
  1020. def __init__(
  1021. self,
  1022. root: Union[str, bytes, os.PathLike[str]],
  1023. object_store: Optional[PackBasedObjectStore] = None,
  1024. bare: Optional[bool] = None,
  1025. ) -> None:
  1026. """Open a repository on disk.
  1027. Args:
  1028. root: Path to the repository's root.
  1029. object_store: ObjectStore to use; if omitted, we use the
  1030. repository's default object store
  1031. bare: True if this is a bare repository.
  1032. """
  1033. root = os.fspath(root)
  1034. if isinstance(root, bytes):
  1035. root = os.fsdecode(root)
  1036. hidden_path = os.path.join(root, CONTROLDIR)
  1037. if bare is None:
  1038. if os.path.isfile(hidden_path) or os.path.isdir(
  1039. os.path.join(hidden_path, OBJECTDIR)
  1040. ):
  1041. bare = False
  1042. elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir(
  1043. os.path.join(root, REFSDIR)
  1044. ):
  1045. bare = True
  1046. else:
  1047. raise NotGitRepository(
  1048. "No git repository was found at {path}".format(**dict(path=root))
  1049. )
  1050. self.bare = bare
  1051. if bare is False:
  1052. if os.path.isfile(hidden_path):
  1053. with open(hidden_path, "rb") as f:
  1054. path = read_gitfile(f)
  1055. self._controldir = os.path.join(root, path)
  1056. else:
  1057. self._controldir = hidden_path
  1058. else:
  1059. self._controldir = root
  1060. commondir = self.get_named_file(COMMONDIR)
  1061. if commondir is not None:
  1062. with commondir:
  1063. self._commondir = os.path.join(
  1064. self.controldir(),
  1065. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  1066. )
  1067. else:
  1068. self._commondir = self._controldir
  1069. self.path = root
  1070. # Initialize refs early so they're available for config condition matchers
  1071. self.refs = DiskRefsContainer(
  1072. self.commondir(), self._controldir, logger=self._write_reflog
  1073. )
  1074. # Initialize worktrees container
  1075. from .worktree import WorkTreeContainer
  1076. self.worktrees = WorkTreeContainer(self)
  1077. config = self.get_config()
  1078. try:
  1079. repository_format_version = config.get("core", "repositoryformatversion")
  1080. format_version = (
  1081. 0
  1082. if repository_format_version is None
  1083. else int(repository_format_version)
  1084. )
  1085. except KeyError:
  1086. format_version = 0
  1087. if format_version not in (0, 1):
  1088. raise UnsupportedVersion(format_version)
  1089. # Track extensions we encounter
  1090. has_reftable_extension = False
  1091. for extension, value in config.items((b"extensions",)):
  1092. if extension.lower() == b"refstorage":
  1093. if value == b"reftable":
  1094. has_reftable_extension = True
  1095. else:
  1096. raise UnsupportedExtension(f"refStorage = {value.decode()}")
  1097. elif extension.lower() not in (b"worktreeconfig",):
  1098. raise UnsupportedExtension(extension.decode("utf-8"))
  1099. if object_store is None:
  1100. object_store = DiskObjectStore.from_config(
  1101. os.path.join(self.commondir(), OBJECTDIR), config
  1102. )
  1103. # Use reftable if extension is configured
  1104. if has_reftable_extension:
  1105. from .reftable import ReftableRefsContainer
  1106. self.refs = ReftableRefsContainer(self.commondir())
  1107. # Update worktrees container after refs change
  1108. self.worktrees = WorkTreeContainer(self)
  1109. BaseRepo.__init__(self, object_store, self.refs)
  1110. self._graftpoints = {}
  1111. graft_file = self.get_named_file(
  1112. os.path.join("info", "grafts"), basedir=self.commondir()
  1113. )
  1114. if graft_file:
  1115. with graft_file:
  1116. self._graftpoints.update(parse_graftpoints(graft_file))
  1117. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  1118. if graft_file:
  1119. with graft_file:
  1120. self._graftpoints.update(parse_graftpoints(graft_file))
  1121. self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir())
  1122. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  1123. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  1124. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  1125. # Initialize filter context as None, will be created lazily
  1126. self.filter_context = None
  1127. def get_worktree(self) -> "WorkTree":
  1128. """Get the working tree for this repository.
  1129. Returns:
  1130. WorkTree instance for performing working tree operations
  1131. """
  1132. from .worktree import WorkTree
  1133. return WorkTree(self, self.path)
  1134. def _write_reflog(
  1135. self,
  1136. ref: bytes,
  1137. old_sha: bytes,
  1138. new_sha: bytes,
  1139. committer: Optional[bytes],
  1140. timestamp: Optional[int],
  1141. timezone: Optional[int],
  1142. message: bytes,
  1143. ) -> None:
  1144. from .reflog import format_reflog_line
  1145. path = self._reflog_path(ref)
  1146. try:
  1147. os.makedirs(os.path.dirname(path))
  1148. except FileExistsError:
  1149. pass
  1150. if committer is None:
  1151. config = self.get_config_stack()
  1152. committer = get_user_identity(config)
  1153. check_user_identity(committer)
  1154. if timestamp is None:
  1155. timestamp = int(time.time())
  1156. if timezone is None:
  1157. timezone = 0 # FIXME
  1158. with open(path, "ab") as f:
  1159. f.write(
  1160. format_reflog_line(
  1161. old_sha, new_sha, committer, timestamp, timezone, message
  1162. )
  1163. + b"\n"
  1164. )
  1165. def _reflog_path(self, ref: bytes) -> str:
  1166. if ref.startswith((b"main-worktree/", b"worktrees/")):
  1167. raise NotImplementedError(f"refs {ref.decode()} are not supported")
  1168. base = self.controldir() if is_per_worktree_ref(ref) else self.commondir()
  1169. return os.path.join(base, "logs", os.fsdecode(ref))
  1170. def read_reflog(self, ref: bytes) -> Generator[reflog.Entry, None, None]:
  1171. """Read reflog entries for a reference.
  1172. Args:
  1173. ref: Reference name (e.g. b'HEAD', b'refs/heads/master')
  1174. Yields:
  1175. reflog.Entry objects in chronological order (oldest first)
  1176. """
  1177. from .reflog import read_reflog
  1178. path = self._reflog_path(ref)
  1179. try:
  1180. with open(path, "rb") as f:
  1181. yield from read_reflog(f)
  1182. except FileNotFoundError:
  1183. return
  1184. @classmethod
  1185. def discover(cls, start: Union[str, bytes, os.PathLike[str]] = ".") -> "Repo":
  1186. """Iterate parent directories to discover a repository.
  1187. Return a Repo object for the first parent directory that looks like a
  1188. Git repository.
  1189. Args:
  1190. start: The directory to start discovery from (defaults to '.')
  1191. """
  1192. path = os.path.abspath(start)
  1193. while True:
  1194. try:
  1195. return cls(path)
  1196. except NotGitRepository:
  1197. new_path, _tail = os.path.split(path)
  1198. if new_path == path: # Root reached
  1199. break
  1200. path = new_path
  1201. start_str = os.fspath(start)
  1202. if isinstance(start_str, bytes):
  1203. start_str = start_str.decode("utf-8")
  1204. raise NotGitRepository(f"No git repository was found at {start_str}")
  1205. def controldir(self) -> str:
  1206. """Return the path of the control directory."""
  1207. return self._controldir
  1208. def commondir(self) -> str:
  1209. """Return the path of the common directory.
  1210. For a main working tree, it is identical to controldir().
  1211. For a linked working tree, it is the control directory of the
  1212. main working tree.
  1213. """
  1214. return self._commondir
  1215. def _determine_file_mode(self) -> bool:
  1216. """Probe the file-system to determine whether permissions can be trusted.
  1217. Returns: True if permissions can be trusted, False otherwise.
  1218. """
  1219. fname = os.path.join(self.path, ".probe-permissions")
  1220. with open(fname, "w") as f:
  1221. f.write("")
  1222. st1 = os.lstat(fname)
  1223. try:
  1224. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  1225. except PermissionError:
  1226. return False
  1227. st2 = os.lstat(fname)
  1228. os.unlink(fname)
  1229. mode_differs = st1.st_mode != st2.st_mode
  1230. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1231. return mode_differs and st2_has_exec
  1232. def _determine_symlinks(self) -> bool:
  1233. """Probe the filesystem to determine whether symlinks can be created.
  1234. Returns: True if symlinks can be created, False otherwise.
  1235. """
  1236. # TODO(jelmer): Actually probe disk / look at filesystem
  1237. return sys.platform != "win32"
  1238. def _put_named_file(self, path: str, contents: bytes) -> None:
  1239. """Write a file to the control dir with the given name and contents.
  1240. Args:
  1241. path: The path to the file, relative to the control dir.
  1242. contents: A string to write to the file.
  1243. """
  1244. path = path.lstrip(os.path.sep)
  1245. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1246. f.write(contents)
  1247. def _del_named_file(self, path: str) -> None:
  1248. try:
  1249. os.unlink(os.path.join(self.controldir(), path))
  1250. except FileNotFoundError:
  1251. return
  1252. def get_named_file(
  1253. self,
  1254. path: Union[str, bytes],
  1255. basedir: Optional[str] = None,
  1256. ) -> Optional[BinaryIO]:
  1257. """Get a file from the control dir with a specific name.
  1258. Although the filename should be interpreted as a filename relative to
  1259. the control dir in a disk-based Repo, the object returned need not be
  1260. pointing to a file in that location.
  1261. Args:
  1262. path: The path to the file, relative to the control dir.
  1263. basedir: Optional argument that specifies an alternative to the
  1264. control dir.
  1265. Returns: An open file object, or None if the file does not exist.
  1266. """
  1267. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1268. # the dumb web serving code.
  1269. if basedir is None:
  1270. basedir = self.controldir()
  1271. if isinstance(path, bytes):
  1272. path = path.decode("utf-8")
  1273. path = path.lstrip(os.path.sep)
  1274. try:
  1275. return open(os.path.join(basedir, path), "rb")
  1276. except FileNotFoundError:
  1277. return None
  1278. def index_path(self) -> str:
  1279. """Return path to the index file."""
  1280. return os.path.join(self.controldir(), INDEX_FILENAME)
  1281. def open_index(self) -> "Index":
  1282. """Open the index for this repository.
  1283. Raises:
  1284. NoIndexPresent: If no index is present
  1285. Returns: The matching `Index`
  1286. """
  1287. from .index import Index
  1288. if not self.has_index():
  1289. raise NoIndexPresent
  1290. # Check for manyFiles feature configuration
  1291. config = self.get_config_stack()
  1292. many_files = config.get_boolean(b"feature", b"manyFiles", False)
  1293. skip_hash = False
  1294. index_version = None
  1295. if many_files:
  1296. # When feature.manyFiles is enabled, set index.version=4 and index.skipHash=true
  1297. try:
  1298. index_version_str = config.get(b"index", b"version")
  1299. index_version = int(index_version_str)
  1300. except KeyError:
  1301. index_version = 4 # Default to version 4 for manyFiles
  1302. skip_hash = config.get_boolean(b"index", b"skipHash", True)
  1303. else:
  1304. # Check for explicit index settings
  1305. try:
  1306. index_version_str = config.get(b"index", b"version")
  1307. index_version = int(index_version_str)
  1308. except KeyError:
  1309. index_version = None
  1310. skip_hash = config.get_boolean(b"index", b"skipHash", False)
  1311. return Index(self.index_path(), skip_hash=skip_hash, version=index_version)
  1312. def has_index(self) -> bool:
  1313. """Check if an index is present."""
  1314. # Bare repos must never have index files; non-bare repos may have a
  1315. # missing index file, which is treated as empty.
  1316. return not self.bare
  1317. @replace_me(remove_in="0.26.0")
  1318. def stage(
  1319. self,
  1320. fs_paths: Union[
  1321. str, bytes, os.PathLike[str], Iterable[Union[str, bytes, os.PathLike[str]]]
  1322. ],
  1323. ) -> None:
  1324. """Stage a set of paths.
  1325. Args:
  1326. fs_paths: List of paths, relative to the repository path
  1327. """
  1328. return self.get_worktree().stage(fs_paths)
  1329. @replace_me(remove_in="0.26.0")
  1330. def unstage(self, fs_paths: list[str]) -> None:
  1331. """Unstage specific file in the index.
  1332. Args:
  1333. fs_paths: a list of files to unstage,
  1334. relative to the repository path.
  1335. """
  1336. return self.get_worktree().unstage(fs_paths)
  1337. def clone(
  1338. self,
  1339. target_path: Union[str, bytes, os.PathLike[str]],
  1340. *,
  1341. mkdir: bool = True,
  1342. bare: bool = False,
  1343. origin: bytes = b"origin",
  1344. checkout: Optional[bool] = None,
  1345. branch: Optional[bytes] = None,
  1346. progress: Optional[Callable[[str], None]] = None,
  1347. depth: Optional[int] = None,
  1348. symlinks: Optional[bool] = None,
  1349. ) -> "Repo":
  1350. """Clone this repository.
  1351. Args:
  1352. target_path: Target path
  1353. mkdir: Create the target directory
  1354. bare: Whether to create a bare repository
  1355. checkout: Whether or not to check-out HEAD after cloning
  1356. origin: Base name for refs in target repository
  1357. cloned from this repository
  1358. branch: Optional branch or tag to be used as HEAD in the new repository
  1359. instead of this repository's HEAD.
  1360. progress: Optional progress function
  1361. depth: Depth at which to fetch
  1362. symlinks: Symlinks setting (default to autodetect)
  1363. Returns: Created repository as `Repo`
  1364. """
  1365. encoded_path = os.fsencode(self.path)
  1366. if mkdir:
  1367. os.mkdir(target_path)
  1368. try:
  1369. if not bare:
  1370. target = Repo.init(target_path, symlinks=symlinks)
  1371. if checkout is None:
  1372. checkout = True
  1373. else:
  1374. if checkout:
  1375. raise ValueError("checkout and bare are incompatible")
  1376. target = Repo.init_bare(target_path)
  1377. try:
  1378. target_config = target.get_config()
  1379. target_config.set((b"remote", origin), b"url", encoded_path)
  1380. target_config.set(
  1381. (b"remote", origin),
  1382. b"fetch",
  1383. b"+refs/heads/*:refs/remotes/" + origin + b"/*",
  1384. )
  1385. target_config.write_to_path()
  1386. ref_message = b"clone: from " + encoded_path
  1387. self.fetch(target, depth=depth)
  1388. target.refs.import_refs(
  1389. b"refs/remotes/" + origin,
  1390. self.refs.as_dict(b"refs/heads"),
  1391. message=ref_message,
  1392. )
  1393. target.refs.import_refs(
  1394. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1395. )
  1396. head_chain, origin_sha = self.refs.follow(b"HEAD")
  1397. origin_head = head_chain[-1] if head_chain else None
  1398. if origin_sha and not origin_head:
  1399. # set detached HEAD
  1400. target.refs[b"HEAD"] = origin_sha
  1401. else:
  1402. _set_origin_head(target.refs, origin, origin_head)
  1403. head_ref = _set_default_branch(
  1404. target.refs, origin, origin_head, branch, ref_message
  1405. )
  1406. # Update target head
  1407. if head_ref:
  1408. head = _set_head(target.refs, head_ref, ref_message)
  1409. else:
  1410. head = None
  1411. if checkout and head is not None:
  1412. target.get_worktree().reset_index()
  1413. except BaseException:
  1414. target.close()
  1415. raise
  1416. except BaseException:
  1417. if mkdir:
  1418. import shutil
  1419. shutil.rmtree(target_path)
  1420. raise
  1421. return target
  1422. @replace_me(remove_in="0.26.0")
  1423. def reset_index(self, tree: Optional[bytes] = None) -> None:
  1424. """Reset the index back to a specific tree.
  1425. Args:
  1426. tree: Tree SHA to reset to, None for current HEAD tree.
  1427. """
  1428. return self.get_worktree().reset_index(tree)
  1429. def _get_config_condition_matchers(self) -> dict[str, "ConditionMatcher"]:
  1430. """Get condition matchers for includeIf conditions.
  1431. Returns a dict of condition prefix to matcher function.
  1432. """
  1433. from pathlib import Path
  1434. from .config import ConditionMatcher, match_glob_pattern
  1435. # Add gitdir matchers
  1436. def match_gitdir(pattern: str, case_sensitive: bool = True) -> bool:
  1437. """Match gitdir against a pattern.
  1438. Args:
  1439. pattern: Pattern to match against
  1440. case_sensitive: Whether to match case-sensitively
  1441. Returns:
  1442. True if gitdir matches pattern
  1443. """
  1444. # Handle relative patterns (starting with ./)
  1445. if pattern.startswith("./"):
  1446. # Can't handle relative patterns without config directory context
  1447. return False
  1448. # Normalize repository path
  1449. try:
  1450. repo_path = str(Path(self._controldir).resolve())
  1451. except (OSError, ValueError):
  1452. return False
  1453. # Expand ~ in pattern and normalize
  1454. pattern = os.path.expanduser(pattern)
  1455. # Normalize pattern following Git's rules
  1456. pattern = pattern.replace("\\", "/")
  1457. if not pattern.startswith(("~/", "./", "/", "**")):
  1458. # Check for Windows absolute path
  1459. if len(pattern) >= 2 and pattern[1] == ":":
  1460. pass
  1461. else:
  1462. pattern = "**/" + pattern
  1463. if pattern.endswith("/"):
  1464. pattern = pattern + "**"
  1465. # Use the existing _match_gitdir_pattern function
  1466. from .config import _match_gitdir_pattern
  1467. pattern_bytes = pattern.encode("utf-8", errors="replace")
  1468. repo_path_bytes = repo_path.encode("utf-8", errors="replace")
  1469. return _match_gitdir_pattern(
  1470. repo_path_bytes, pattern_bytes, ignorecase=not case_sensitive
  1471. )
  1472. # Add onbranch matcher
  1473. def match_onbranch(pattern: str) -> bool:
  1474. """Match current branch against a pattern.
  1475. Args:
  1476. pattern: Pattern to match against
  1477. Returns:
  1478. True if current branch matches pattern
  1479. """
  1480. try:
  1481. # Get the current branch using refs
  1482. ref_chain, _ = self.refs.follow(b"HEAD")
  1483. head_ref = ref_chain[-1] # Get the final resolved ref
  1484. except KeyError:
  1485. pass
  1486. else:
  1487. if head_ref and head_ref.startswith(b"refs/heads/"):
  1488. # Extract branch name from ref
  1489. branch = head_ref[11:].decode("utf-8", errors="replace")
  1490. return match_glob_pattern(branch, pattern)
  1491. return False
  1492. matchers: dict[str, ConditionMatcher] = {
  1493. "onbranch:": match_onbranch,
  1494. "gitdir:": lambda pattern: match_gitdir(pattern, True),
  1495. "gitdir/i:": lambda pattern: match_gitdir(pattern, False),
  1496. }
  1497. return matchers
  1498. def get_worktree_config(self) -> "ConfigFile":
  1499. """Get the worktree-specific config.
  1500. Returns:
  1501. ConfigFile object for the worktree config
  1502. """
  1503. from .config import ConfigFile
  1504. path = os.path.join(self.commondir(), "config.worktree")
  1505. try:
  1506. # Pass condition matchers for includeIf evaluation
  1507. condition_matchers = self._get_config_condition_matchers()
  1508. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1509. except FileNotFoundError:
  1510. cf = ConfigFile()
  1511. cf.path = path
  1512. return cf
  1513. def get_config(self) -> "ConfigFile":
  1514. """Retrieve the config object.
  1515. Returns: `ConfigFile` object for the ``.git/config`` file.
  1516. """
  1517. from .config import ConfigFile
  1518. path = os.path.join(self._commondir, "config")
  1519. try:
  1520. # Pass condition matchers for includeIf evaluation
  1521. condition_matchers = self._get_config_condition_matchers()
  1522. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1523. except FileNotFoundError:
  1524. ret = ConfigFile()
  1525. ret.path = path
  1526. return ret
  1527. def get_rebase_state_manager(self) -> "RebaseStateManager":
  1528. """Get the appropriate rebase state manager for this repository.
  1529. Returns: DiskRebaseStateManager instance
  1530. """
  1531. import os
  1532. from .rebase import DiskRebaseStateManager
  1533. path = os.path.join(self.controldir(), "rebase-merge")
  1534. return DiskRebaseStateManager(path)
  1535. def get_description(self) -> Optional[bytes]:
  1536. """Retrieve the description of this repository.
  1537. Returns: Description as bytes or None.
  1538. """
  1539. path = os.path.join(self._controldir, "description")
  1540. try:
  1541. with GitFile(path, "rb") as f:
  1542. return f.read()
  1543. except FileNotFoundError:
  1544. return None
  1545. def __repr__(self) -> str:
  1546. """Return string representation of this repository."""
  1547. return f"<Repo at {self.path!r}>"
  1548. def set_description(self, description: bytes) -> None:
  1549. """Set the description for this repository.
  1550. Args:
  1551. description: Text to set as description for this repository.
  1552. """
  1553. self._put_named_file("description", description)
  1554. @classmethod
  1555. def _init_maybe_bare(
  1556. cls,
  1557. path: Union[str, bytes, os.PathLike[str]],
  1558. controldir: Union[str, bytes, os.PathLike[str]],
  1559. bare: bool,
  1560. object_store: Optional[PackBasedObjectStore] = None,
  1561. config: Optional["StackedConfig"] = None,
  1562. default_branch: Optional[bytes] = None,
  1563. symlinks: Optional[bool] = None,
  1564. format: Optional[int] = None,
  1565. ) -> "Repo":
  1566. path = os.fspath(path)
  1567. if isinstance(path, bytes):
  1568. path = os.fsdecode(path)
  1569. controldir = os.fspath(controldir)
  1570. if isinstance(controldir, bytes):
  1571. controldir = os.fsdecode(controldir)
  1572. for d in BASE_DIRECTORIES:
  1573. os.mkdir(os.path.join(controldir, *d))
  1574. if object_store is None:
  1575. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1576. ret = cls(path, bare=bare, object_store=object_store)
  1577. if default_branch is None:
  1578. if config is None:
  1579. from .config import StackedConfig
  1580. config = StackedConfig.default()
  1581. try:
  1582. default_branch = config.get("init", "defaultBranch")
  1583. except KeyError:
  1584. default_branch = DEFAULT_BRANCH
  1585. ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch)
  1586. ret._init_files(bare=bare, symlinks=symlinks, format=format)
  1587. return ret
  1588. @classmethod
  1589. def init(
  1590. cls,
  1591. path: Union[str, bytes, os.PathLike[str]],
  1592. *,
  1593. mkdir: bool = False,
  1594. config: Optional["StackedConfig"] = None,
  1595. default_branch: Optional[bytes] = None,
  1596. symlinks: Optional[bool] = None,
  1597. format: Optional[int] = None,
  1598. ) -> "Repo":
  1599. """Create a new repository.
  1600. Args:
  1601. path: Path in which to create the repository
  1602. mkdir: Whether to create the directory
  1603. config: Configuration object
  1604. default_branch: Default branch name
  1605. symlinks: Whether to support symlinks
  1606. format: Repository format version (defaults to 0)
  1607. Returns: `Repo` instance
  1608. """
  1609. path = os.fspath(path)
  1610. if isinstance(path, bytes):
  1611. path = os.fsdecode(path)
  1612. if mkdir:
  1613. os.mkdir(path)
  1614. controldir = os.path.join(path, CONTROLDIR)
  1615. os.mkdir(controldir)
  1616. _set_filesystem_hidden(controldir)
  1617. return cls._init_maybe_bare(
  1618. path,
  1619. controldir,
  1620. False,
  1621. config=config,
  1622. default_branch=default_branch,
  1623. symlinks=symlinks,
  1624. format=format,
  1625. )
  1626. @classmethod
  1627. def _init_new_working_directory(
  1628. cls,
  1629. path: Union[str, bytes, os.PathLike[str]],
  1630. main_repo: "Repo",
  1631. identifier: Optional[str] = None,
  1632. mkdir: bool = False,
  1633. ) -> "Repo":
  1634. """Create a new working directory linked to a repository.
  1635. Args:
  1636. path: Path in which to create the working tree.
  1637. main_repo: Main repository to reference
  1638. identifier: Worktree identifier
  1639. mkdir: Whether to create the directory
  1640. Returns: `Repo` instance
  1641. """
  1642. path = os.fspath(path)
  1643. if isinstance(path, bytes):
  1644. path = os.fsdecode(path)
  1645. if mkdir:
  1646. os.mkdir(path)
  1647. if identifier is None:
  1648. identifier = os.path.basename(path)
  1649. # Ensure we use absolute path for the worktree control directory
  1650. main_controldir = os.path.abspath(main_repo.controldir())
  1651. main_worktreesdir = os.path.join(main_controldir, WORKTREES)
  1652. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1653. gitdirfile = os.path.join(path, CONTROLDIR)
  1654. with open(gitdirfile, "wb") as f:
  1655. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1656. try:
  1657. os.mkdir(main_worktreesdir)
  1658. except FileExistsError:
  1659. pass
  1660. try:
  1661. os.mkdir(worktree_controldir)
  1662. except FileExistsError:
  1663. pass
  1664. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1665. f.write(os.fsencode(gitdirfile) + b"\n")
  1666. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1667. f.write(b"../..\n")
  1668. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1669. f.write(main_repo.head() + b"\n")
  1670. r = cls(os.path.normpath(path))
  1671. r.get_worktree().reset_index()
  1672. return r
  1673. @classmethod
  1674. def init_bare(
  1675. cls,
  1676. path: Union[str, bytes, os.PathLike[str]],
  1677. *,
  1678. mkdir: bool = False,
  1679. object_store: Optional[PackBasedObjectStore] = None,
  1680. config: Optional["StackedConfig"] = None,
  1681. default_branch: Optional[bytes] = None,
  1682. format: Optional[int] = None,
  1683. ) -> "Repo":
  1684. """Create a new bare repository.
  1685. ``path`` should already exist and be an empty directory.
  1686. Args:
  1687. path: Path to create bare repository in
  1688. mkdir: Whether to create the directory
  1689. object_store: Object store to use
  1690. config: Configuration object
  1691. default_branch: Default branch name
  1692. format: Repository format version (defaults to 0)
  1693. Returns: a `Repo` instance
  1694. """
  1695. path = os.fspath(path)
  1696. if isinstance(path, bytes):
  1697. path = os.fsdecode(path)
  1698. if mkdir:
  1699. os.mkdir(path)
  1700. return cls._init_maybe_bare(
  1701. path,
  1702. path,
  1703. True,
  1704. object_store=object_store,
  1705. config=config,
  1706. default_branch=default_branch,
  1707. format=format,
  1708. )
  1709. create = init_bare
  1710. def close(self) -> None:
  1711. """Close any files opened by this repository."""
  1712. self.object_store.close()
  1713. # Clean up filter context if it was created
  1714. if self.filter_context is not None:
  1715. self.filter_context.close()
  1716. self.filter_context = None
  1717. def __enter__(self) -> "Repo":
  1718. """Enter context manager."""
  1719. return self
  1720. def __exit__(
  1721. self,
  1722. exc_type: Optional[type[BaseException]],
  1723. exc_val: Optional[BaseException],
  1724. exc_tb: Optional[TracebackType],
  1725. ) -> None:
  1726. """Exit context manager and close repository."""
  1727. self.close()
  1728. def _read_gitattributes(self) -> dict[bytes, dict[bytes, bytes]]:
  1729. """Read .gitattributes file from working tree.
  1730. Returns:
  1731. Dictionary mapping file patterns to attributes
  1732. """
  1733. gitattributes = {}
  1734. gitattributes_path = os.path.join(self.path, ".gitattributes")
  1735. if os.path.exists(gitattributes_path):
  1736. with open(gitattributes_path, "rb") as f:
  1737. for line in f:
  1738. line = line.strip()
  1739. if not line or line.startswith(b"#"):
  1740. continue
  1741. parts = line.split()
  1742. if len(parts) < 2:
  1743. continue
  1744. pattern = parts[0]
  1745. attrs = {}
  1746. for attr in parts[1:]:
  1747. if attr.startswith(b"-"):
  1748. # Unset attribute
  1749. attrs[attr[1:]] = b"false"
  1750. elif b"=" in attr:
  1751. # Set to value
  1752. key, value = attr.split(b"=", 1)
  1753. attrs[key] = value
  1754. else:
  1755. # Set attribute
  1756. attrs[attr] = b"true"
  1757. gitattributes[pattern] = attrs
  1758. return gitattributes
  1759. def get_blob_normalizer(self) -> "FilterBlobNormalizer":
  1760. """Return a BlobNormalizer object."""
  1761. from .filters import FilterBlobNormalizer, FilterContext, FilterRegistry
  1762. # Get fresh configuration and GitAttributes
  1763. config_stack = self.get_config_stack()
  1764. git_attributes = self.get_gitattributes()
  1765. # Lazily create FilterContext if needed
  1766. if self.filter_context is None:
  1767. filter_registry = FilterRegistry(config_stack, self)
  1768. self.filter_context = FilterContext(filter_registry)
  1769. else:
  1770. # Refresh the context with current config to handle config changes
  1771. self.filter_context.refresh_config(config_stack)
  1772. # Return a new FilterBlobNormalizer with the context
  1773. return FilterBlobNormalizer(
  1774. config_stack, git_attributes, filter_context=self.filter_context
  1775. )
  1776. def get_gitattributes(self, tree: Optional[bytes] = None) -> "GitAttributes":
  1777. """Read gitattributes for the repository.
  1778. Args:
  1779. tree: Tree SHA to read .gitattributes from (defaults to HEAD)
  1780. Returns:
  1781. GitAttributes object that can be used to match paths
  1782. """
  1783. from .attrs import (
  1784. GitAttributes,
  1785. Pattern,
  1786. parse_git_attributes,
  1787. )
  1788. patterns = []
  1789. # Read system gitattributes (TODO: implement this)
  1790. # Read global gitattributes (TODO: implement this)
  1791. # Read repository .gitattributes from index/tree
  1792. if tree is None:
  1793. try:
  1794. # Try to get from HEAD
  1795. head = self[b"HEAD"]
  1796. if isinstance(head, Tag):
  1797. _cls, obj = head.object
  1798. head = self.get_object(obj)
  1799. assert isinstance(head, Commit)
  1800. tree = head.tree
  1801. except KeyError:
  1802. # No HEAD, no attributes from tree
  1803. pass
  1804. if tree is not None:
  1805. try:
  1806. tree_obj = self[tree]
  1807. assert isinstance(tree_obj, Tree)
  1808. if b".gitattributes" in tree_obj:
  1809. _, attrs_sha = tree_obj[b".gitattributes"]
  1810. attrs_blob = self[attrs_sha]
  1811. if isinstance(attrs_blob, Blob):
  1812. attrs_data = BytesIO(attrs_blob.data)
  1813. for pattern_bytes, attrs in parse_git_attributes(attrs_data):
  1814. pattern = Pattern(pattern_bytes)
  1815. patterns.append((pattern, attrs))
  1816. except (KeyError, NotTreeError):
  1817. pass
  1818. # Read .git/info/attributes
  1819. info_attrs_path = os.path.join(self.controldir(), "info", "attributes")
  1820. if os.path.exists(info_attrs_path):
  1821. with open(info_attrs_path, "rb") as f:
  1822. for pattern_bytes, attrs in parse_git_attributes(f):
  1823. pattern = Pattern(pattern_bytes)
  1824. patterns.append((pattern, attrs))
  1825. # Read .gitattributes from working directory (if it exists)
  1826. working_attrs_path = os.path.join(self.path, ".gitattributes")
  1827. if os.path.exists(working_attrs_path):
  1828. with open(working_attrs_path, "rb") as f:
  1829. for pattern_bytes, attrs in parse_git_attributes(f):
  1830. pattern = Pattern(pattern_bytes)
  1831. patterns.append((pattern, attrs))
  1832. return GitAttributes(patterns)
  1833. @replace_me(remove_in="0.26.0")
  1834. def _sparse_checkout_file_path(self) -> str:
  1835. """Return the path of the sparse-checkout file in this repo's control dir."""
  1836. return self.get_worktree()._sparse_checkout_file_path()
  1837. @replace_me(remove_in="0.26.0")
  1838. def configure_for_cone_mode(self) -> None:
  1839. """Ensure the repository is configured for cone-mode sparse-checkout."""
  1840. return self.get_worktree().configure_for_cone_mode()
  1841. @replace_me(remove_in="0.26.0")
  1842. def infer_cone_mode(self) -> bool:
  1843. """Return True if 'core.sparseCheckoutCone' is set to 'true' in config, else False."""
  1844. return self.get_worktree().infer_cone_mode()
  1845. @replace_me(remove_in="0.26.0")
  1846. def get_sparse_checkout_patterns(self) -> list[str]:
  1847. """Return a list of sparse-checkout patterns from info/sparse-checkout.
  1848. Returns:
  1849. A list of patterns. Returns an empty list if the file is missing.
  1850. """
  1851. return self.get_worktree().get_sparse_checkout_patterns()
  1852. @replace_me(remove_in="0.26.0")
  1853. def set_sparse_checkout_patterns(self, patterns: list[str]) -> None:
  1854. """Write the given sparse-checkout patterns into info/sparse-checkout.
  1855. Creates the info/ directory if it does not exist.
  1856. Args:
  1857. patterns: A list of gitignore-style patterns to store.
  1858. """
  1859. return self.get_worktree().set_sparse_checkout_patterns(patterns)
  1860. @replace_me(remove_in="0.26.0")
  1861. def set_cone_mode_patterns(self, dirs: Union[list[str], None] = None) -> None:
  1862. """Write the given cone-mode directory patterns into info/sparse-checkout.
  1863. For each directory to include, add an inclusion line that "undoes" the prior
  1864. ``!/*/`` 'exclude' that re-includes that directory and everything under it.
  1865. Never add the same line twice.
  1866. """
  1867. return self.get_worktree().set_cone_mode_patterns(dirs)
  1868. class MemoryRepo(BaseRepo):
  1869. """Repo that stores refs, objects, and named files in memory.
  1870. MemoryRepos are always bare: they have no working tree and no index, since
  1871. those have a stronger dependency on the filesystem.
  1872. """
  1873. filter_context: Optional["FilterContext"]
  1874. def __init__(self) -> None:
  1875. """Create a new repository in memory."""
  1876. from .config import ConfigFile
  1877. self._reflog: list[Any] = []
  1878. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1879. BaseRepo.__init__(self, MemoryObjectStore(), refs_container) # type: ignore[arg-type]
  1880. self._named_files: dict[str, bytes] = {}
  1881. self.bare = True
  1882. self._config = ConfigFile()
  1883. self._description: Optional[bytes] = None
  1884. self.filter_context = None
  1885. def _append_reflog(
  1886. self,
  1887. ref: bytes,
  1888. old_sha: Optional[bytes],
  1889. new_sha: Optional[bytes],
  1890. committer: Optional[bytes],
  1891. timestamp: Optional[int],
  1892. timezone: Optional[int],
  1893. message: Optional[bytes],
  1894. ) -> None:
  1895. self._reflog.append(
  1896. (ref, old_sha, new_sha, committer, timestamp, timezone, message)
  1897. )
  1898. def set_description(self, description: bytes) -> None:
  1899. """Set the description for this repository.
  1900. Args:
  1901. description: Text to set as description
  1902. """
  1903. self._description = description
  1904. def get_description(self) -> Optional[bytes]:
  1905. """Get the description of this repository.
  1906. Returns:
  1907. Repository description as bytes
  1908. """
  1909. return self._description
  1910. def _determine_file_mode(self) -> bool:
  1911. """Probe the file-system to determine whether permissions can be trusted.
  1912. Returns: True if permissions can be trusted, False otherwise.
  1913. """
  1914. return sys.platform != "win32"
  1915. def _determine_symlinks(self) -> bool:
  1916. """Probe the file-system to determine whether permissions can be trusted.
  1917. Returns: True if permissions can be trusted, False otherwise.
  1918. """
  1919. return sys.platform != "win32"
  1920. def _put_named_file(self, path: str, contents: bytes) -> None:
  1921. """Write a file to the control dir with the given name and contents.
  1922. Args:
  1923. path: The path to the file, relative to the control dir.
  1924. contents: A string to write to the file.
  1925. """
  1926. self._named_files[path] = contents
  1927. def _del_named_file(self, path: str) -> None:
  1928. try:
  1929. del self._named_files[path]
  1930. except KeyError:
  1931. pass
  1932. def get_named_file(
  1933. self,
  1934. path: Union[str, bytes],
  1935. basedir: Optional[str] = None,
  1936. ) -> Optional[BytesIO]:
  1937. """Get a file from the control dir with a specific name.
  1938. Although the filename should be interpreted as a filename relative to
  1939. the control dir in a disk-baked Repo, the object returned need not be
  1940. pointing to a file in that location.
  1941. Args:
  1942. path: The path to the file, relative to the control dir.
  1943. basedir: Optional base directory for the path
  1944. Returns: An open file object, or None if the file does not exist.
  1945. """
  1946. path_str = path.decode() if isinstance(path, bytes) else path
  1947. contents = self._named_files.get(path_str, None)
  1948. if contents is None:
  1949. return None
  1950. return BytesIO(contents)
  1951. def open_index(self) -> "Index":
  1952. """Fail to open index for this repo, since it is bare.
  1953. Raises:
  1954. NoIndexPresent: Raised when no index is present
  1955. """
  1956. raise NoIndexPresent
  1957. def get_config(self) -> "ConfigFile":
  1958. """Retrieve the config object.
  1959. Returns: `ConfigFile` object.
  1960. """
  1961. return self._config
  1962. def get_rebase_state_manager(self) -> "RebaseStateManager":
  1963. """Get the appropriate rebase state manager for this repository.
  1964. Returns: MemoryRebaseStateManager instance
  1965. """
  1966. from .rebase import MemoryRebaseStateManager
  1967. return MemoryRebaseStateManager(self)
  1968. def get_blob_normalizer(self) -> "FilterBlobNormalizer":
  1969. """Return a BlobNormalizer object for checkin/checkout operations."""
  1970. from .filters import FilterBlobNormalizer, FilterContext, FilterRegistry
  1971. # Get fresh configuration and GitAttributes
  1972. config_stack = self.get_config_stack()
  1973. git_attributes = self.get_gitattributes()
  1974. # Lazily create FilterContext if needed
  1975. if self.filter_context is None:
  1976. filter_registry = FilterRegistry(config_stack, self)
  1977. self.filter_context = FilterContext(filter_registry)
  1978. else:
  1979. # Refresh the context with current config to handle config changes
  1980. self.filter_context.refresh_config(config_stack)
  1981. # Return a new FilterBlobNormalizer with the context
  1982. return FilterBlobNormalizer(
  1983. config_stack, git_attributes, filter_context=self.filter_context
  1984. )
  1985. def get_gitattributes(self, tree: Optional[bytes] = None) -> "GitAttributes":
  1986. """Read gitattributes for the repository."""
  1987. from .attrs import GitAttributes
  1988. # Memory repos don't have working trees or gitattributes files
  1989. # Return empty GitAttributes
  1990. return GitAttributes([])
  1991. def close(self) -> None:
  1992. """Close any resources opened by this repository."""
  1993. # Clean up filter context if it was created
  1994. if self.filter_context is not None:
  1995. self.filter_context.close()
  1996. self.filter_context = None
  1997. def do_commit(
  1998. self,
  1999. message: Optional[bytes] = None,
  2000. committer: Optional[bytes] = None,
  2001. author: Optional[bytes] = None,
  2002. commit_timestamp: Optional[float] = None,
  2003. commit_timezone: Optional[int] = None,
  2004. author_timestamp: Optional[float] = None,
  2005. author_timezone: Optional[int] = None,
  2006. tree: Optional[ObjectID] = None,
  2007. encoding: Optional[bytes] = None,
  2008. ref: Optional[Ref] = b"HEAD",
  2009. merge_heads: Optional[list[ObjectID]] = None,
  2010. no_verify: bool = False,
  2011. sign: bool = False,
  2012. ) -> bytes:
  2013. """Create a new commit.
  2014. This is a simplified implementation for in-memory repositories that
  2015. doesn't support worktree operations or hooks.
  2016. Args:
  2017. message: Commit message
  2018. committer: Committer fullname
  2019. author: Author fullname
  2020. commit_timestamp: Commit timestamp (defaults to now)
  2021. commit_timezone: Commit timestamp timezone (defaults to GMT)
  2022. author_timestamp: Author timestamp (defaults to commit timestamp)
  2023. author_timezone: Author timestamp timezone (defaults to commit timezone)
  2024. tree: SHA1 of the tree root to use
  2025. encoding: Encoding
  2026. ref: Optional ref to commit to (defaults to current branch).
  2027. If None, creates a dangling commit without updating any ref.
  2028. merge_heads: Merge heads
  2029. no_verify: Skip pre-commit and commit-msg hooks (ignored for MemoryRepo)
  2030. sign: GPG Sign the commit (ignored for MemoryRepo)
  2031. Returns:
  2032. New commit SHA1
  2033. """
  2034. import time
  2035. from .objects import Commit
  2036. if tree is None:
  2037. raise ValueError("tree must be specified for MemoryRepo")
  2038. c = Commit()
  2039. if len(tree) != 40:
  2040. raise ValueError("tree must be a 40-byte hex sha string")
  2041. c.tree = tree
  2042. config = self.get_config_stack()
  2043. if merge_heads is None:
  2044. merge_heads = []
  2045. if committer is None:
  2046. committer = get_user_identity(config, kind="COMMITTER")
  2047. check_user_identity(committer)
  2048. c.committer = committer
  2049. if commit_timestamp is None:
  2050. commit_timestamp = time.time()
  2051. c.commit_time = int(commit_timestamp)
  2052. if commit_timezone is None:
  2053. commit_timezone = 0
  2054. c.commit_timezone = commit_timezone
  2055. if author is None:
  2056. author = get_user_identity(config, kind="AUTHOR")
  2057. c.author = author
  2058. check_user_identity(author)
  2059. if author_timestamp is None:
  2060. author_timestamp = commit_timestamp
  2061. c.author_time = int(author_timestamp)
  2062. if author_timezone is None:
  2063. author_timezone = commit_timezone
  2064. c.author_timezone = author_timezone
  2065. if encoding is None:
  2066. try:
  2067. encoding = config.get(("i18n",), "commitEncoding")
  2068. except KeyError:
  2069. pass
  2070. if encoding is not None:
  2071. c.encoding = encoding
  2072. # Handle message (for MemoryRepo, we don't support callable messages)
  2073. if callable(message):
  2074. message = message(self, c)
  2075. if message is None:
  2076. raise ValueError("Message callback returned None")
  2077. if message is None:
  2078. raise ValueError("No commit message specified")
  2079. c.message = message
  2080. if ref is None:
  2081. # Create a dangling commit
  2082. c.parents = merge_heads
  2083. self.object_store.add_object(c)
  2084. else:
  2085. try:
  2086. old_head = self.refs[ref]
  2087. c.parents = [old_head, *merge_heads]
  2088. self.object_store.add_object(c)
  2089. ok = self.refs.set_if_equals(
  2090. ref,
  2091. old_head,
  2092. c.id,
  2093. message=b"commit: " + message,
  2094. committer=committer,
  2095. timestamp=int(commit_timestamp),
  2096. timezone=commit_timezone,
  2097. )
  2098. except KeyError:
  2099. c.parents = merge_heads
  2100. self.object_store.add_object(c)
  2101. ok = self.refs.add_if_new(
  2102. ref,
  2103. c.id,
  2104. message=b"commit: " + message,
  2105. committer=committer,
  2106. timestamp=int(commit_timestamp),
  2107. timezone=commit_timezone,
  2108. )
  2109. if not ok:
  2110. from .errors import CommitError
  2111. raise CommitError(f"{ref!r} changed during commit")
  2112. return c.id
  2113. @classmethod
  2114. def init_bare(
  2115. cls,
  2116. objects: Iterable[ShaFile],
  2117. refs: dict[bytes, bytes],
  2118. format: Optional[int] = None,
  2119. ) -> "MemoryRepo":
  2120. """Create a new bare repository in memory.
  2121. Args:
  2122. objects: Objects for the new repository,
  2123. as iterable
  2124. refs: Refs as dictionary, mapping names
  2125. to object SHA1s
  2126. format: Repository format version (defaults to 0)
  2127. """
  2128. ret = cls()
  2129. for obj in objects:
  2130. ret.object_store.add_object(obj)
  2131. for refname, sha in refs.items():
  2132. ret.refs.add_if_new(refname, sha)
  2133. ret._init_files(bare=True, format=format)
  2134. return ret