repo.py 77 KB

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