repo.py 98 KB

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