repo.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  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. object_store: DiskObjectStore
  929. def __init__(
  930. self,
  931. root: Union[str, bytes, os.PathLike],
  932. object_store: Optional[PackBasedObjectStore] = None,
  933. bare: Optional[bool] = None,
  934. ) -> None:
  935. """Open a repository on disk.
  936. Args:
  937. root: Path to the repository's root.
  938. object_store: ObjectStore to use; if omitted, we use the
  939. repository's default object store
  940. bare: True if this is a bare repository.
  941. """
  942. root = os.fspath(root)
  943. if isinstance(root, bytes):
  944. root = os.fsdecode(root)
  945. hidden_path = os.path.join(root, CONTROLDIR)
  946. if bare is None:
  947. if os.path.isfile(hidden_path) or os.path.isdir(
  948. os.path.join(hidden_path, OBJECTDIR)
  949. ):
  950. bare = False
  951. elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir(
  952. os.path.join(root, REFSDIR)
  953. ):
  954. bare = True
  955. else:
  956. raise NotGitRepository(
  957. "No git repository was found at {path}".format(**dict(path=root))
  958. )
  959. self.bare = bare
  960. if bare is False:
  961. if os.path.isfile(hidden_path):
  962. with open(hidden_path) as f:
  963. path = read_gitfile(f)
  964. self._controldir = os.path.join(root, path)
  965. else:
  966. self._controldir = hidden_path
  967. else:
  968. self._controldir = root
  969. commondir = self.get_named_file(COMMONDIR)
  970. if commondir is not None:
  971. with commondir:
  972. self._commondir = os.path.join(
  973. self.controldir(),
  974. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  975. )
  976. else:
  977. self._commondir = self._controldir
  978. self.path = root
  979. # Initialize refs early so they're available for config condition matchers
  980. self.refs = DiskRefsContainer(
  981. self.commondir(), self._controldir, logger=self._write_reflog
  982. )
  983. # Initialize worktrees container
  984. from .worktree import WorkTreeContainer
  985. self.worktrees = WorkTreeContainer(self)
  986. config = self.get_config()
  987. try:
  988. repository_format_version = config.get("core", "repositoryformatversion")
  989. format_version = (
  990. 0
  991. if repository_format_version is None
  992. else int(repository_format_version)
  993. )
  994. except KeyError:
  995. format_version = 0
  996. if format_version not in (0, 1):
  997. raise UnsupportedVersion(format_version)
  998. # Track extensions we encounter
  999. has_reftable_extension = False
  1000. for extension, value in config.items((b"extensions",)):
  1001. if extension.lower() == b"refstorage":
  1002. if value == b"reftable":
  1003. has_reftable_extension = True
  1004. else:
  1005. raise UnsupportedExtension(f"refStorage = {value.decode()}")
  1006. elif extension.lower() not in (b"worktreeconfig",):
  1007. raise UnsupportedExtension(extension)
  1008. if object_store is None:
  1009. object_store = DiskObjectStore.from_config(
  1010. os.path.join(self.commondir(), OBJECTDIR), config
  1011. )
  1012. # Use reftable if extension is configured
  1013. if has_reftable_extension:
  1014. from .reftable import ReftableRefsContainer
  1015. self.refs = ReftableRefsContainer(self.commondir())
  1016. # Update worktrees container after refs change
  1017. self.worktrees = WorkTreeContainer(self)
  1018. BaseRepo.__init__(self, object_store, self.refs)
  1019. self._graftpoints = {}
  1020. graft_file = self.get_named_file(
  1021. os.path.join("info", "grafts"), basedir=self.commondir()
  1022. )
  1023. if graft_file:
  1024. with graft_file:
  1025. self._graftpoints.update(parse_graftpoints(graft_file))
  1026. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  1027. if graft_file:
  1028. with graft_file:
  1029. self._graftpoints.update(parse_graftpoints(graft_file))
  1030. self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir())
  1031. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  1032. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  1033. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  1034. def get_worktree(self) -> "WorkTree":
  1035. """Get the working tree for this repository.
  1036. Returns:
  1037. WorkTree instance for performing working tree operations
  1038. """
  1039. from .worktree import WorkTree
  1040. return WorkTree(self, self.path)
  1041. def _write_reflog(
  1042. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  1043. ) -> None:
  1044. from .reflog import format_reflog_line
  1045. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  1046. try:
  1047. os.makedirs(os.path.dirname(path))
  1048. except FileExistsError:
  1049. pass
  1050. if committer is None:
  1051. config = self.get_config_stack()
  1052. committer = get_user_identity(config)
  1053. check_user_identity(committer)
  1054. if timestamp is None:
  1055. timestamp = int(time.time())
  1056. if timezone is None:
  1057. timezone = 0 # FIXME
  1058. with open(path, "ab") as f:
  1059. f.write(
  1060. format_reflog_line(
  1061. old_sha, new_sha, committer, timestamp, timezone, message
  1062. )
  1063. + b"\n"
  1064. )
  1065. def read_reflog(self, ref):
  1066. """Read reflog entries for a reference.
  1067. Args:
  1068. ref: Reference name (e.g. b'HEAD', b'refs/heads/master')
  1069. Yields:
  1070. reflog.Entry objects in chronological order (oldest first)
  1071. """
  1072. from .reflog import read_reflog
  1073. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  1074. try:
  1075. with open(path, "rb") as f:
  1076. yield from read_reflog(f)
  1077. except FileNotFoundError:
  1078. return
  1079. @classmethod
  1080. def discover(cls, start="."):
  1081. """Iterate parent directories to discover a repository.
  1082. Return a Repo object for the first parent directory that looks like a
  1083. Git repository.
  1084. Args:
  1085. start: The directory to start discovery from (defaults to '.')
  1086. """
  1087. remaining = True
  1088. path = os.path.abspath(start)
  1089. while remaining:
  1090. try:
  1091. return cls(path)
  1092. except NotGitRepository:
  1093. path, remaining = os.path.split(path)
  1094. raise NotGitRepository(
  1095. "No git repository was found at {path}".format(**dict(path=start))
  1096. )
  1097. def controldir(self):
  1098. """Return the path of the control directory."""
  1099. return self._controldir
  1100. def commondir(self):
  1101. """Return the path of the common directory.
  1102. For a main working tree, it is identical to controldir().
  1103. For a linked working tree, it is the control directory of the
  1104. main working tree.
  1105. """
  1106. return self._commondir
  1107. def _determine_file_mode(self):
  1108. """Probe the file-system to determine whether permissions can be trusted.
  1109. Returns: True if permissions can be trusted, False otherwise.
  1110. """
  1111. fname = os.path.join(self.path, ".probe-permissions")
  1112. with open(fname, "w") as f:
  1113. f.write("")
  1114. st1 = os.lstat(fname)
  1115. try:
  1116. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  1117. except PermissionError:
  1118. return False
  1119. st2 = os.lstat(fname)
  1120. os.unlink(fname)
  1121. mode_differs = st1.st_mode != st2.st_mode
  1122. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1123. return mode_differs and st2_has_exec
  1124. def _determine_symlinks(self):
  1125. """Probe the filesystem to determine whether symlinks can be created.
  1126. Returns: True if symlinks can be created, False otherwise.
  1127. """
  1128. # TODO(jelmer): Actually probe disk / look at filesystem
  1129. return sys.platform != "win32"
  1130. def _put_named_file(self, path, contents) -> None:
  1131. """Write a file to the control dir with the given name and contents.
  1132. Args:
  1133. path: The path to the file, relative to the control dir.
  1134. contents: A string to write to the file.
  1135. """
  1136. path = path.lstrip(os.path.sep)
  1137. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1138. f.write(contents)
  1139. def _del_named_file(self, path) -> None:
  1140. try:
  1141. os.unlink(os.path.join(self.controldir(), path))
  1142. except FileNotFoundError:
  1143. return
  1144. def get_named_file(self, path, basedir=None):
  1145. """Get a file from the control dir with a specific name.
  1146. Although the filename should be interpreted as a filename relative to
  1147. the control dir in a disk-based Repo, the object returned need not be
  1148. pointing to a file in that location.
  1149. Args:
  1150. path: The path to the file, relative to the control dir.
  1151. basedir: Optional argument that specifies an alternative to the
  1152. control dir.
  1153. Returns: An open file object, or None if the file does not exist.
  1154. """
  1155. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1156. # the dumb web serving code.
  1157. if basedir is None:
  1158. basedir = self.controldir()
  1159. path = path.lstrip(os.path.sep)
  1160. try:
  1161. return open(os.path.join(basedir, path), "rb")
  1162. except FileNotFoundError:
  1163. return None
  1164. def index_path(self):
  1165. """Return path to the index file."""
  1166. return os.path.join(self.controldir(), INDEX_FILENAME)
  1167. def open_index(self) -> "Index":
  1168. """Open the index for this repository.
  1169. Raises:
  1170. NoIndexPresent: If no index is present
  1171. Returns: The matching `Index`
  1172. """
  1173. from .index import Index
  1174. if not self.has_index():
  1175. raise NoIndexPresent
  1176. # Check for manyFiles feature configuration
  1177. config = self.get_config_stack()
  1178. many_files = config.get_boolean(b"feature", b"manyFiles", False)
  1179. skip_hash = False
  1180. index_version = None
  1181. if many_files:
  1182. # When feature.manyFiles is enabled, set index.version=4 and index.skipHash=true
  1183. try:
  1184. index_version_str = config.get(b"index", b"version")
  1185. index_version = int(index_version_str)
  1186. except KeyError:
  1187. index_version = 4 # Default to version 4 for manyFiles
  1188. skip_hash = config.get_boolean(b"index", b"skipHash", True)
  1189. else:
  1190. # Check for explicit index settings
  1191. try:
  1192. index_version_str = config.get(b"index", b"version")
  1193. index_version = int(index_version_str)
  1194. except KeyError:
  1195. index_version = None
  1196. skip_hash = config.get_boolean(b"index", b"skipHash", False)
  1197. return Index(self.index_path(), skip_hash=skip_hash, version=index_version)
  1198. def has_index(self) -> bool:
  1199. """Check if an index is present."""
  1200. # Bare repos must never have index files; non-bare repos may have a
  1201. # missing index file, which is treated as empty.
  1202. return not self.bare
  1203. @replace_me(remove_in="0.26.0")
  1204. def stage(
  1205. self,
  1206. fs_paths: Union[
  1207. str, bytes, os.PathLike, Iterable[Union[str, bytes, os.PathLike]]
  1208. ],
  1209. ) -> None:
  1210. """Stage a set of paths.
  1211. Args:
  1212. fs_paths: List of paths, relative to the repository path
  1213. """
  1214. return self.get_worktree().stage(fs_paths)
  1215. @replace_me(remove_in="0.26.0")
  1216. def unstage(self, fs_paths: list[str]) -> None:
  1217. """Unstage specific file in the index
  1218. Args:
  1219. fs_paths: a list of files to unstage,
  1220. relative to the repository path.
  1221. """
  1222. return self.get_worktree().unstage(fs_paths)
  1223. def clone(
  1224. self,
  1225. target_path,
  1226. *,
  1227. mkdir=True,
  1228. bare=False,
  1229. origin=b"origin",
  1230. checkout=None,
  1231. branch=None,
  1232. progress=None,
  1233. depth: Optional[int] = None,
  1234. symlinks=None,
  1235. ) -> "Repo":
  1236. """Clone this repository.
  1237. Args:
  1238. target_path: Target path
  1239. mkdir: Create the target directory
  1240. bare: Whether to create a bare repository
  1241. checkout: Whether or not to check-out HEAD after cloning
  1242. origin: Base name for refs in target repository
  1243. cloned from this repository
  1244. branch: Optional branch or tag to be used as HEAD in the new repository
  1245. instead of this repository's HEAD.
  1246. progress: Optional progress function
  1247. depth: Depth at which to fetch
  1248. symlinks: Symlinks setting (default to autodetect)
  1249. Returns: Created repository as `Repo`
  1250. """
  1251. encoded_path = os.fsencode(self.path)
  1252. if mkdir:
  1253. os.mkdir(target_path)
  1254. try:
  1255. if not bare:
  1256. target = Repo.init(target_path, symlinks=symlinks)
  1257. if checkout is None:
  1258. checkout = True
  1259. else:
  1260. if checkout:
  1261. raise ValueError("checkout and bare are incompatible")
  1262. target = Repo.init_bare(target_path)
  1263. try:
  1264. target_config = target.get_config()
  1265. target_config.set((b"remote", origin), b"url", encoded_path)
  1266. target_config.set(
  1267. (b"remote", origin),
  1268. b"fetch",
  1269. b"+refs/heads/*:refs/remotes/" + origin + b"/*",
  1270. )
  1271. target_config.write_to_path()
  1272. ref_message = b"clone: from " + encoded_path
  1273. self.fetch(target, depth=depth)
  1274. target.refs.import_refs(
  1275. b"refs/remotes/" + origin,
  1276. self.refs.as_dict(b"refs/heads"),
  1277. message=ref_message,
  1278. )
  1279. target.refs.import_refs(
  1280. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1281. )
  1282. head_chain, origin_sha = self.refs.follow(b"HEAD")
  1283. origin_head = head_chain[-1] if head_chain else None
  1284. if origin_sha and not origin_head:
  1285. # set detached HEAD
  1286. target.refs[b"HEAD"] = origin_sha
  1287. else:
  1288. _set_origin_head(target.refs, origin, origin_head)
  1289. head_ref = _set_default_branch(
  1290. target.refs, origin, origin_head, branch, ref_message
  1291. )
  1292. # Update target head
  1293. if head_ref:
  1294. head = _set_head(target.refs, head_ref, ref_message)
  1295. else:
  1296. head = None
  1297. if checkout and head is not None:
  1298. target.get_worktree().reset_index()
  1299. except BaseException:
  1300. target.close()
  1301. raise
  1302. except BaseException:
  1303. if mkdir:
  1304. import shutil
  1305. shutil.rmtree(target_path)
  1306. raise
  1307. return target
  1308. @replace_me(remove_in="0.26.0")
  1309. def reset_index(self, tree: Optional[bytes] = None):
  1310. """Reset the index back to a specific tree.
  1311. Args:
  1312. tree: Tree SHA to reset to, None for current HEAD tree.
  1313. """
  1314. return self.get_worktree().reset_index(tree)
  1315. def _get_config_condition_matchers(self) -> dict[str, "ConditionMatcher"]:
  1316. """Get condition matchers for includeIf conditions.
  1317. Returns a dict of condition prefix to matcher function.
  1318. """
  1319. from pathlib import Path
  1320. from .config import ConditionMatcher, match_glob_pattern
  1321. # Add gitdir matchers
  1322. def match_gitdir(pattern: str, case_sensitive: bool = True) -> bool:
  1323. # Handle relative patterns (starting with ./)
  1324. if pattern.startswith("./"):
  1325. # Can't handle relative patterns without config directory context
  1326. return False
  1327. # Normalize repository path
  1328. try:
  1329. repo_path = str(Path(self._controldir).resolve())
  1330. except (OSError, ValueError):
  1331. return False
  1332. # Expand ~ in pattern and normalize
  1333. pattern = os.path.expanduser(pattern)
  1334. # Normalize pattern following Git's rules
  1335. pattern = pattern.replace("\\", "/")
  1336. if not pattern.startswith(("~/", "./", "/", "**")):
  1337. # Check for Windows absolute path
  1338. if len(pattern) >= 2 and pattern[1] == ":":
  1339. pass
  1340. else:
  1341. pattern = "**/" + pattern
  1342. if pattern.endswith("/"):
  1343. pattern = pattern + "**"
  1344. # Use the existing _match_gitdir_pattern function
  1345. from .config import _match_gitdir_pattern
  1346. pattern_bytes = pattern.encode("utf-8", errors="replace")
  1347. repo_path_bytes = repo_path.encode("utf-8", errors="replace")
  1348. return _match_gitdir_pattern(
  1349. repo_path_bytes, pattern_bytes, ignorecase=not case_sensitive
  1350. )
  1351. # Add onbranch matcher
  1352. def match_onbranch(pattern: str) -> bool:
  1353. try:
  1354. # Get the current branch using refs
  1355. ref_chain, _ = self.refs.follow(b"HEAD")
  1356. head_ref = ref_chain[-1] # Get the final resolved ref
  1357. except KeyError:
  1358. pass
  1359. else:
  1360. if head_ref and head_ref.startswith(b"refs/heads/"):
  1361. # Extract branch name from ref
  1362. branch = head_ref[11:].decode("utf-8", errors="replace")
  1363. return match_glob_pattern(branch, pattern)
  1364. return False
  1365. matchers: dict[str, ConditionMatcher] = {
  1366. "onbranch:": match_onbranch,
  1367. "gitdir:": lambda pattern: match_gitdir(pattern, True),
  1368. "gitdir/i:": lambda pattern: match_gitdir(pattern, False),
  1369. }
  1370. return matchers
  1371. def get_worktree_config(self) -> "ConfigFile":
  1372. from .config import ConfigFile
  1373. path = os.path.join(self.commondir(), "config.worktree")
  1374. try:
  1375. # Pass condition matchers for includeIf evaluation
  1376. condition_matchers = self._get_config_condition_matchers()
  1377. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1378. except FileNotFoundError:
  1379. cf = ConfigFile()
  1380. cf.path = path
  1381. return cf
  1382. def get_config(self) -> "ConfigFile":
  1383. """Retrieve the config object.
  1384. Returns: `ConfigFile` object for the ``.git/config`` file.
  1385. """
  1386. from .config import ConfigFile
  1387. path = os.path.join(self._commondir, "config")
  1388. try:
  1389. # Pass condition matchers for includeIf evaluation
  1390. condition_matchers = self._get_config_condition_matchers()
  1391. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1392. except FileNotFoundError:
  1393. ret = ConfigFile()
  1394. ret.path = path
  1395. return ret
  1396. def get_rebase_state_manager(self):
  1397. """Get the appropriate rebase state manager for this repository.
  1398. Returns: DiskRebaseStateManager instance
  1399. """
  1400. import os
  1401. from .rebase import DiskRebaseStateManager
  1402. path = os.path.join(self.controldir(), "rebase-merge")
  1403. return DiskRebaseStateManager(path)
  1404. def get_description(self):
  1405. """Retrieve the description of this repository.
  1406. Returns: A string describing the repository or None.
  1407. """
  1408. path = os.path.join(self._controldir, "description")
  1409. try:
  1410. with GitFile(path, "rb") as f:
  1411. return f.read()
  1412. except FileNotFoundError:
  1413. return None
  1414. def __repr__(self) -> str:
  1415. return f"<Repo at {self.path!r}>"
  1416. def set_description(self, description) -> None:
  1417. """Set the description for this repository.
  1418. Args:
  1419. description: Text to set as description for this repository.
  1420. """
  1421. self._put_named_file("description", description)
  1422. @classmethod
  1423. def _init_maybe_bare(
  1424. cls,
  1425. path: Union[str, bytes, os.PathLike],
  1426. controldir: Union[str, bytes, os.PathLike],
  1427. bare,
  1428. object_store=None,
  1429. config=None,
  1430. default_branch=None,
  1431. symlinks: Optional[bool] = None,
  1432. format: Optional[int] = None,
  1433. ):
  1434. path = os.fspath(path)
  1435. if isinstance(path, bytes):
  1436. path = os.fsdecode(path)
  1437. controldir = os.fspath(controldir)
  1438. if isinstance(controldir, bytes):
  1439. controldir = os.fsdecode(controldir)
  1440. for d in BASE_DIRECTORIES:
  1441. os.mkdir(os.path.join(controldir, *d))
  1442. if object_store is None:
  1443. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1444. ret = cls(path, bare=bare, object_store=object_store)
  1445. if default_branch is None:
  1446. if config is None:
  1447. from .config import StackedConfig
  1448. config = StackedConfig.default()
  1449. try:
  1450. default_branch = config.get("init", "defaultBranch")
  1451. except KeyError:
  1452. default_branch = DEFAULT_BRANCH
  1453. ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch)
  1454. ret._init_files(bare=bare, symlinks=symlinks, format=format)
  1455. return ret
  1456. @classmethod
  1457. def init(
  1458. cls,
  1459. path: Union[str, bytes, os.PathLike],
  1460. *,
  1461. mkdir: bool = False,
  1462. config=None,
  1463. default_branch=None,
  1464. symlinks: Optional[bool] = None,
  1465. format: Optional[int] = None,
  1466. ) -> "Repo":
  1467. """Create a new repository.
  1468. Args:
  1469. path: Path in which to create the repository
  1470. mkdir: Whether to create the directory
  1471. format: Repository format version (defaults to 0)
  1472. Returns: `Repo` instance
  1473. """
  1474. path = os.fspath(path)
  1475. if isinstance(path, bytes):
  1476. path = os.fsdecode(path)
  1477. if mkdir:
  1478. os.mkdir(path)
  1479. controldir = os.path.join(path, CONTROLDIR)
  1480. os.mkdir(controldir)
  1481. _set_filesystem_hidden(controldir)
  1482. return cls._init_maybe_bare(
  1483. path,
  1484. controldir,
  1485. False,
  1486. config=config,
  1487. default_branch=default_branch,
  1488. symlinks=symlinks,
  1489. format=format,
  1490. )
  1491. @classmethod
  1492. def _init_new_working_directory(
  1493. cls,
  1494. path: Union[str, bytes, os.PathLike],
  1495. main_repo,
  1496. identifier=None,
  1497. mkdir=False,
  1498. ):
  1499. """Create a new working directory linked to a repository.
  1500. Args:
  1501. path: Path in which to create the working tree.
  1502. main_repo: Main repository to reference
  1503. identifier: Worktree identifier
  1504. mkdir: Whether to create the directory
  1505. Returns: `Repo` instance
  1506. """
  1507. path = os.fspath(path)
  1508. if isinstance(path, bytes):
  1509. path = os.fsdecode(path)
  1510. if mkdir:
  1511. os.mkdir(path)
  1512. if identifier is None:
  1513. identifier = os.path.basename(path)
  1514. # Ensure we use absolute path for the worktree control directory
  1515. main_controldir = os.path.abspath(main_repo.controldir())
  1516. main_worktreesdir = os.path.join(main_controldir, WORKTREES)
  1517. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1518. gitdirfile = os.path.join(path, CONTROLDIR)
  1519. with open(gitdirfile, "wb") as f:
  1520. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1521. try:
  1522. os.mkdir(main_worktreesdir)
  1523. except FileExistsError:
  1524. pass
  1525. try:
  1526. os.mkdir(worktree_controldir)
  1527. except FileExistsError:
  1528. pass
  1529. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1530. f.write(os.fsencode(gitdirfile) + b"\n")
  1531. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1532. f.write(b"../..\n")
  1533. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1534. f.write(main_repo.head() + b"\n")
  1535. r = cls(os.path.normpath(path))
  1536. r.get_worktree().reset_index()
  1537. return r
  1538. @classmethod
  1539. def init_bare(
  1540. cls,
  1541. path: Union[str, bytes, os.PathLike],
  1542. *,
  1543. mkdir=False,
  1544. object_store=None,
  1545. config=None,
  1546. default_branch=None,
  1547. format: Optional[int] = None,
  1548. ):
  1549. """Create a new bare repository.
  1550. ``path`` should already exist and be an empty directory.
  1551. Args:
  1552. path: Path to create bare repository in
  1553. format: Repository format version (defaults to 0)
  1554. Returns: a `Repo` instance
  1555. """
  1556. path = os.fspath(path)
  1557. if isinstance(path, bytes):
  1558. path = os.fsdecode(path)
  1559. if mkdir:
  1560. os.mkdir(path)
  1561. return cls._init_maybe_bare(
  1562. path,
  1563. path,
  1564. True,
  1565. object_store=object_store,
  1566. config=config,
  1567. default_branch=default_branch,
  1568. format=format,
  1569. )
  1570. create = init_bare
  1571. def close(self) -> None:
  1572. """Close any files opened by this repository."""
  1573. self.object_store.close()
  1574. def __enter__(self):
  1575. return self
  1576. def __exit__(self, exc_type, exc_val, exc_tb):
  1577. self.close()
  1578. def _read_gitattributes(self) -> dict[bytes, dict[bytes, bytes]]:
  1579. """Read .gitattributes file from working tree.
  1580. Returns:
  1581. Dictionary mapping file patterns to attributes
  1582. """
  1583. gitattributes = {}
  1584. gitattributes_path = os.path.join(self.path, ".gitattributes")
  1585. if os.path.exists(gitattributes_path):
  1586. with open(gitattributes_path, "rb") as f:
  1587. for line in f:
  1588. line = line.strip()
  1589. if not line or line.startswith(b"#"):
  1590. continue
  1591. parts = line.split()
  1592. if len(parts) < 2:
  1593. continue
  1594. pattern = parts[0]
  1595. attrs = {}
  1596. for attr in parts[1:]:
  1597. if attr.startswith(b"-"):
  1598. # Unset attribute
  1599. attrs[attr[1:]] = b"false"
  1600. elif b"=" in attr:
  1601. # Set to value
  1602. key, value = attr.split(b"=", 1)
  1603. attrs[key] = value
  1604. else:
  1605. # Set attribute
  1606. attrs[attr] = b"true"
  1607. gitattributes[pattern] = attrs
  1608. return gitattributes
  1609. def get_blob_normalizer(self):
  1610. """Return a BlobNormalizer object."""
  1611. from .filters import FilterBlobNormalizer, FilterRegistry
  1612. # Get proper GitAttributes object
  1613. git_attributes = self.get_gitattributes()
  1614. config_stack = self.get_config_stack()
  1615. # Create FilterRegistry with repo reference
  1616. filter_registry = FilterRegistry(config_stack, self)
  1617. # Return FilterBlobNormalizer which handles all filters including line endings
  1618. return FilterBlobNormalizer(config_stack, git_attributes, filter_registry, self)
  1619. def get_gitattributes(self, tree: Optional[bytes] = None) -> "GitAttributes":
  1620. """Read gitattributes for the repository.
  1621. Args:
  1622. tree: Tree SHA to read .gitattributes from (defaults to HEAD)
  1623. Returns:
  1624. GitAttributes object that can be used to match paths
  1625. """
  1626. from .attrs import (
  1627. GitAttributes,
  1628. Pattern,
  1629. parse_git_attributes,
  1630. )
  1631. patterns = []
  1632. # Read system gitattributes (TODO: implement this)
  1633. # Read global gitattributes (TODO: implement this)
  1634. # Read repository .gitattributes from index/tree
  1635. if tree is None:
  1636. try:
  1637. # Try to get from HEAD
  1638. head = self[b"HEAD"]
  1639. if isinstance(head, Tag):
  1640. _cls, obj = head.object
  1641. head = self.get_object(obj)
  1642. tree = head.tree
  1643. except KeyError:
  1644. # No HEAD, no attributes from tree
  1645. pass
  1646. if tree is not None:
  1647. try:
  1648. tree_obj = self[tree]
  1649. if b".gitattributes" in tree_obj:
  1650. _, attrs_sha = tree_obj[b".gitattributes"]
  1651. attrs_blob = self[attrs_sha]
  1652. if isinstance(attrs_blob, Blob):
  1653. attrs_data = BytesIO(attrs_blob.data)
  1654. for pattern_bytes, attrs in parse_git_attributes(attrs_data):
  1655. pattern = Pattern(pattern_bytes)
  1656. patterns.append((pattern, attrs))
  1657. except (KeyError, NotTreeError):
  1658. pass
  1659. # Read .git/info/attributes
  1660. info_attrs_path = os.path.join(self.controldir(), "info", "attributes")
  1661. if os.path.exists(info_attrs_path):
  1662. with open(info_attrs_path, "rb") as f:
  1663. for pattern_bytes, attrs in parse_git_attributes(f):
  1664. pattern = Pattern(pattern_bytes)
  1665. patterns.append((pattern, attrs))
  1666. # Read .gitattributes from working directory (if it exists)
  1667. working_attrs_path = os.path.join(self.path, ".gitattributes")
  1668. if os.path.exists(working_attrs_path):
  1669. with open(working_attrs_path, "rb") as f:
  1670. for pattern_bytes, attrs in parse_git_attributes(f):
  1671. pattern = Pattern(pattern_bytes)
  1672. patterns.append((pattern, attrs))
  1673. return GitAttributes(patterns)
  1674. @replace_me(remove_in="0.26.0")
  1675. def _sparse_checkout_file_path(self) -> str:
  1676. """Return the path of the sparse-checkout file in this repo's control dir."""
  1677. return self.get_worktree()._sparse_checkout_file_path()
  1678. @replace_me(remove_in="0.26.0")
  1679. def configure_for_cone_mode(self) -> None:
  1680. """Ensure the repository is configured for cone-mode sparse-checkout."""
  1681. return self.get_worktree().configure_for_cone_mode()
  1682. @replace_me(remove_in="0.26.0")
  1683. def infer_cone_mode(self) -> bool:
  1684. """Return True if 'core.sparseCheckoutCone' is set to 'true' in config, else False."""
  1685. return self.get_worktree().infer_cone_mode()
  1686. @replace_me(remove_in="0.26.0")
  1687. def get_sparse_checkout_patterns(self) -> list[str]:
  1688. """Return a list of sparse-checkout patterns from info/sparse-checkout.
  1689. Returns:
  1690. A list of patterns. Returns an empty list if the file is missing.
  1691. """
  1692. return self.get_worktree().get_sparse_checkout_patterns()
  1693. @replace_me(remove_in="0.26.0")
  1694. def set_sparse_checkout_patterns(self, patterns: list[str]) -> None:
  1695. """Write the given sparse-checkout patterns into info/sparse-checkout.
  1696. Creates the info/ directory if it does not exist.
  1697. Args:
  1698. patterns: A list of gitignore-style patterns to store.
  1699. """
  1700. return self.get_worktree().set_sparse_checkout_patterns(patterns)
  1701. @replace_me(remove_in="0.26.0")
  1702. def set_cone_mode_patterns(self, dirs: Union[list[str], None] = None) -> None:
  1703. """Write the given cone-mode directory patterns into info/sparse-checkout.
  1704. For each directory to include, add an inclusion line that "undoes" the prior
  1705. ``!/*/`` 'exclude' that re-includes that directory and everything under it.
  1706. Never add the same line twice.
  1707. """
  1708. return self.get_worktree().set_cone_mode_patterns(dirs)
  1709. class MemoryRepo(BaseRepo):
  1710. """Repo that stores refs, objects, and named files in memory.
  1711. MemoryRepos are always bare: they have no working tree and no index, since
  1712. those have a stronger dependency on the filesystem.
  1713. """
  1714. def __init__(self) -> None:
  1715. """Create a new repository in memory."""
  1716. from .config import ConfigFile
  1717. self._reflog: list[Any] = []
  1718. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1719. BaseRepo.__init__(self, MemoryObjectStore(), refs_container) # type: ignore
  1720. self._named_files: dict[str, bytes] = {}
  1721. self.bare = True
  1722. self._config = ConfigFile()
  1723. self._description = None
  1724. def _append_reflog(self, *args) -> None:
  1725. self._reflog.append(args)
  1726. def set_description(self, description) -> None:
  1727. self._description = description
  1728. def get_description(self):
  1729. return self._description
  1730. def _determine_file_mode(self):
  1731. """Probe the file-system to determine whether permissions can be trusted.
  1732. Returns: True if permissions can be trusted, False otherwise.
  1733. """
  1734. return sys.platform != "win32"
  1735. def _determine_symlinks(self):
  1736. """Probe the file-system to determine whether permissions can be trusted.
  1737. Returns: True if permissions can be trusted, False otherwise.
  1738. """
  1739. return sys.platform != "win32"
  1740. def _put_named_file(self, path, contents) -> None:
  1741. """Write a file to the control dir with the given name and contents.
  1742. Args:
  1743. path: The path to the file, relative to the control dir.
  1744. contents: A string to write to the file.
  1745. """
  1746. self._named_files[path] = contents
  1747. def _del_named_file(self, path) -> None:
  1748. try:
  1749. del self._named_files[path]
  1750. except KeyError:
  1751. pass
  1752. def get_named_file(self, path, basedir=None):
  1753. """Get a file from the control dir with a specific name.
  1754. Although the filename should be interpreted as a filename relative to
  1755. the control dir in a disk-baked Repo, the object returned need not be
  1756. pointing to a file in that location.
  1757. Args:
  1758. path: The path to the file, relative to the control dir.
  1759. Returns: An open file object, or None if the file does not exist.
  1760. """
  1761. contents = self._named_files.get(path, None)
  1762. if contents is None:
  1763. return None
  1764. return BytesIO(contents)
  1765. def open_index(self) -> "Index":
  1766. """Fail to open index for this repo, since it is bare.
  1767. Raises:
  1768. NoIndexPresent: Raised when no index is present
  1769. """
  1770. raise NoIndexPresent
  1771. def get_config(self):
  1772. """Retrieve the config object.
  1773. Returns: `ConfigFile` object.
  1774. """
  1775. return self._config
  1776. def get_rebase_state_manager(self):
  1777. """Get the appropriate rebase state manager for this repository.
  1778. Returns: MemoryRebaseStateManager instance
  1779. """
  1780. from .rebase import MemoryRebaseStateManager
  1781. return MemoryRebaseStateManager(self)
  1782. def get_blob_normalizer(self):
  1783. """Return a BlobNormalizer object for checkin/checkout operations."""
  1784. from .filters import FilterBlobNormalizer, FilterRegistry
  1785. # Get GitAttributes object
  1786. git_attributes = self.get_gitattributes()
  1787. config_stack = self.get_config_stack()
  1788. # Create FilterRegistry with repo reference
  1789. filter_registry = FilterRegistry(config_stack, self)
  1790. # Return FilterBlobNormalizer which handles all filters
  1791. return FilterBlobNormalizer(config_stack, git_attributes, filter_registry, self)
  1792. def get_gitattributes(self, tree: Optional[bytes] = None) -> "GitAttributes":
  1793. """Read gitattributes for the repository."""
  1794. from .attrs import GitAttributes
  1795. # Memory repos don't have working trees or gitattributes files
  1796. # Return empty GitAttributes
  1797. return GitAttributes([])
  1798. def do_commit(
  1799. self,
  1800. message: Optional[bytes] = None,
  1801. committer: Optional[bytes] = None,
  1802. author: Optional[bytes] = None,
  1803. commit_timestamp=None,
  1804. commit_timezone=None,
  1805. author_timestamp=None,
  1806. author_timezone=None,
  1807. tree: Optional[ObjectID] = None,
  1808. encoding: Optional[bytes] = None,
  1809. ref: Optional[Ref] = b"HEAD",
  1810. merge_heads: Optional[list[ObjectID]] = None,
  1811. no_verify: bool = False,
  1812. sign: bool = False,
  1813. ):
  1814. """Create a new commit.
  1815. This is a simplified implementation for in-memory repositories that
  1816. doesn't support worktree operations or hooks.
  1817. Args:
  1818. message: Commit message
  1819. committer: Committer fullname
  1820. author: Author fullname
  1821. commit_timestamp: Commit timestamp (defaults to now)
  1822. commit_timezone: Commit timestamp timezone (defaults to GMT)
  1823. author_timestamp: Author timestamp (defaults to commit timestamp)
  1824. author_timezone: Author timestamp timezone (defaults to commit timezone)
  1825. tree: SHA1 of the tree root to use
  1826. encoding: Encoding
  1827. ref: Optional ref to commit to (defaults to current branch).
  1828. If None, creates a dangling commit without updating any ref.
  1829. merge_heads: Merge heads
  1830. no_verify: Skip pre-commit and commit-msg hooks (ignored for MemoryRepo)
  1831. sign: GPG Sign the commit (ignored for MemoryRepo)
  1832. Returns:
  1833. New commit SHA1
  1834. """
  1835. import time
  1836. from .objects import Commit
  1837. if tree is None:
  1838. raise ValueError("tree must be specified for MemoryRepo")
  1839. c = Commit()
  1840. if len(tree) != 40:
  1841. raise ValueError("tree must be a 40-byte hex sha string")
  1842. c.tree = tree
  1843. config = self.get_config_stack()
  1844. if merge_heads is None:
  1845. merge_heads = []
  1846. if committer is None:
  1847. committer = get_user_identity(config, kind="COMMITTER")
  1848. check_user_identity(committer)
  1849. c.committer = committer
  1850. if commit_timestamp is None:
  1851. commit_timestamp = time.time()
  1852. c.commit_time = int(commit_timestamp)
  1853. if commit_timezone is None:
  1854. commit_timezone = 0
  1855. c.commit_timezone = commit_timezone
  1856. if author is None:
  1857. author = get_user_identity(config, kind="AUTHOR")
  1858. c.author = author
  1859. check_user_identity(author)
  1860. if author_timestamp is None:
  1861. author_timestamp = commit_timestamp
  1862. c.author_time = int(author_timestamp)
  1863. if author_timezone is None:
  1864. author_timezone = commit_timezone
  1865. c.author_timezone = author_timezone
  1866. if encoding is None:
  1867. try:
  1868. encoding = config.get(("i18n",), "commitEncoding")
  1869. except KeyError:
  1870. pass
  1871. if encoding is not None:
  1872. c.encoding = encoding
  1873. # Handle message (for MemoryRepo, we don't support callable messages)
  1874. if callable(message):
  1875. message = message(self, c)
  1876. if message is None:
  1877. raise ValueError("Message callback returned None")
  1878. if message is None:
  1879. raise ValueError("No commit message specified")
  1880. c.message = message
  1881. if ref is None:
  1882. # Create a dangling commit
  1883. c.parents = merge_heads
  1884. self.object_store.add_object(c)
  1885. else:
  1886. try:
  1887. old_head = self.refs[ref]
  1888. c.parents = [old_head, *merge_heads]
  1889. self.object_store.add_object(c)
  1890. ok = self.refs.set_if_equals(
  1891. ref,
  1892. old_head,
  1893. c.id,
  1894. message=b"commit: " + message,
  1895. committer=committer,
  1896. timestamp=commit_timestamp,
  1897. timezone=commit_timezone,
  1898. )
  1899. except KeyError:
  1900. c.parents = merge_heads
  1901. self.object_store.add_object(c)
  1902. ok = self.refs.add_if_new(
  1903. ref,
  1904. c.id,
  1905. message=b"commit: " + message,
  1906. committer=committer,
  1907. timestamp=commit_timestamp,
  1908. timezone=commit_timezone,
  1909. )
  1910. if not ok:
  1911. from .errors import CommitError
  1912. raise CommitError(f"{ref!r} changed during commit")
  1913. return c.id
  1914. @classmethod
  1915. def init_bare(cls, objects, refs, format: Optional[int] = None):
  1916. """Create a new bare repository in memory.
  1917. Args:
  1918. objects: Objects for the new repository,
  1919. as iterable
  1920. refs: Refs as dictionary, mapping names
  1921. to object SHA1s
  1922. format: Repository format version (defaults to 0)
  1923. """
  1924. ret = cls()
  1925. for obj in objects:
  1926. ret.object_store.add_object(obj)
  1927. for refname, sha in refs.items():
  1928. ret.refs.add_if_new(refname, sha)
  1929. ret._init_files(bare=True, format=format)
  1930. return ret