repo.py 76 KB

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