repo.py 66 KB

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