repo.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  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 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. keyid = sign if isinstance(sign, str) else None
  915. if ref is None:
  916. # Create a dangling commit
  917. c.parents = merge_heads
  918. if sign:
  919. c.sign(keyid)
  920. self.object_store.add_object(c)
  921. else:
  922. try:
  923. old_head = self.refs[ref]
  924. c.parents = [old_head, *merge_heads]
  925. if sign:
  926. c.sign(keyid)
  927. self.object_store.add_object(c)
  928. ok = self.refs.set_if_equals(
  929. ref,
  930. old_head,
  931. c.id,
  932. message=b"commit: " + message,
  933. committer=committer,
  934. timestamp=commit_timestamp,
  935. timezone=commit_timezone,
  936. )
  937. except KeyError:
  938. c.parents = merge_heads
  939. if sign:
  940. c.sign(keyid)
  941. self.object_store.add_object(c)
  942. ok = self.refs.add_if_new(
  943. ref,
  944. c.id,
  945. message=b"commit: " + message,
  946. committer=committer,
  947. timestamp=commit_timestamp,
  948. timezone=commit_timezone,
  949. )
  950. if not ok:
  951. # Fail if the atomic compare-and-swap failed, leaving the
  952. # commit and all its objects as garbage.
  953. raise CommitError(f"{ref!r} changed during commit")
  954. self._del_named_file("MERGE_HEAD")
  955. try:
  956. self.hooks["post-commit"].execute()
  957. except HookError as e: # silent failure
  958. warnings.warn(f"post-commit hook failed: {e}", UserWarning)
  959. except KeyError: # no hook defined, silent fallthrough
  960. pass
  961. return c.id
  962. def read_gitfile(f):
  963. """Read a ``.git`` file.
  964. The first line of the file should start with "gitdir: "
  965. Args:
  966. f: File-like object to read from
  967. Returns: A path
  968. """
  969. cs = f.read()
  970. if not cs.startswith("gitdir: "):
  971. raise ValueError("Expected file to start with 'gitdir: '")
  972. return cs[len("gitdir: ") :].rstrip("\n")
  973. class UnsupportedVersion(Exception):
  974. """Unsupported repository version."""
  975. def __init__(self, version) -> None:
  976. self.version = version
  977. class UnsupportedExtension(Exception):
  978. """Unsupported repository extension."""
  979. def __init__(self, extension) -> None:
  980. self.extension = extension
  981. class Repo(BaseRepo):
  982. """A git repository backed by local disk.
  983. To open an existing repository, call the constructor with
  984. the path of the repository.
  985. To create a new repository, use the Repo.init class method.
  986. Note that a repository object may hold on to resources such
  987. as file handles for performance reasons; call .close() to free
  988. up those resources.
  989. Attributes:
  990. path: Path to the working copy (if it exists) or repository control
  991. directory (if the repository is bare)
  992. bare: Whether this is a bare repository
  993. """
  994. path: str
  995. bare: bool
  996. def __init__(
  997. self,
  998. root: Union[str, bytes, os.PathLike],
  999. object_store: Optional[PackBasedObjectStore] = None,
  1000. bare: Optional[bool] = None,
  1001. ) -> None:
  1002. """Open a repository on disk.
  1003. Args:
  1004. root: Path to the repository's root.
  1005. object_store: ObjectStore to use; if omitted, we use the
  1006. repository's default object store
  1007. bare: True if this is a bare repository.
  1008. """
  1009. root = os.fspath(root)
  1010. if isinstance(root, bytes):
  1011. root = os.fsdecode(root)
  1012. hidden_path = os.path.join(root, CONTROLDIR)
  1013. if bare is None:
  1014. if os.path.isfile(hidden_path) or os.path.isdir(
  1015. os.path.join(hidden_path, OBJECTDIR)
  1016. ):
  1017. bare = False
  1018. elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir(
  1019. os.path.join(root, REFSDIR)
  1020. ):
  1021. bare = True
  1022. else:
  1023. raise NotGitRepository(
  1024. "No git repository was found at {path}".format(**dict(path=root))
  1025. )
  1026. self.bare = bare
  1027. if bare is False:
  1028. if os.path.isfile(hidden_path):
  1029. with open(hidden_path) as f:
  1030. path = read_gitfile(f)
  1031. self._controldir = os.path.join(root, path)
  1032. else:
  1033. self._controldir = hidden_path
  1034. else:
  1035. self._controldir = root
  1036. commondir = self.get_named_file(COMMONDIR)
  1037. if commondir is not None:
  1038. with commondir:
  1039. self._commondir = os.path.join(
  1040. self.controldir(),
  1041. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  1042. )
  1043. else:
  1044. self._commondir = self._controldir
  1045. self.path = root
  1046. config = self.get_config()
  1047. try:
  1048. repository_format_version = config.get("core", "repositoryformatversion")
  1049. format_version = (
  1050. 0
  1051. if repository_format_version is None
  1052. else int(repository_format_version)
  1053. )
  1054. except KeyError:
  1055. format_version = 0
  1056. if format_version not in (0, 1):
  1057. raise UnsupportedVersion(format_version)
  1058. for extension, _value in config.items((b"extensions",)):
  1059. if extension.lower() not in (b"worktreeconfig",):
  1060. raise UnsupportedExtension(extension)
  1061. if object_store is None:
  1062. object_store = DiskObjectStore.from_config(
  1063. os.path.join(self.commondir(), OBJECTDIR), config
  1064. )
  1065. refs = DiskRefsContainer(
  1066. self.commondir(), self._controldir, logger=self._write_reflog
  1067. )
  1068. BaseRepo.__init__(self, object_store, refs)
  1069. self._graftpoints = {}
  1070. graft_file = self.get_named_file(
  1071. os.path.join("info", "grafts"), basedir=self.commondir()
  1072. )
  1073. if graft_file:
  1074. with graft_file:
  1075. self._graftpoints.update(parse_graftpoints(graft_file))
  1076. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  1077. if graft_file:
  1078. with graft_file:
  1079. self._graftpoints.update(parse_graftpoints(graft_file))
  1080. self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir())
  1081. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  1082. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  1083. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  1084. def _write_reflog(
  1085. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  1086. ) -> None:
  1087. from .reflog import format_reflog_line
  1088. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  1089. try:
  1090. os.makedirs(os.path.dirname(path))
  1091. except FileExistsError:
  1092. pass
  1093. if committer is None:
  1094. config = self.get_config_stack()
  1095. committer = get_user_identity(config)
  1096. check_user_identity(committer)
  1097. if timestamp is None:
  1098. timestamp = int(time.time())
  1099. if timezone is None:
  1100. timezone = 0 # FIXME
  1101. with open(path, "ab") as f:
  1102. f.write(
  1103. format_reflog_line(
  1104. old_sha, new_sha, committer, timestamp, timezone, message
  1105. )
  1106. + b"\n"
  1107. )
  1108. @classmethod
  1109. def discover(cls, start="."):
  1110. """Iterate parent directories to discover a repository.
  1111. Return a Repo object for the first parent directory that looks like a
  1112. Git repository.
  1113. Args:
  1114. start: The directory to start discovery from (defaults to '.')
  1115. """
  1116. remaining = True
  1117. path = os.path.abspath(start)
  1118. while remaining:
  1119. try:
  1120. return cls(path)
  1121. except NotGitRepository:
  1122. path, remaining = os.path.split(path)
  1123. raise NotGitRepository(
  1124. "No git repository was found at {path}".format(**dict(path=start))
  1125. )
  1126. def controldir(self):
  1127. """Return the path of the control directory."""
  1128. return self._controldir
  1129. def commondir(self):
  1130. """Return the path of the common directory.
  1131. For a main working tree, it is identical to controldir().
  1132. For a linked working tree, it is the control directory of the
  1133. main working tree.
  1134. """
  1135. return self._commondir
  1136. def _determine_file_mode(self):
  1137. """Probe the file-system to determine whether permissions can be trusted.
  1138. Returns: True if permissions can be trusted, False otherwise.
  1139. """
  1140. fname = os.path.join(self.path, ".probe-permissions")
  1141. with open(fname, "w") as f:
  1142. f.write("")
  1143. st1 = os.lstat(fname)
  1144. try:
  1145. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  1146. except PermissionError:
  1147. return False
  1148. st2 = os.lstat(fname)
  1149. os.unlink(fname)
  1150. mode_differs = st1.st_mode != st2.st_mode
  1151. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1152. return mode_differs and st2_has_exec
  1153. def _determine_symlinks(self):
  1154. """Probe the filesystem to determine whether symlinks can be created.
  1155. Returns: True if symlinks can be created, False otherwise.
  1156. """
  1157. # TODO(jelmer): Actually probe disk / look at filesystem
  1158. return sys.platform != "win32"
  1159. def _put_named_file(self, path, contents) -> None:
  1160. """Write a file to the control dir with the given name and contents.
  1161. Args:
  1162. path: The path to the file, relative to the control dir.
  1163. contents: A string to write to the file.
  1164. """
  1165. path = path.lstrip(os.path.sep)
  1166. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1167. f.write(contents)
  1168. def _del_named_file(self, path) -> None:
  1169. try:
  1170. os.unlink(os.path.join(self.controldir(), path))
  1171. except FileNotFoundError:
  1172. return
  1173. def get_named_file(self, path, basedir=None):
  1174. """Get a file from the control dir with a specific name.
  1175. Although the filename should be interpreted as a filename relative to
  1176. the control dir in a disk-based Repo, the object returned need not be
  1177. pointing to a file in that location.
  1178. Args:
  1179. path: The path to the file, relative to the control dir.
  1180. basedir: Optional argument that specifies an alternative to the
  1181. control dir.
  1182. Returns: An open file object, or None if the file does not exist.
  1183. """
  1184. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1185. # the dumb web serving code.
  1186. if basedir is None:
  1187. basedir = self.controldir()
  1188. path = path.lstrip(os.path.sep)
  1189. try:
  1190. return open(os.path.join(basedir, path), "rb")
  1191. except FileNotFoundError:
  1192. return None
  1193. def index_path(self):
  1194. """Return path to the index file."""
  1195. return os.path.join(self.controldir(), INDEX_FILENAME)
  1196. def open_index(self) -> "Index":
  1197. """Open the index for this repository.
  1198. Raises:
  1199. NoIndexPresent: If no index is present
  1200. Returns: The matching `Index`
  1201. """
  1202. from .index import Index
  1203. if not self.has_index():
  1204. raise NoIndexPresent
  1205. # Check for manyFiles feature configuration
  1206. config = self.get_config_stack()
  1207. many_files = config.get_boolean(b"feature", b"manyFiles", False)
  1208. skip_hash = False
  1209. index_version = None
  1210. if many_files:
  1211. # When feature.manyFiles is enabled, set index.version=4 and index.skipHash=true
  1212. try:
  1213. index_version_str = config.get(b"index", b"version")
  1214. index_version = int(index_version_str)
  1215. except KeyError:
  1216. index_version = 4 # Default to version 4 for manyFiles
  1217. skip_hash = config.get_boolean(b"index", b"skipHash", True)
  1218. else:
  1219. # Check for explicit index settings
  1220. try:
  1221. index_version_str = config.get(b"index", b"version")
  1222. index_version = int(index_version_str)
  1223. except KeyError:
  1224. index_version = None
  1225. skip_hash = config.get_boolean(b"index", b"skipHash", False)
  1226. return Index(self.index_path(), skip_hash=skip_hash, version=index_version)
  1227. def has_index(self) -> bool:
  1228. """Check if an index is present."""
  1229. # Bare repos must never have index files; non-bare repos may have a
  1230. # missing index file, which is treated as empty.
  1231. return not self.bare
  1232. def stage(
  1233. self,
  1234. fs_paths: Union[
  1235. str, bytes, os.PathLike, Iterable[Union[str, bytes, os.PathLike]]
  1236. ],
  1237. ) -> None:
  1238. """Stage a set of paths.
  1239. Args:
  1240. fs_paths: List of paths, relative to the repository path
  1241. """
  1242. root_path_bytes = os.fsencode(self.path)
  1243. if isinstance(fs_paths, (str, bytes, os.PathLike)):
  1244. fs_paths = [fs_paths]
  1245. fs_paths = list(fs_paths)
  1246. from .index import (
  1247. _fs_to_tree_path,
  1248. blob_from_path_and_stat,
  1249. index_entry_from_directory,
  1250. index_entry_from_stat,
  1251. )
  1252. index = self.open_index()
  1253. blob_normalizer = self.get_blob_normalizer()
  1254. for fs_path in fs_paths:
  1255. if not isinstance(fs_path, bytes):
  1256. fs_path = os.fsencode(fs_path)
  1257. if os.path.isabs(fs_path):
  1258. raise ValueError(
  1259. f"path {fs_path!r} should be relative to "
  1260. "repository root, not absolute"
  1261. )
  1262. tree_path = _fs_to_tree_path(fs_path)
  1263. full_path = os.path.join(root_path_bytes, fs_path)
  1264. try:
  1265. st = os.lstat(full_path)
  1266. except OSError:
  1267. # File no longer exists
  1268. try:
  1269. del index[tree_path]
  1270. except KeyError:
  1271. pass # already removed
  1272. else:
  1273. if stat.S_ISDIR(st.st_mode):
  1274. entry = index_entry_from_directory(st, full_path)
  1275. if entry:
  1276. index[tree_path] = entry
  1277. else:
  1278. try:
  1279. del index[tree_path]
  1280. except KeyError:
  1281. pass
  1282. elif not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1283. try:
  1284. del index[tree_path]
  1285. except KeyError:
  1286. pass
  1287. else:
  1288. blob = blob_from_path_and_stat(full_path, st)
  1289. blob = blob_normalizer.checkin_normalize(blob, fs_path)
  1290. self.object_store.add_object(blob)
  1291. index[tree_path] = index_entry_from_stat(st, blob.id)
  1292. index.write()
  1293. def unstage(self, fs_paths: list[str]) -> None:
  1294. """Unstage specific file in the index
  1295. Args:
  1296. fs_paths: a list of files to unstage,
  1297. relative to the repository path.
  1298. """
  1299. from .index import IndexEntry, _fs_to_tree_path
  1300. index = self.open_index()
  1301. try:
  1302. tree_id = self[b"HEAD"].tree
  1303. except KeyError:
  1304. # no head mean no commit in the repo
  1305. for fs_path in fs_paths:
  1306. tree_path = _fs_to_tree_path(fs_path)
  1307. del index[tree_path]
  1308. index.write()
  1309. return
  1310. for fs_path in fs_paths:
  1311. tree_path = _fs_to_tree_path(fs_path)
  1312. try:
  1313. tree = self.object_store[tree_id]
  1314. assert isinstance(tree, Tree)
  1315. tree_entry = tree.lookup_path(self.object_store.__getitem__, tree_path)
  1316. except KeyError:
  1317. # if tree_entry didn't exist, this file was being added, so
  1318. # remove index entry
  1319. try:
  1320. del index[tree_path]
  1321. continue
  1322. except KeyError as exc:
  1323. raise KeyError(f"file '{tree_path.decode()}' not in index") from exc
  1324. st = None
  1325. try:
  1326. st = os.lstat(os.path.join(self.path, fs_path))
  1327. except FileNotFoundError:
  1328. pass
  1329. index_entry = IndexEntry(
  1330. ctime=(self[b"HEAD"].commit_time, 0),
  1331. mtime=(self[b"HEAD"].commit_time, 0),
  1332. dev=st.st_dev if st else 0,
  1333. ino=st.st_ino if st else 0,
  1334. mode=tree_entry[0],
  1335. uid=st.st_uid if st else 0,
  1336. gid=st.st_gid if st else 0,
  1337. size=len(self[tree_entry[1]].data),
  1338. sha=tree_entry[1],
  1339. flags=0,
  1340. extended_flags=0,
  1341. )
  1342. index[tree_path] = index_entry
  1343. index.write()
  1344. def clone(
  1345. self,
  1346. target_path,
  1347. *,
  1348. mkdir=True,
  1349. bare=False,
  1350. origin=b"origin",
  1351. checkout=None,
  1352. branch=None,
  1353. progress=None,
  1354. depth: Optional[int] = None,
  1355. symlinks=None,
  1356. ) -> "Repo":
  1357. """Clone this repository.
  1358. Args:
  1359. target_path: Target path
  1360. mkdir: Create the target directory
  1361. bare: Whether to create a bare repository
  1362. checkout: Whether or not to check-out HEAD after cloning
  1363. origin: Base name for refs in target repository
  1364. cloned from this repository
  1365. branch: Optional branch or tag to be used as HEAD in the new repository
  1366. instead of this repository's HEAD.
  1367. progress: Optional progress function
  1368. depth: Depth at which to fetch
  1369. symlinks: Symlinks setting (default to autodetect)
  1370. Returns: Created repository as `Repo`
  1371. """
  1372. encoded_path = os.fsencode(self.path)
  1373. if mkdir:
  1374. os.mkdir(target_path)
  1375. try:
  1376. if not bare:
  1377. target = Repo.init(target_path, symlinks=symlinks)
  1378. if checkout is None:
  1379. checkout = True
  1380. else:
  1381. if checkout:
  1382. raise ValueError("checkout and bare are incompatible")
  1383. target = Repo.init_bare(target_path)
  1384. try:
  1385. target_config = target.get_config()
  1386. target_config.set((b"remote", origin), b"url", encoded_path)
  1387. target_config.set(
  1388. (b"remote", origin),
  1389. b"fetch",
  1390. b"+refs/heads/*:refs/remotes/" + origin + b"/*",
  1391. )
  1392. target_config.write_to_path()
  1393. ref_message = b"clone: from " + encoded_path
  1394. self.fetch(target, depth=depth)
  1395. target.refs.import_refs(
  1396. b"refs/remotes/" + origin,
  1397. self.refs.as_dict(b"refs/heads"),
  1398. message=ref_message,
  1399. )
  1400. target.refs.import_refs(
  1401. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1402. )
  1403. head_chain, origin_sha = self.refs.follow(b"HEAD")
  1404. origin_head = head_chain[-1] if head_chain else None
  1405. if origin_sha and not origin_head:
  1406. # set detached HEAD
  1407. target.refs[b"HEAD"] = origin_sha
  1408. else:
  1409. _set_origin_head(target.refs, origin, origin_head)
  1410. head_ref = _set_default_branch(
  1411. target.refs, origin, origin_head, branch, ref_message
  1412. )
  1413. # Update target head
  1414. if head_ref:
  1415. head = _set_head(target.refs, head_ref, ref_message)
  1416. else:
  1417. head = None
  1418. if checkout and head is not None:
  1419. target.reset_index()
  1420. except BaseException:
  1421. target.close()
  1422. raise
  1423. except BaseException:
  1424. if mkdir:
  1425. import shutil
  1426. shutil.rmtree(target_path)
  1427. raise
  1428. return target
  1429. def reset_index(self, tree: Optional[bytes] = None):
  1430. """Reset the index back to a specific tree.
  1431. Args:
  1432. tree: Tree SHA to reset to, None for current HEAD tree.
  1433. """
  1434. from .index import (
  1435. build_index_from_tree,
  1436. symlink,
  1437. validate_path_element_default,
  1438. validate_path_element_ntfs,
  1439. )
  1440. if tree is None:
  1441. head = self[b"HEAD"]
  1442. if isinstance(head, Tag):
  1443. _cls, obj = head.object
  1444. head = self.get_object(obj)
  1445. tree = head.tree
  1446. config = self.get_config()
  1447. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1448. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1449. validate_path_element = validate_path_element_ntfs
  1450. else:
  1451. validate_path_element = validate_path_element_default
  1452. if config.get_boolean(b"core", b"symlinks", True):
  1453. symlink_fn = symlink
  1454. else:
  1455. def symlink_fn(source, target) -> None: # type: ignore
  1456. with open(
  1457. target, "w" + ("b" if isinstance(source, bytes) else "")
  1458. ) as f:
  1459. f.write(source)
  1460. return build_index_from_tree(
  1461. self.path,
  1462. self.index_path(),
  1463. self.object_store,
  1464. tree,
  1465. honor_filemode=honor_filemode,
  1466. validate_path_element=validate_path_element,
  1467. symlink_fn=symlink_fn,
  1468. )
  1469. def get_worktree_config(self) -> "ConfigFile":
  1470. from .config import ConfigFile
  1471. path = os.path.join(self.commondir(), "config.worktree")
  1472. try:
  1473. return ConfigFile.from_path(path)
  1474. except FileNotFoundError:
  1475. cf = ConfigFile()
  1476. cf.path = path
  1477. return cf
  1478. def get_config(self) -> "ConfigFile":
  1479. """Retrieve the config object.
  1480. Returns: `ConfigFile` object for the ``.git/config`` file.
  1481. """
  1482. from .config import ConfigFile
  1483. path = os.path.join(self._commondir, "config")
  1484. try:
  1485. return ConfigFile.from_path(path)
  1486. except FileNotFoundError:
  1487. ret = ConfigFile()
  1488. ret.path = path
  1489. return ret
  1490. def get_rebase_state_manager(self):
  1491. """Get the appropriate rebase state manager for this repository.
  1492. Returns: DiskRebaseStateManager instance
  1493. """
  1494. import os
  1495. from .rebase import DiskRebaseStateManager
  1496. path = os.path.join(self.controldir(), "rebase-merge")
  1497. return DiskRebaseStateManager(path)
  1498. def get_description(self):
  1499. """Retrieve the description of this repository.
  1500. Returns: A string describing the repository or None.
  1501. """
  1502. path = os.path.join(self._controldir, "description")
  1503. try:
  1504. with GitFile(path, "rb") as f:
  1505. return f.read()
  1506. except FileNotFoundError:
  1507. return None
  1508. def __repr__(self) -> str:
  1509. return f"<Repo at {self.path!r}>"
  1510. def set_description(self, description) -> None:
  1511. """Set the description for this repository.
  1512. Args:
  1513. description: Text to set as description for this repository.
  1514. """
  1515. self._put_named_file("description", description)
  1516. @classmethod
  1517. def _init_maybe_bare(
  1518. cls,
  1519. path: Union[str, bytes, os.PathLike],
  1520. controldir: Union[str, bytes, os.PathLike],
  1521. bare,
  1522. object_store=None,
  1523. config=None,
  1524. default_branch=None,
  1525. symlinks: Optional[bool] = None,
  1526. format: Optional[int] = None,
  1527. ):
  1528. path = os.fspath(path)
  1529. if isinstance(path, bytes):
  1530. path = os.fsdecode(path)
  1531. controldir = os.fspath(controldir)
  1532. if isinstance(controldir, bytes):
  1533. controldir = os.fsdecode(controldir)
  1534. for d in BASE_DIRECTORIES:
  1535. os.mkdir(os.path.join(controldir, *d))
  1536. if object_store is None:
  1537. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1538. ret = cls(path, bare=bare, object_store=object_store)
  1539. if default_branch is None:
  1540. if config is None:
  1541. from .config import StackedConfig
  1542. config = StackedConfig.default()
  1543. try:
  1544. default_branch = config.get("init", "defaultBranch")
  1545. except KeyError:
  1546. default_branch = DEFAULT_BRANCH
  1547. ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch)
  1548. ret._init_files(bare=bare, symlinks=symlinks, format=format)
  1549. return ret
  1550. @classmethod
  1551. def init(
  1552. cls,
  1553. path: Union[str, bytes, os.PathLike],
  1554. *,
  1555. mkdir: bool = False,
  1556. config=None,
  1557. default_branch=None,
  1558. symlinks: Optional[bool] = None,
  1559. format: Optional[int] = None,
  1560. ) -> "Repo":
  1561. """Create a new repository.
  1562. Args:
  1563. path: Path in which to create the repository
  1564. mkdir: Whether to create the directory
  1565. format: Repository format version (defaults to 0)
  1566. Returns: `Repo` instance
  1567. """
  1568. path = os.fspath(path)
  1569. if isinstance(path, bytes):
  1570. path = os.fsdecode(path)
  1571. if mkdir:
  1572. os.mkdir(path)
  1573. controldir = os.path.join(path, CONTROLDIR)
  1574. os.mkdir(controldir)
  1575. _set_filesystem_hidden(controldir)
  1576. return cls._init_maybe_bare(
  1577. path,
  1578. controldir,
  1579. False,
  1580. config=config,
  1581. default_branch=default_branch,
  1582. symlinks=symlinks,
  1583. format=format,
  1584. )
  1585. @classmethod
  1586. def _init_new_working_directory(
  1587. cls,
  1588. path: Union[str, bytes, os.PathLike],
  1589. main_repo,
  1590. identifier=None,
  1591. mkdir=False,
  1592. ):
  1593. """Create a new working directory linked to a repository.
  1594. Args:
  1595. path: Path in which to create the working tree.
  1596. main_repo: Main repository to reference
  1597. identifier: Worktree identifier
  1598. mkdir: Whether to create the directory
  1599. Returns: `Repo` instance
  1600. """
  1601. path = os.fspath(path)
  1602. if isinstance(path, bytes):
  1603. path = os.fsdecode(path)
  1604. if mkdir:
  1605. os.mkdir(path)
  1606. if identifier is None:
  1607. identifier = os.path.basename(path)
  1608. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  1609. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1610. gitdirfile = os.path.join(path, CONTROLDIR)
  1611. with open(gitdirfile, "wb") as f:
  1612. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1613. try:
  1614. os.mkdir(main_worktreesdir)
  1615. except FileExistsError:
  1616. pass
  1617. try:
  1618. os.mkdir(worktree_controldir)
  1619. except FileExistsError:
  1620. pass
  1621. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1622. f.write(os.fsencode(gitdirfile) + b"\n")
  1623. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1624. f.write(b"../..\n")
  1625. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1626. f.write(main_repo.head() + b"\n")
  1627. r = cls(path)
  1628. r.reset_index()
  1629. return r
  1630. @classmethod
  1631. def init_bare(
  1632. cls,
  1633. path: Union[str, bytes, os.PathLike],
  1634. *,
  1635. mkdir=False,
  1636. object_store=None,
  1637. config=None,
  1638. default_branch=None,
  1639. format: Optional[int] = None,
  1640. ):
  1641. """Create a new bare repository.
  1642. ``path`` should already exist and be an empty directory.
  1643. Args:
  1644. path: Path to create bare repository in
  1645. format: Repository format version (defaults to 0)
  1646. Returns: a `Repo` instance
  1647. """
  1648. path = os.fspath(path)
  1649. if isinstance(path, bytes):
  1650. path = os.fsdecode(path)
  1651. if mkdir:
  1652. os.mkdir(path)
  1653. return cls._init_maybe_bare(
  1654. path,
  1655. path,
  1656. True,
  1657. object_store=object_store,
  1658. config=config,
  1659. default_branch=default_branch,
  1660. format=format,
  1661. )
  1662. create = init_bare
  1663. def close(self) -> None:
  1664. """Close any files opened by this repository."""
  1665. self.object_store.close()
  1666. def __enter__(self):
  1667. return self
  1668. def __exit__(self, exc_type, exc_val, exc_tb):
  1669. self.close()
  1670. def get_blob_normalizer(self):
  1671. """Return a BlobNormalizer object."""
  1672. # TODO Parse the git attributes files
  1673. git_attributes = {}
  1674. config_stack = self.get_config_stack()
  1675. try:
  1676. tree = self.object_store[self.refs[b"HEAD"]].tree
  1677. return TreeBlobNormalizer(
  1678. config_stack,
  1679. git_attributes,
  1680. self.object_store,
  1681. tree,
  1682. )
  1683. except KeyError:
  1684. return BlobNormalizer(config_stack, git_attributes)
  1685. def _sparse_checkout_file_path(self) -> str:
  1686. """Return the path of the sparse-checkout file in this repo's control dir."""
  1687. return os.path.join(self.controldir(), "info", "sparse-checkout")
  1688. def configure_for_cone_mode(self) -> None:
  1689. """Ensure the repository is configured for cone-mode sparse-checkout."""
  1690. config = self.get_config()
  1691. config.set((b"core",), b"sparseCheckout", b"true")
  1692. config.set((b"core",), b"sparseCheckoutCone", b"true")
  1693. config.write_to_path()
  1694. def infer_cone_mode(self) -> bool:
  1695. """Return True if 'core.sparseCheckoutCone' is set to 'true' in config, else False."""
  1696. config = self.get_config()
  1697. try:
  1698. sc_cone = config.get((b"core",), b"sparseCheckoutCone")
  1699. return sc_cone == b"true"
  1700. except KeyError:
  1701. # If core.sparseCheckoutCone is not set, default to False
  1702. return False
  1703. def get_sparse_checkout_patterns(self) -> list[str]:
  1704. """Return a list of sparse-checkout patterns from info/sparse-checkout.
  1705. Returns:
  1706. A list of patterns. Returns an empty list if the file is missing.
  1707. """
  1708. path = self._sparse_checkout_file_path()
  1709. try:
  1710. with open(path, encoding="utf-8") as f:
  1711. return [line.strip() for line in f if line.strip()]
  1712. except FileNotFoundError:
  1713. return []
  1714. def set_sparse_checkout_patterns(self, patterns: list[str]) -> None:
  1715. """Write the given sparse-checkout patterns into info/sparse-checkout.
  1716. Creates the info/ directory if it does not exist.
  1717. Args:
  1718. patterns: A list of gitignore-style patterns to store.
  1719. """
  1720. info_dir = os.path.join(self.controldir(), "info")
  1721. os.makedirs(info_dir, exist_ok=True)
  1722. path = self._sparse_checkout_file_path()
  1723. with open(path, "w", encoding="utf-8") as f:
  1724. for pat in patterns:
  1725. f.write(pat + "\n")
  1726. def set_cone_mode_patterns(self, dirs: Union[list[str], None] = None) -> None:
  1727. """Write the given cone-mode directory patterns into info/sparse-checkout.
  1728. For each directory to include, add an inclusion line that "undoes" the prior
  1729. ``!/*/`` 'exclude' that re-includes that directory and everything under it.
  1730. Never add the same line twice.
  1731. """
  1732. patterns = ["/*", "!/*/"]
  1733. if dirs:
  1734. for d in dirs:
  1735. d = d.strip("/")
  1736. line = f"/{d}/"
  1737. if d and line not in patterns:
  1738. patterns.append(line)
  1739. self.set_sparse_checkout_patterns(patterns)
  1740. class MemoryRepo(BaseRepo):
  1741. """Repo that stores refs, objects, and named files in memory.
  1742. MemoryRepos are always bare: they have no working tree and no index, since
  1743. those have a stronger dependency on the filesystem.
  1744. """
  1745. def __init__(self) -> None:
  1746. """Create a new repository in memory."""
  1747. from .config import ConfigFile
  1748. self._reflog: list[Any] = []
  1749. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1750. BaseRepo.__init__(self, MemoryObjectStore(), refs_container) # type: ignore
  1751. self._named_files: dict[str, bytes] = {}
  1752. self.bare = True
  1753. self._config = ConfigFile()
  1754. self._description = None
  1755. def _append_reflog(self, *args) -> None:
  1756. self._reflog.append(args)
  1757. def set_description(self, description) -> None:
  1758. self._description = description
  1759. def get_description(self):
  1760. return self._description
  1761. def _determine_file_mode(self):
  1762. """Probe the file-system to determine whether permissions can be trusted.
  1763. Returns: True if permissions can be trusted, False otherwise.
  1764. """
  1765. return sys.platform != "win32"
  1766. def _determine_symlinks(self):
  1767. """Probe the file-system to determine whether permissions can be trusted.
  1768. Returns: True if permissions can be trusted, False otherwise.
  1769. """
  1770. return sys.platform != "win32"
  1771. def _put_named_file(self, path, contents) -> None:
  1772. """Write a file to the control dir with the given name and contents.
  1773. Args:
  1774. path: The path to the file, relative to the control dir.
  1775. contents: A string to write to the file.
  1776. """
  1777. self._named_files[path] = contents
  1778. def _del_named_file(self, path) -> None:
  1779. try:
  1780. del self._named_files[path]
  1781. except KeyError:
  1782. pass
  1783. def get_named_file(self, path, basedir=None):
  1784. """Get a file from the control dir with a specific name.
  1785. Although the filename should be interpreted as a filename relative to
  1786. the control dir in a disk-baked Repo, the object returned need not be
  1787. pointing to a file in that location.
  1788. Args:
  1789. path: The path to the file, relative to the control dir.
  1790. Returns: An open file object, or None if the file does not exist.
  1791. """
  1792. contents = self._named_files.get(path, None)
  1793. if contents is None:
  1794. return None
  1795. return BytesIO(contents)
  1796. def open_index(self) -> "Index":
  1797. """Fail to open index for this repo, since it is bare.
  1798. Raises:
  1799. NoIndexPresent: Raised when no index is present
  1800. """
  1801. raise NoIndexPresent
  1802. def get_config(self):
  1803. """Retrieve the config object.
  1804. Returns: `ConfigFile` object.
  1805. """
  1806. return self._config
  1807. def get_rebase_state_manager(self):
  1808. """Get the appropriate rebase state manager for this repository.
  1809. Returns: MemoryRebaseStateManager instance
  1810. """
  1811. from .rebase import MemoryRebaseStateManager
  1812. return MemoryRebaseStateManager(self)
  1813. @classmethod
  1814. def init_bare(cls, objects, refs, format: Optional[int] = None):
  1815. """Create a new bare repository in memory.
  1816. Args:
  1817. objects: Objects for the new repository,
  1818. as iterable
  1819. refs: Refs as dictionary, mapping names
  1820. to object SHA1s
  1821. format: Repository format version (defaults to 0)
  1822. """
  1823. ret = cls()
  1824. for obj in objects:
  1825. ret.object_store.add_object(obj)
  1826. for refname, sha in refs.items():
  1827. ret.refs.add_if_new(refname, sha)
  1828. ret._init_files(bare=True, format=format)
  1829. return ret