repo.py 58 KB

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