repo.py 85 KB

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