repo.py 62 KB

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