repo.py 81 KB

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