repo.py 58 KB

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