repo.py 67 KB

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