repo.py 57 KB

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