repo.py 62 KB

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