repo.py 58 KB

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