repo.py 60 KB

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