repo.py 59 KB

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