repo.py 69 KB

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