repo.py 55 KB

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