repo.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258
  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 public 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 .config import ConditionMatcher, ConfigFile, StackedConfig
  47. from .index import Index
  48. from .notes import Notes
  49. from .errors import (
  50. CommitError,
  51. HookError,
  52. NoIndexPresent,
  53. NotBlobError,
  54. NotCommitError,
  55. NotGitRepository,
  56. NotTagError,
  57. NotTreeError,
  58. RefFormatError,
  59. )
  60. from .file import GitFile
  61. from .hooks import (
  62. CommitMsgShellHook,
  63. Hook,
  64. PostCommitShellHook,
  65. PostReceiveShellHook,
  66. PreCommitShellHook,
  67. )
  68. from .line_ending import BlobNormalizer, TreeBlobNormalizer
  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. return self.refs[b"HEAD"]
  572. def _get_object(self, sha, cls):
  573. assert len(sha) in (20, 40)
  574. ret = self.get_object(sha)
  575. if not isinstance(ret, cls):
  576. if cls is Commit:
  577. raise NotCommitError(ret)
  578. elif cls is Blob:
  579. raise NotBlobError(ret)
  580. elif cls is Tree:
  581. raise NotTreeError(ret)
  582. elif cls is Tag:
  583. raise NotTagError(ret)
  584. else:
  585. raise Exception(f"Type invalid: {ret.type_name!r} != {cls.type_name!r}")
  586. return ret
  587. def get_object(self, sha: bytes) -> ShaFile:
  588. """Retrieve the object with the specified SHA.
  589. Args:
  590. sha: SHA to retrieve
  591. Returns: A ShaFile object
  592. Raises:
  593. KeyError: when the object can not be found
  594. """
  595. return self.object_store[sha]
  596. def parents_provider(self) -> ParentsProvider:
  597. return ParentsProvider(
  598. self.object_store,
  599. grafts=self._graftpoints,
  600. shallows=self.get_shallow(),
  601. )
  602. def get_parents(self, sha: bytes, commit: Optional[Commit] = None) -> list[bytes]:
  603. """Retrieve the parents of a specific commit.
  604. If the specific commit is a graftpoint, the graft parents
  605. will be returned instead.
  606. Args:
  607. sha: SHA of the commit for which to retrieve the parents
  608. commit: Optional commit matching the sha
  609. Returns: List of parents
  610. """
  611. return self.parents_provider().get_parents(sha, commit)
  612. def get_config(self) -> "ConfigFile":
  613. """Retrieve the config object.
  614. Returns: `ConfigFile` object for the ``.git/config`` file.
  615. """
  616. raise NotImplementedError(self.get_config)
  617. def get_worktree_config(self) -> "ConfigFile":
  618. """Retrieve the worktree config object."""
  619. raise NotImplementedError(self.get_worktree_config)
  620. def get_description(self) -> Optional[str]:
  621. """Retrieve the description for this repository.
  622. Returns: String with the description of the repository
  623. as set by the user.
  624. """
  625. raise NotImplementedError(self.get_description)
  626. def set_description(self, description) -> None:
  627. """Set the description for this repository.
  628. Args:
  629. description: Text to set as description for this repository.
  630. """
  631. raise NotImplementedError(self.set_description)
  632. def get_rebase_state_manager(self):
  633. """Get the appropriate rebase state manager for this repository.
  634. Returns: RebaseStateManager instance
  635. """
  636. raise NotImplementedError(self.get_rebase_state_manager)
  637. def get_config_stack(self) -> "StackedConfig":
  638. """Return a config stack for this repository.
  639. This stack accesses the configuration for both this repository
  640. itself (.git/config) and the global configuration, which usually
  641. lives in ~/.gitconfig.
  642. Returns: `Config` instance for this repository
  643. """
  644. from .config import ConfigFile, StackedConfig
  645. local_config = self.get_config()
  646. backends: list[ConfigFile] = [local_config]
  647. if local_config.get_boolean((b"extensions",), b"worktreeconfig", False):
  648. backends.append(self.get_worktree_config())
  649. backends += StackedConfig.default_backends()
  650. return StackedConfig(backends, writable=local_config)
  651. def get_shallow(self) -> set[ObjectID]:
  652. """Get the set of shallow commits.
  653. Returns: Set of shallow commits.
  654. """
  655. f = self.get_named_file("shallow")
  656. if f is None:
  657. return set()
  658. with f:
  659. return {line.strip() for line in f}
  660. def update_shallow(self, new_shallow, new_unshallow) -> None:
  661. """Update the list of shallow objects.
  662. Args:
  663. new_shallow: Newly shallow objects
  664. new_unshallow: Newly no longer shallow objects
  665. """
  666. shallow = self.get_shallow()
  667. if new_shallow:
  668. shallow.update(new_shallow)
  669. if new_unshallow:
  670. shallow.difference_update(new_unshallow)
  671. if shallow:
  672. self._put_named_file("shallow", b"".join([sha + b"\n" for sha in shallow]))
  673. else:
  674. self._del_named_file("shallow")
  675. def get_peeled(self, ref: Ref) -> ObjectID:
  676. """Get the peeled value of a ref.
  677. Args:
  678. ref: The refname to peel.
  679. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  680. intermediate tags; if the original ref does not point to a tag,
  681. this will equal the original SHA1.
  682. """
  683. cached = self.refs.get_peeled(ref)
  684. if cached is not None:
  685. return cached
  686. return peel_sha(self.object_store, self.refs[ref])[1].id
  687. @property
  688. def notes(self) -> "Notes":
  689. """Access notes functionality for this repository.
  690. Returns:
  691. Notes object for accessing notes
  692. """
  693. from .notes import Notes
  694. return Notes(self.object_store, self.refs)
  695. def get_walker(self, include: Optional[list[bytes]] = None, **kwargs):
  696. """Obtain a walker for this repository.
  697. Args:
  698. include: Iterable of SHAs of commits to include along with their
  699. ancestors. Defaults to [HEAD]
  700. Keyword Args:
  701. exclude: Iterable of SHAs of commits to exclude along with their
  702. ancestors, overriding includes.
  703. order: ORDER_* constant specifying the order of results.
  704. Anything other than ORDER_DATE may result in O(n) memory usage.
  705. reverse: If True, reverse the order of output, requiring O(n)
  706. memory.
  707. max_entries: The maximum number of entries to yield, or None for
  708. no limit.
  709. paths: Iterable of file or subtree paths to show entries for.
  710. rename_detector: diff.RenameDetector object for detecting
  711. renames.
  712. follow: If True, follow path across renames/copies. Forces a
  713. default rename_detector.
  714. since: Timestamp to list commits after.
  715. until: Timestamp to list commits before.
  716. queue_cls: A class to use for a queue of commits, supporting the
  717. iterator protocol. The constructor takes a single argument, the
  718. Walker.
  719. Returns: A `Walker` object
  720. """
  721. from .walk import Walker
  722. if include is None:
  723. include = [self.head()]
  724. kwargs["get_parents"] = lambda commit: self.get_parents(commit.id, commit)
  725. return Walker(self.object_store, include, **kwargs)
  726. def __getitem__(self, name: Union[ObjectID, Ref]):
  727. """Retrieve a Git object by SHA1 or ref.
  728. Args:
  729. name: A Git object SHA1 or a ref name
  730. Returns: A `ShaFile` object, such as a Commit or Blob
  731. Raises:
  732. KeyError: when the specified ref or object does not exist
  733. """
  734. if not isinstance(name, bytes):
  735. raise TypeError(f"'name' must be bytestring, not {type(name).__name__:.80}")
  736. if len(name) in (20, 40):
  737. try:
  738. return self.object_store[name]
  739. except (KeyError, ValueError):
  740. pass
  741. try:
  742. return self.object_store[self.refs[name]]
  743. except RefFormatError as exc:
  744. raise KeyError(name) from exc
  745. def __contains__(self, name: bytes) -> bool:
  746. """Check if a specific Git object or ref is present.
  747. Args:
  748. name: Git object SHA1 or ref name
  749. """
  750. if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)):
  751. return name in self.object_store or name in self.refs
  752. else:
  753. return name in self.refs
  754. def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]) -> None:
  755. """Set a ref.
  756. Args:
  757. name: ref name
  758. value: Ref value - either a ShaFile object, or a hex sha
  759. """
  760. if name.startswith(b"refs/") or name == b"HEAD":
  761. if isinstance(value, ShaFile):
  762. self.refs[name] = value.id
  763. elif isinstance(value, bytes):
  764. self.refs[name] = value
  765. else:
  766. raise TypeError(value)
  767. else:
  768. raise ValueError(name)
  769. def __delitem__(self, name: bytes) -> None:
  770. """Remove a ref.
  771. Args:
  772. name: Name of the ref to remove
  773. """
  774. if name.startswith(b"refs/") or name == b"HEAD":
  775. del self.refs[name]
  776. else:
  777. raise ValueError(name)
  778. def _get_user_identity(
  779. self, config: "StackedConfig", kind: Optional[str] = None
  780. ) -> bytes:
  781. """Determine the identity to use for new commits."""
  782. warnings.warn(
  783. "use get_user_identity() rather than Repo._get_user_identity",
  784. DeprecationWarning,
  785. )
  786. return get_user_identity(config)
  787. def _add_graftpoints(self, updated_graftpoints: dict[bytes, list[bytes]]) -> None:
  788. """Add or modify graftpoints.
  789. Args:
  790. updated_graftpoints: Dict of commit shas to list of parent shas
  791. """
  792. # Simple validation
  793. for commit, parents in updated_graftpoints.items():
  794. for sha in [commit, *parents]:
  795. check_hexsha(sha, "Invalid graftpoint")
  796. self._graftpoints.update(updated_graftpoints)
  797. def _remove_graftpoints(self, to_remove: list[bytes] = []) -> None:
  798. """Remove graftpoints.
  799. Args:
  800. to_remove: List of commit shas
  801. """
  802. for sha in to_remove:
  803. del self._graftpoints[sha]
  804. def _read_heads(self, name):
  805. f = self.get_named_file(name)
  806. if f is None:
  807. return []
  808. with f:
  809. return [line.strip() for line in f.readlines() if line.strip()]
  810. def do_commit(
  811. self,
  812. message: Optional[bytes] = None,
  813. committer: Optional[bytes] = None,
  814. author: Optional[bytes] = None,
  815. commit_timestamp=None,
  816. commit_timezone=None,
  817. author_timestamp=None,
  818. author_timezone=None,
  819. tree: Optional[ObjectID] = None,
  820. encoding: Optional[bytes] = None,
  821. ref: Ref = b"HEAD",
  822. merge_heads: Optional[list[ObjectID]] = None,
  823. no_verify: bool = False,
  824. sign: bool = False,
  825. ):
  826. """Create a new commit.
  827. If not specified, committer and author default to
  828. get_user_identity(..., 'COMMITTER')
  829. and get_user_identity(..., 'AUTHOR') respectively.
  830. Args:
  831. message: Commit message
  832. committer: Committer fullname
  833. author: Author fullname
  834. commit_timestamp: Commit timestamp (defaults to now)
  835. commit_timezone: Commit timestamp timezone (defaults to GMT)
  836. author_timestamp: Author timestamp (defaults to commit
  837. timestamp)
  838. author_timezone: Author timestamp timezone
  839. (defaults to commit timestamp timezone)
  840. tree: SHA1 of the tree root to use (if not specified the
  841. current index will be committed).
  842. encoding: Encoding
  843. ref: Optional ref to commit to (defaults to current branch)
  844. merge_heads: Merge heads (defaults to .git/MERGE_HEAD)
  845. no_verify: Skip pre-commit and commit-msg hooks
  846. sign: GPG Sign the commit (bool, defaults to False,
  847. pass True to use default GPG key,
  848. pass a str containing Key ID to use a specific GPG key)
  849. Returns:
  850. New commit SHA1
  851. """
  852. try:
  853. if not no_verify:
  854. self.hooks["pre-commit"].execute()
  855. except HookError as exc:
  856. raise CommitError(exc) from exc
  857. except KeyError: # no hook defined, silent fallthrough
  858. pass
  859. c = Commit()
  860. if tree is None:
  861. index = self.open_index()
  862. c.tree = index.commit(self.object_store)
  863. else:
  864. if len(tree) != 40:
  865. raise ValueError("tree must be a 40-byte hex sha string")
  866. c.tree = tree
  867. config = self.get_config_stack()
  868. if merge_heads is None:
  869. merge_heads = self._read_heads("MERGE_HEAD")
  870. if committer is None:
  871. committer = get_user_identity(config, kind="COMMITTER")
  872. check_user_identity(committer)
  873. c.committer = committer
  874. if commit_timestamp is None:
  875. # FIXME: Support GIT_COMMITTER_DATE environment variable
  876. commit_timestamp = time.time()
  877. c.commit_time = int(commit_timestamp)
  878. if commit_timezone is None:
  879. # FIXME: Use current user timezone rather than UTC
  880. commit_timezone = 0
  881. c.commit_timezone = commit_timezone
  882. if author is None:
  883. author = get_user_identity(config, kind="AUTHOR")
  884. c.author = author
  885. check_user_identity(author)
  886. if author_timestamp is None:
  887. # FIXME: Support GIT_AUTHOR_DATE environment variable
  888. author_timestamp = commit_timestamp
  889. c.author_time = int(author_timestamp)
  890. if author_timezone is None:
  891. author_timezone = commit_timezone
  892. c.author_timezone = author_timezone
  893. if encoding is None:
  894. try:
  895. encoding = config.get(("i18n",), "commitEncoding")
  896. except KeyError:
  897. pass # No dice
  898. if encoding is not None:
  899. c.encoding = encoding
  900. if message is None:
  901. # FIXME: Try to read commit message from .git/MERGE_MSG
  902. raise ValueError("No commit message specified")
  903. try:
  904. if no_verify:
  905. c.message = message
  906. else:
  907. c.message = self.hooks["commit-msg"].execute(message)
  908. if c.message is None:
  909. c.message = message
  910. except HookError as exc:
  911. raise CommitError(exc) from exc
  912. except KeyError: # no hook defined, message not modified
  913. c.message = message
  914. # Check if we should sign the commit
  915. should_sign = sign
  916. if sign is None:
  917. # Check commit.gpgSign configuration when sign is not explicitly set
  918. config = self.get_config_stack()
  919. try:
  920. should_sign = config.get_boolean((b"commit",), b"gpgSign")
  921. except KeyError:
  922. should_sign = False # Default to not signing if no config
  923. keyid = sign if isinstance(sign, str) else None
  924. if ref is None:
  925. # Create a dangling commit
  926. c.parents = merge_heads
  927. if should_sign:
  928. c.sign(keyid)
  929. self.object_store.add_object(c)
  930. else:
  931. try:
  932. old_head = self.refs[ref]
  933. c.parents = [old_head, *merge_heads]
  934. if should_sign:
  935. c.sign(keyid)
  936. self.object_store.add_object(c)
  937. ok = self.refs.set_if_equals(
  938. ref,
  939. old_head,
  940. c.id,
  941. message=b"commit: " + message,
  942. committer=committer,
  943. timestamp=commit_timestamp,
  944. timezone=commit_timezone,
  945. )
  946. except KeyError:
  947. c.parents = merge_heads
  948. if should_sign:
  949. c.sign(keyid)
  950. self.object_store.add_object(c)
  951. ok = self.refs.add_if_new(
  952. ref,
  953. c.id,
  954. message=b"commit: " + message,
  955. committer=committer,
  956. timestamp=commit_timestamp,
  957. timezone=commit_timezone,
  958. )
  959. if not ok:
  960. # Fail if the atomic compare-and-swap failed, leaving the
  961. # commit and all its objects as garbage.
  962. raise CommitError(f"{ref!r} changed during commit")
  963. self._del_named_file("MERGE_HEAD")
  964. try:
  965. self.hooks["post-commit"].execute()
  966. except HookError as e: # silent failure
  967. warnings.warn(f"post-commit hook failed: {e}", UserWarning)
  968. except KeyError: # no hook defined, silent fallthrough
  969. pass
  970. # Trigger auto GC if needed
  971. from .gc import maybe_auto_gc
  972. maybe_auto_gc(self)
  973. return c.id
  974. def read_gitfile(f):
  975. """Read a ``.git`` file.
  976. The first line of the file should start with "gitdir: "
  977. Args:
  978. f: File-like object to read from
  979. Returns: A path
  980. """
  981. cs = f.read()
  982. if not cs.startswith("gitdir: "):
  983. raise ValueError("Expected file to start with 'gitdir: '")
  984. return cs[len("gitdir: ") :].rstrip("\n")
  985. class UnsupportedVersion(Exception):
  986. """Unsupported repository version."""
  987. def __init__(self, version) -> None:
  988. self.version = version
  989. class UnsupportedExtension(Exception):
  990. """Unsupported repository extension."""
  991. def __init__(self, extension) -> None:
  992. self.extension = extension
  993. class Repo(BaseRepo):
  994. """A git repository backed by local disk.
  995. To open an existing repository, call the constructor with
  996. the path of the repository.
  997. To create a new repository, use the Repo.init class method.
  998. Note that a repository object may hold on to resources such
  999. as file handles for performance reasons; call .close() to free
  1000. up those resources.
  1001. Attributes:
  1002. path: Path to the working copy (if it exists) or repository control
  1003. directory (if the repository is bare)
  1004. bare: Whether this is a bare repository
  1005. """
  1006. path: str
  1007. bare: bool
  1008. def __init__(
  1009. self,
  1010. root: Union[str, bytes, os.PathLike],
  1011. object_store: Optional[PackBasedObjectStore] = None,
  1012. bare: Optional[bool] = None,
  1013. ) -> None:
  1014. """Open a repository on disk.
  1015. Args:
  1016. root: Path to the repository's root.
  1017. object_store: ObjectStore to use; if omitted, we use the
  1018. repository's default object store
  1019. bare: True if this is a bare repository.
  1020. """
  1021. root = os.fspath(root)
  1022. if isinstance(root, bytes):
  1023. root = os.fsdecode(root)
  1024. hidden_path = os.path.join(root, CONTROLDIR)
  1025. if bare is None:
  1026. if os.path.isfile(hidden_path) or os.path.isdir(
  1027. os.path.join(hidden_path, OBJECTDIR)
  1028. ):
  1029. bare = False
  1030. elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir(
  1031. os.path.join(root, REFSDIR)
  1032. ):
  1033. bare = True
  1034. else:
  1035. raise NotGitRepository(
  1036. "No git repository was found at {path}".format(**dict(path=root))
  1037. )
  1038. self.bare = bare
  1039. if bare is False:
  1040. if os.path.isfile(hidden_path):
  1041. with open(hidden_path) as f:
  1042. path = read_gitfile(f)
  1043. self._controldir = os.path.join(root, path)
  1044. else:
  1045. self._controldir = hidden_path
  1046. else:
  1047. self._controldir = root
  1048. commondir = self.get_named_file(COMMONDIR)
  1049. if commondir is not None:
  1050. with commondir:
  1051. self._commondir = os.path.join(
  1052. self.controldir(),
  1053. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  1054. )
  1055. else:
  1056. self._commondir = self._controldir
  1057. self.path = root
  1058. # Initialize refs early so they're available for config condition matchers
  1059. self.refs = DiskRefsContainer(
  1060. self.commondir(), self._controldir, logger=self._write_reflog
  1061. )
  1062. config = self.get_config()
  1063. try:
  1064. repository_format_version = config.get("core", "repositoryformatversion")
  1065. format_version = (
  1066. 0
  1067. if repository_format_version is None
  1068. else int(repository_format_version)
  1069. )
  1070. except KeyError:
  1071. format_version = 0
  1072. if format_version not in (0, 1):
  1073. raise UnsupportedVersion(format_version)
  1074. # Track extensions we encounter
  1075. has_reftable_extension = False
  1076. for extension, value in config.items((b"extensions",)):
  1077. if extension.lower() == b"refstorage":
  1078. if value == b"reftable":
  1079. has_reftable_extension = True
  1080. else:
  1081. raise UnsupportedExtension(f"refStorage = {value.decode()}")
  1082. elif extension.lower() not in (b"worktreeconfig",):
  1083. raise UnsupportedExtension(extension)
  1084. if object_store is None:
  1085. object_store = DiskObjectStore.from_config(
  1086. os.path.join(self.commondir(), OBJECTDIR), config
  1087. )
  1088. # Use reftable if extension is configured
  1089. if has_reftable_extension:
  1090. from .reftable import ReftableRefsContainer
  1091. self.refs = ReftableRefsContainer(self.commondir())
  1092. BaseRepo.__init__(self, object_store, self.refs)
  1093. self._graftpoints = {}
  1094. graft_file = self.get_named_file(
  1095. os.path.join("info", "grafts"), basedir=self.commondir()
  1096. )
  1097. if graft_file:
  1098. with graft_file:
  1099. self._graftpoints.update(parse_graftpoints(graft_file))
  1100. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  1101. if graft_file:
  1102. with graft_file:
  1103. self._graftpoints.update(parse_graftpoints(graft_file))
  1104. self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir())
  1105. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  1106. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  1107. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  1108. def _write_reflog(
  1109. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  1110. ) -> None:
  1111. from .reflog import format_reflog_line
  1112. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  1113. try:
  1114. os.makedirs(os.path.dirname(path))
  1115. except FileExistsError:
  1116. pass
  1117. if committer is None:
  1118. config = self.get_config_stack()
  1119. committer = get_user_identity(config)
  1120. check_user_identity(committer)
  1121. if timestamp is None:
  1122. timestamp = int(time.time())
  1123. if timezone is None:
  1124. timezone = 0 # FIXME
  1125. with open(path, "ab") as f:
  1126. f.write(
  1127. format_reflog_line(
  1128. old_sha, new_sha, committer, timestamp, timezone, message
  1129. )
  1130. + b"\n"
  1131. )
  1132. @classmethod
  1133. def discover(cls, start="."):
  1134. """Iterate parent directories to discover a repository.
  1135. Return a Repo object for the first parent directory that looks like a
  1136. Git repository.
  1137. Args:
  1138. start: The directory to start discovery from (defaults to '.')
  1139. """
  1140. remaining = True
  1141. path = os.path.abspath(start)
  1142. while remaining:
  1143. try:
  1144. return cls(path)
  1145. except NotGitRepository:
  1146. path, remaining = os.path.split(path)
  1147. raise NotGitRepository(
  1148. "No git repository was found at {path}".format(**dict(path=start))
  1149. )
  1150. def controldir(self):
  1151. """Return the path of the control directory."""
  1152. return self._controldir
  1153. def commondir(self):
  1154. """Return the path of the common directory.
  1155. For a main working tree, it is identical to controldir().
  1156. For a linked working tree, it is the control directory of the
  1157. main working tree.
  1158. """
  1159. return self._commondir
  1160. def _determine_file_mode(self):
  1161. """Probe the file-system to determine whether permissions can be trusted.
  1162. Returns: True if permissions can be trusted, False otherwise.
  1163. """
  1164. fname = os.path.join(self.path, ".probe-permissions")
  1165. with open(fname, "w") as f:
  1166. f.write("")
  1167. st1 = os.lstat(fname)
  1168. try:
  1169. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  1170. except PermissionError:
  1171. return False
  1172. st2 = os.lstat(fname)
  1173. os.unlink(fname)
  1174. mode_differs = st1.st_mode != st2.st_mode
  1175. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1176. return mode_differs and st2_has_exec
  1177. def _determine_symlinks(self):
  1178. """Probe the filesystem to determine whether symlinks can be created.
  1179. Returns: True if symlinks can be created, False otherwise.
  1180. """
  1181. # TODO(jelmer): Actually probe disk / look at filesystem
  1182. return sys.platform != "win32"
  1183. def _put_named_file(self, path, contents) -> None:
  1184. """Write a file to the control dir with the given name and contents.
  1185. Args:
  1186. path: The path to the file, relative to the control dir.
  1187. contents: A string to write to the file.
  1188. """
  1189. path = path.lstrip(os.path.sep)
  1190. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1191. f.write(contents)
  1192. def _del_named_file(self, path) -> None:
  1193. try:
  1194. os.unlink(os.path.join(self.controldir(), path))
  1195. except FileNotFoundError:
  1196. return
  1197. def get_named_file(self, path, basedir=None):
  1198. """Get a file from the control dir with a specific name.
  1199. Although the filename should be interpreted as a filename relative to
  1200. the control dir in a disk-based Repo, the object returned need not be
  1201. pointing to a file in that location.
  1202. Args:
  1203. path: The path to the file, relative to the control dir.
  1204. basedir: Optional argument that specifies an alternative to the
  1205. control dir.
  1206. Returns: An open file object, or None if the file does not exist.
  1207. """
  1208. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1209. # the dumb web serving code.
  1210. if basedir is None:
  1211. basedir = self.controldir()
  1212. path = path.lstrip(os.path.sep)
  1213. try:
  1214. return open(os.path.join(basedir, path), "rb")
  1215. except FileNotFoundError:
  1216. return None
  1217. def index_path(self):
  1218. """Return path to the index file."""
  1219. return os.path.join(self.controldir(), INDEX_FILENAME)
  1220. def open_index(self) -> "Index":
  1221. """Open the index for this repository.
  1222. Raises:
  1223. NoIndexPresent: If no index is present
  1224. Returns: The matching `Index`
  1225. """
  1226. from .index import Index
  1227. if not self.has_index():
  1228. raise NoIndexPresent
  1229. # Check for manyFiles feature configuration
  1230. config = self.get_config_stack()
  1231. many_files = config.get_boolean(b"feature", b"manyFiles", False)
  1232. skip_hash = False
  1233. index_version = None
  1234. if many_files:
  1235. # When feature.manyFiles is enabled, set index.version=4 and index.skipHash=true
  1236. try:
  1237. index_version_str = config.get(b"index", b"version")
  1238. index_version = int(index_version_str)
  1239. except KeyError:
  1240. index_version = 4 # Default to version 4 for manyFiles
  1241. skip_hash = config.get_boolean(b"index", b"skipHash", True)
  1242. else:
  1243. # Check for explicit index settings
  1244. try:
  1245. index_version_str = config.get(b"index", b"version")
  1246. index_version = int(index_version_str)
  1247. except KeyError:
  1248. index_version = None
  1249. skip_hash = config.get_boolean(b"index", b"skipHash", False)
  1250. return Index(self.index_path(), skip_hash=skip_hash, version=index_version)
  1251. def has_index(self) -> bool:
  1252. """Check if an index is present."""
  1253. # Bare repos must never have index files; non-bare repos may have a
  1254. # missing index file, which is treated as empty.
  1255. return not self.bare
  1256. def stage(
  1257. self,
  1258. fs_paths: Union[
  1259. str, bytes, os.PathLike, Iterable[Union[str, bytes, os.PathLike]]
  1260. ],
  1261. ) -> None:
  1262. """Stage a set of paths.
  1263. Args:
  1264. fs_paths: List of paths, relative to the repository path
  1265. """
  1266. root_path_bytes = os.fsencode(self.path)
  1267. if isinstance(fs_paths, (str, bytes, os.PathLike)):
  1268. fs_paths = [fs_paths]
  1269. fs_paths = list(fs_paths)
  1270. from .index import (
  1271. _fs_to_tree_path,
  1272. blob_from_path_and_stat,
  1273. index_entry_from_directory,
  1274. index_entry_from_stat,
  1275. )
  1276. index = self.open_index()
  1277. blob_normalizer = self.get_blob_normalizer()
  1278. for fs_path in fs_paths:
  1279. if not isinstance(fs_path, bytes):
  1280. fs_path = os.fsencode(fs_path)
  1281. if os.path.isabs(fs_path):
  1282. raise ValueError(
  1283. f"path {fs_path!r} should be relative to "
  1284. "repository root, not absolute"
  1285. )
  1286. tree_path = _fs_to_tree_path(fs_path)
  1287. full_path = os.path.join(root_path_bytes, fs_path)
  1288. try:
  1289. st = os.lstat(full_path)
  1290. except OSError:
  1291. # File no longer exists
  1292. try:
  1293. del index[tree_path]
  1294. except KeyError:
  1295. pass # already removed
  1296. else:
  1297. if stat.S_ISDIR(st.st_mode):
  1298. entry = index_entry_from_directory(st, full_path)
  1299. if entry:
  1300. index[tree_path] = entry
  1301. else:
  1302. try:
  1303. del index[tree_path]
  1304. except KeyError:
  1305. pass
  1306. elif not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1307. try:
  1308. del index[tree_path]
  1309. except KeyError:
  1310. pass
  1311. else:
  1312. blob = blob_from_path_and_stat(full_path, st)
  1313. blob = blob_normalizer.checkin_normalize(blob, fs_path)
  1314. self.object_store.add_object(blob)
  1315. index[tree_path] = index_entry_from_stat(st, blob.id)
  1316. index.write()
  1317. def unstage(self, fs_paths: list[str]) -> None:
  1318. """Unstage specific file in the index
  1319. Args:
  1320. fs_paths: a list of files to unstage,
  1321. relative to the repository path.
  1322. """
  1323. from .index import IndexEntry, _fs_to_tree_path
  1324. index = self.open_index()
  1325. try:
  1326. tree_id = self[b"HEAD"].tree
  1327. except KeyError:
  1328. # no head mean no commit in the repo
  1329. for fs_path in fs_paths:
  1330. tree_path = _fs_to_tree_path(fs_path)
  1331. del index[tree_path]
  1332. index.write()
  1333. return
  1334. for fs_path in fs_paths:
  1335. tree_path = _fs_to_tree_path(fs_path)
  1336. try:
  1337. tree = self.object_store[tree_id]
  1338. assert isinstance(tree, Tree)
  1339. tree_entry = tree.lookup_path(self.object_store.__getitem__, tree_path)
  1340. except KeyError:
  1341. # if tree_entry didn't exist, this file was being added, so
  1342. # remove index entry
  1343. try:
  1344. del index[tree_path]
  1345. continue
  1346. except KeyError as exc:
  1347. raise KeyError(f"file '{tree_path.decode()}' not in index") from exc
  1348. st = None
  1349. try:
  1350. st = os.lstat(os.path.join(self.path, fs_path))
  1351. except FileNotFoundError:
  1352. pass
  1353. index_entry = IndexEntry(
  1354. ctime=(self[b"HEAD"].commit_time, 0),
  1355. mtime=(self[b"HEAD"].commit_time, 0),
  1356. dev=st.st_dev if st else 0,
  1357. ino=st.st_ino if st else 0,
  1358. mode=tree_entry[0],
  1359. uid=st.st_uid if st else 0,
  1360. gid=st.st_gid if st else 0,
  1361. size=len(self[tree_entry[1]].data),
  1362. sha=tree_entry[1],
  1363. flags=0,
  1364. extended_flags=0,
  1365. )
  1366. index[tree_path] = index_entry
  1367. index.write()
  1368. def clone(
  1369. self,
  1370. target_path,
  1371. *,
  1372. mkdir=True,
  1373. bare=False,
  1374. origin=b"origin",
  1375. checkout=None,
  1376. branch=None,
  1377. progress=None,
  1378. depth: Optional[int] = None,
  1379. symlinks=None,
  1380. ) -> "Repo":
  1381. """Clone this repository.
  1382. Args:
  1383. target_path: Target path
  1384. mkdir: Create the target directory
  1385. bare: Whether to create a bare repository
  1386. checkout: Whether or not to check-out HEAD after cloning
  1387. origin: Base name for refs in target repository
  1388. cloned from this repository
  1389. branch: Optional branch or tag to be used as HEAD in the new repository
  1390. instead of this repository's HEAD.
  1391. progress: Optional progress function
  1392. depth: Depth at which to fetch
  1393. symlinks: Symlinks setting (default to autodetect)
  1394. Returns: Created repository as `Repo`
  1395. """
  1396. encoded_path = os.fsencode(self.path)
  1397. if mkdir:
  1398. os.mkdir(target_path)
  1399. try:
  1400. if not bare:
  1401. target = Repo.init(target_path, symlinks=symlinks)
  1402. if checkout is None:
  1403. checkout = True
  1404. else:
  1405. if checkout:
  1406. raise ValueError("checkout and bare are incompatible")
  1407. target = Repo.init_bare(target_path)
  1408. try:
  1409. target_config = target.get_config()
  1410. target_config.set((b"remote", origin), b"url", encoded_path)
  1411. target_config.set(
  1412. (b"remote", origin),
  1413. b"fetch",
  1414. b"+refs/heads/*:refs/remotes/" + origin + b"/*",
  1415. )
  1416. target_config.write_to_path()
  1417. ref_message = b"clone: from " + encoded_path
  1418. self.fetch(target, depth=depth)
  1419. target.refs.import_refs(
  1420. b"refs/remotes/" + origin,
  1421. self.refs.as_dict(b"refs/heads"),
  1422. message=ref_message,
  1423. )
  1424. target.refs.import_refs(
  1425. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1426. )
  1427. head_chain, origin_sha = self.refs.follow(b"HEAD")
  1428. origin_head = head_chain[-1] if head_chain else None
  1429. if origin_sha and not origin_head:
  1430. # set detached HEAD
  1431. target.refs[b"HEAD"] = origin_sha
  1432. else:
  1433. _set_origin_head(target.refs, origin, origin_head)
  1434. head_ref = _set_default_branch(
  1435. target.refs, origin, origin_head, branch, ref_message
  1436. )
  1437. # Update target head
  1438. if head_ref:
  1439. head = _set_head(target.refs, head_ref, ref_message)
  1440. else:
  1441. head = None
  1442. if checkout and head is not None:
  1443. target.reset_index()
  1444. except BaseException:
  1445. target.close()
  1446. raise
  1447. except BaseException:
  1448. if mkdir:
  1449. import shutil
  1450. shutil.rmtree(target_path)
  1451. raise
  1452. return target
  1453. def reset_index(self, tree: Optional[bytes] = None):
  1454. """Reset the index back to a specific tree.
  1455. Args:
  1456. tree: Tree SHA to reset to, None for current HEAD tree.
  1457. """
  1458. from .index import (
  1459. build_index_from_tree,
  1460. symlink,
  1461. validate_path_element_default,
  1462. validate_path_element_ntfs,
  1463. )
  1464. if tree is None:
  1465. head = self[b"HEAD"]
  1466. if isinstance(head, Tag):
  1467. _cls, obj = head.object
  1468. head = self.get_object(obj)
  1469. tree = head.tree
  1470. config = self.get_config()
  1471. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1472. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1473. validate_path_element = validate_path_element_ntfs
  1474. else:
  1475. validate_path_element = validate_path_element_default
  1476. if config.get_boolean(b"core", b"symlinks", True):
  1477. symlink_fn = symlink
  1478. else:
  1479. def symlink_fn(source, target) -> None: # type: ignore
  1480. with open(
  1481. target, "w" + ("b" if isinstance(source, bytes) else "")
  1482. ) as f:
  1483. f.write(source)
  1484. blob_normalizer = self.get_blob_normalizer()
  1485. return build_index_from_tree(
  1486. self.path,
  1487. self.index_path(),
  1488. self.object_store,
  1489. tree,
  1490. honor_filemode=honor_filemode,
  1491. validate_path_element=validate_path_element,
  1492. symlink_fn=symlink_fn,
  1493. blob_normalizer=blob_normalizer,
  1494. )
  1495. def _get_config_condition_matchers(self) -> dict[str, "ConditionMatcher"]:
  1496. """Get condition matchers for includeIf conditions.
  1497. Returns a dict of condition prefix to matcher function.
  1498. """
  1499. from pathlib import Path
  1500. from .config import ConditionMatcher, match_glob_pattern
  1501. # Add gitdir matchers
  1502. def match_gitdir(pattern: str, case_sensitive: bool = True) -> bool:
  1503. # Handle relative patterns (starting with ./)
  1504. if pattern.startswith("./"):
  1505. # Can't handle relative patterns without config directory context
  1506. return False
  1507. # Normalize repository path
  1508. try:
  1509. repo_path = str(Path(self._controldir).resolve())
  1510. except (OSError, ValueError):
  1511. return False
  1512. # Expand ~ in pattern and normalize
  1513. pattern = os.path.expanduser(pattern)
  1514. # Normalize pattern following Git's rules
  1515. pattern = pattern.replace("\\", "/")
  1516. if not pattern.startswith(("~/", "./", "/", "**")):
  1517. # Check for Windows absolute path
  1518. if len(pattern) >= 2 and pattern[1] == ":":
  1519. pass
  1520. else:
  1521. pattern = "**/" + pattern
  1522. if pattern.endswith("/"):
  1523. pattern = pattern + "**"
  1524. # Use the existing _match_gitdir_pattern function
  1525. from .config import _match_gitdir_pattern
  1526. pattern_bytes = pattern.encode("utf-8", errors="replace")
  1527. repo_path_bytes = repo_path.encode("utf-8", errors="replace")
  1528. return _match_gitdir_pattern(
  1529. repo_path_bytes, pattern_bytes, ignorecase=not case_sensitive
  1530. )
  1531. # Add onbranch matcher
  1532. def match_onbranch(pattern: str) -> bool:
  1533. try:
  1534. # Get the current branch using refs
  1535. ref_chain, _ = self.refs.follow(b"HEAD")
  1536. head_ref = ref_chain[-1] # Get the final resolved ref
  1537. except KeyError:
  1538. pass
  1539. else:
  1540. if head_ref and head_ref.startswith(b"refs/heads/"):
  1541. # Extract branch name from ref
  1542. branch = head_ref[11:].decode("utf-8", errors="replace")
  1543. return match_glob_pattern(branch, pattern)
  1544. return False
  1545. matchers: dict[str, ConditionMatcher] = {
  1546. "onbranch:": match_onbranch,
  1547. "gitdir:": lambda pattern: match_gitdir(pattern, True),
  1548. "gitdir/i:": lambda pattern: match_gitdir(pattern, False),
  1549. }
  1550. return matchers
  1551. def get_worktree_config(self) -> "ConfigFile":
  1552. from .config import ConfigFile
  1553. path = os.path.join(self.commondir(), "config.worktree")
  1554. try:
  1555. # Pass condition matchers for includeIf evaluation
  1556. condition_matchers = self._get_config_condition_matchers()
  1557. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1558. except FileNotFoundError:
  1559. cf = ConfigFile()
  1560. cf.path = path
  1561. return cf
  1562. def get_config(self) -> "ConfigFile":
  1563. """Retrieve the config object.
  1564. Returns: `ConfigFile` object for the ``.git/config`` file.
  1565. """
  1566. from .config import ConfigFile
  1567. path = os.path.join(self._commondir, "config")
  1568. try:
  1569. # Pass condition matchers for includeIf evaluation
  1570. condition_matchers = self._get_config_condition_matchers()
  1571. return ConfigFile.from_path(path, condition_matchers=condition_matchers)
  1572. except FileNotFoundError:
  1573. ret = ConfigFile()
  1574. ret.path = path
  1575. return ret
  1576. def get_rebase_state_manager(self):
  1577. """Get the appropriate rebase state manager for this repository.
  1578. Returns: DiskRebaseStateManager instance
  1579. """
  1580. import os
  1581. from .rebase import DiskRebaseStateManager
  1582. path = os.path.join(self.controldir(), "rebase-merge")
  1583. return DiskRebaseStateManager(path)
  1584. def get_description(self):
  1585. """Retrieve the description of this repository.
  1586. Returns: A string describing the repository or None.
  1587. """
  1588. path = os.path.join(self._controldir, "description")
  1589. try:
  1590. with GitFile(path, "rb") as f:
  1591. return f.read()
  1592. except FileNotFoundError:
  1593. return None
  1594. def __repr__(self) -> str:
  1595. return f"<Repo at {self.path!r}>"
  1596. def set_description(self, description) -> None:
  1597. """Set the description for this repository.
  1598. Args:
  1599. description: Text to set as description for this repository.
  1600. """
  1601. self._put_named_file("description", description)
  1602. @classmethod
  1603. def _init_maybe_bare(
  1604. cls,
  1605. path: Union[str, bytes, os.PathLike],
  1606. controldir: Union[str, bytes, os.PathLike],
  1607. bare,
  1608. object_store=None,
  1609. config=None,
  1610. default_branch=None,
  1611. symlinks: Optional[bool] = None,
  1612. format: Optional[int] = None,
  1613. ):
  1614. path = os.fspath(path)
  1615. if isinstance(path, bytes):
  1616. path = os.fsdecode(path)
  1617. controldir = os.fspath(controldir)
  1618. if isinstance(controldir, bytes):
  1619. controldir = os.fsdecode(controldir)
  1620. for d in BASE_DIRECTORIES:
  1621. os.mkdir(os.path.join(controldir, *d))
  1622. if object_store is None:
  1623. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1624. ret = cls(path, bare=bare, object_store=object_store)
  1625. if default_branch is None:
  1626. if config is None:
  1627. from .config import StackedConfig
  1628. config = StackedConfig.default()
  1629. try:
  1630. default_branch = config.get("init", "defaultBranch")
  1631. except KeyError:
  1632. default_branch = DEFAULT_BRANCH
  1633. ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch)
  1634. ret._init_files(bare=bare, symlinks=symlinks, format=format)
  1635. return ret
  1636. @classmethod
  1637. def init(
  1638. cls,
  1639. path: Union[str, bytes, os.PathLike],
  1640. *,
  1641. mkdir: bool = False,
  1642. config=None,
  1643. default_branch=None,
  1644. symlinks: Optional[bool] = None,
  1645. format: Optional[int] = None,
  1646. ) -> "Repo":
  1647. """Create a new repository.
  1648. Args:
  1649. path: Path in which to create the repository
  1650. mkdir: Whether to create the directory
  1651. format: Repository format version (defaults to 0)
  1652. Returns: `Repo` instance
  1653. """
  1654. path = os.fspath(path)
  1655. if isinstance(path, bytes):
  1656. path = os.fsdecode(path)
  1657. if mkdir:
  1658. os.mkdir(path)
  1659. controldir = os.path.join(path, CONTROLDIR)
  1660. os.mkdir(controldir)
  1661. _set_filesystem_hidden(controldir)
  1662. return cls._init_maybe_bare(
  1663. path,
  1664. controldir,
  1665. False,
  1666. config=config,
  1667. default_branch=default_branch,
  1668. symlinks=symlinks,
  1669. format=format,
  1670. )
  1671. @classmethod
  1672. def _init_new_working_directory(
  1673. cls,
  1674. path: Union[str, bytes, os.PathLike],
  1675. main_repo,
  1676. identifier=None,
  1677. mkdir=False,
  1678. ):
  1679. """Create a new working directory linked to a repository.
  1680. Args:
  1681. path: Path in which to create the working tree.
  1682. main_repo: Main repository to reference
  1683. identifier: Worktree identifier
  1684. mkdir: Whether to create the directory
  1685. Returns: `Repo` instance
  1686. """
  1687. path = os.fspath(path)
  1688. if isinstance(path, bytes):
  1689. path = os.fsdecode(path)
  1690. if mkdir:
  1691. os.mkdir(path)
  1692. if identifier is None:
  1693. identifier = os.path.basename(path)
  1694. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  1695. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1696. gitdirfile = os.path.join(path, CONTROLDIR)
  1697. with open(gitdirfile, "wb") as f:
  1698. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1699. try:
  1700. os.mkdir(main_worktreesdir)
  1701. except FileExistsError:
  1702. pass
  1703. try:
  1704. os.mkdir(worktree_controldir)
  1705. except FileExistsError:
  1706. pass
  1707. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1708. f.write(os.fsencode(gitdirfile) + b"\n")
  1709. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1710. f.write(b"../..\n")
  1711. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1712. f.write(main_repo.head() + b"\n")
  1713. r = cls(path)
  1714. r.reset_index()
  1715. return r
  1716. @classmethod
  1717. def init_bare(
  1718. cls,
  1719. path: Union[str, bytes, os.PathLike],
  1720. *,
  1721. mkdir=False,
  1722. object_store=None,
  1723. config=None,
  1724. default_branch=None,
  1725. format: Optional[int] = None,
  1726. ):
  1727. """Create a new bare repository.
  1728. ``path`` should already exist and be an empty directory.
  1729. Args:
  1730. path: Path to create bare repository in
  1731. format: Repository format version (defaults to 0)
  1732. Returns: a `Repo` instance
  1733. """
  1734. path = os.fspath(path)
  1735. if isinstance(path, bytes):
  1736. path = os.fsdecode(path)
  1737. if mkdir:
  1738. os.mkdir(path)
  1739. return cls._init_maybe_bare(
  1740. path,
  1741. path,
  1742. True,
  1743. object_store=object_store,
  1744. config=config,
  1745. default_branch=default_branch,
  1746. format=format,
  1747. )
  1748. create = init_bare
  1749. def close(self) -> None:
  1750. """Close any files opened by this repository."""
  1751. self.object_store.close()
  1752. def __enter__(self):
  1753. return self
  1754. def __exit__(self, exc_type, exc_val, exc_tb):
  1755. self.close()
  1756. def get_blob_normalizer(self):
  1757. """Return a BlobNormalizer object."""
  1758. # TODO Parse the git attributes files
  1759. git_attributes = {}
  1760. config_stack = self.get_config_stack()
  1761. try:
  1762. head_sha = self.refs[b"HEAD"]
  1763. # Peel tags to get the underlying commit
  1764. _, obj = peel_sha(self.object_store, head_sha)
  1765. tree = obj.tree
  1766. return TreeBlobNormalizer(
  1767. config_stack,
  1768. git_attributes,
  1769. self.object_store,
  1770. tree,
  1771. )
  1772. except KeyError:
  1773. return BlobNormalizer(config_stack, git_attributes)
  1774. def _sparse_checkout_file_path(self) -> str:
  1775. """Return the path of the sparse-checkout file in this repo's control dir."""
  1776. return os.path.join(self.controldir(), "info", "sparse-checkout")
  1777. def configure_for_cone_mode(self) -> None:
  1778. """Ensure the repository is configured for cone-mode sparse-checkout."""
  1779. config = self.get_config()
  1780. config.set((b"core",), b"sparseCheckout", b"true")
  1781. config.set((b"core",), b"sparseCheckoutCone", b"true")
  1782. config.write_to_path()
  1783. def infer_cone_mode(self) -> bool:
  1784. """Return True if 'core.sparseCheckoutCone' is set to 'true' in config, else False."""
  1785. config = self.get_config()
  1786. try:
  1787. sc_cone = config.get((b"core",), b"sparseCheckoutCone")
  1788. return sc_cone == b"true"
  1789. except KeyError:
  1790. # If core.sparseCheckoutCone is not set, default to False
  1791. return False
  1792. def get_sparse_checkout_patterns(self) -> list[str]:
  1793. """Return a list of sparse-checkout patterns from info/sparse-checkout.
  1794. Returns:
  1795. A list of patterns. Returns an empty list if the file is missing.
  1796. """
  1797. path = self._sparse_checkout_file_path()
  1798. try:
  1799. with open(path, encoding="utf-8") as f:
  1800. return [line.strip() for line in f if line.strip()]
  1801. except FileNotFoundError:
  1802. return []
  1803. def set_sparse_checkout_patterns(self, patterns: list[str]) -> None:
  1804. """Write the given sparse-checkout patterns into info/sparse-checkout.
  1805. Creates the info/ directory if it does not exist.
  1806. Args:
  1807. patterns: A list of gitignore-style patterns to store.
  1808. """
  1809. info_dir = os.path.join(self.controldir(), "info")
  1810. os.makedirs(info_dir, exist_ok=True)
  1811. path = self._sparse_checkout_file_path()
  1812. with open(path, "w", encoding="utf-8") as f:
  1813. for pat in patterns:
  1814. f.write(pat + "\n")
  1815. def set_cone_mode_patterns(self, dirs: Union[list[str], None] = None) -> None:
  1816. """Write the given cone-mode directory patterns into info/sparse-checkout.
  1817. For each directory to include, add an inclusion line that "undoes" the prior
  1818. ``!/*/`` 'exclude' that re-includes that directory and everything under it.
  1819. Never add the same line twice.
  1820. """
  1821. patterns = ["/*", "!/*/"]
  1822. if dirs:
  1823. for d in dirs:
  1824. d = d.strip("/")
  1825. line = f"/{d}/"
  1826. if d and line not in patterns:
  1827. patterns.append(line)
  1828. self.set_sparse_checkout_patterns(patterns)
  1829. class MemoryRepo(BaseRepo):
  1830. """Repo that stores refs, objects, and named files in memory.
  1831. MemoryRepos are always bare: they have no working tree and no index, since
  1832. those have a stronger dependency on the filesystem.
  1833. """
  1834. def __init__(self) -> None:
  1835. """Create a new repository in memory."""
  1836. from .config import ConfigFile
  1837. self._reflog: list[Any] = []
  1838. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1839. BaseRepo.__init__(self, MemoryObjectStore(), refs_container) # type: ignore
  1840. self._named_files: dict[str, bytes] = {}
  1841. self.bare = True
  1842. self._config = ConfigFile()
  1843. self._description = None
  1844. def _append_reflog(self, *args) -> None:
  1845. self._reflog.append(args)
  1846. def set_description(self, description) -> None:
  1847. self._description = description
  1848. def get_description(self):
  1849. return self._description
  1850. def _determine_file_mode(self):
  1851. """Probe the file-system to determine whether permissions can be trusted.
  1852. Returns: True if permissions can be trusted, False otherwise.
  1853. """
  1854. return sys.platform != "win32"
  1855. def _determine_symlinks(self):
  1856. """Probe the file-system to determine whether permissions can be trusted.
  1857. Returns: True if permissions can be trusted, False otherwise.
  1858. """
  1859. return sys.platform != "win32"
  1860. def _put_named_file(self, path, contents) -> None:
  1861. """Write a file to the control dir with the given name and contents.
  1862. Args:
  1863. path: The path to the file, relative to the control dir.
  1864. contents: A string to write to the file.
  1865. """
  1866. self._named_files[path] = contents
  1867. def _del_named_file(self, path) -> None:
  1868. try:
  1869. del self._named_files[path]
  1870. except KeyError:
  1871. pass
  1872. def get_named_file(self, path, basedir=None):
  1873. """Get a file from the control dir with a specific name.
  1874. Although the filename should be interpreted as a filename relative to
  1875. the control dir in a disk-baked Repo, the object returned need not be
  1876. pointing to a file in that location.
  1877. Args:
  1878. path: The path to the file, relative to the control dir.
  1879. Returns: An open file object, or None if the file does not exist.
  1880. """
  1881. contents = self._named_files.get(path, None)
  1882. if contents is None:
  1883. return None
  1884. return BytesIO(contents)
  1885. def open_index(self) -> "Index":
  1886. """Fail to open index for this repo, since it is bare.
  1887. Raises:
  1888. NoIndexPresent: Raised when no index is present
  1889. """
  1890. raise NoIndexPresent
  1891. def get_config(self):
  1892. """Retrieve the config object.
  1893. Returns: `ConfigFile` object.
  1894. """
  1895. return self._config
  1896. def get_rebase_state_manager(self):
  1897. """Get the appropriate rebase state manager for this repository.
  1898. Returns: MemoryRebaseStateManager instance
  1899. """
  1900. from .rebase import MemoryRebaseStateManager
  1901. return MemoryRebaseStateManager(self)
  1902. @classmethod
  1903. def init_bare(cls, objects, refs, format: Optional[int] = None):
  1904. """Create a new bare repository in memory.
  1905. Args:
  1906. objects: Objects for the new repository,
  1907. as iterable
  1908. refs: Refs as dictionary, mapping names
  1909. to object SHA1s
  1910. format: Repository format version (defaults to 0)
  1911. """
  1912. ret = cls()
  1913. for obj in objects:
  1914. ret.object_store.add_object(obj)
  1915. for refname, sha in refs.items():
  1916. ret.refs.add_if_new(refname, sha)
  1917. ret._init_files(bare=True, format=format)
  1918. return ret