repo.py 62 KB

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