repo.py 59 KB

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