object_store.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. # and others
  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. """Git object store interfaces and implementation."""
  23. import binascii
  24. import os
  25. import stat
  26. import sys
  27. import time
  28. import warnings
  29. from collections.abc import Iterable, Iterator, Sequence
  30. from contextlib import suppress
  31. from io import BytesIO
  32. from typing import (
  33. Callable,
  34. Optional,
  35. Protocol,
  36. Union,
  37. cast,
  38. )
  39. from .errors import NotTreeError
  40. from .file import GitFile
  41. from .objects import (
  42. S_ISGITLINK,
  43. ZERO_SHA,
  44. Blob,
  45. Commit,
  46. ObjectID,
  47. ShaFile,
  48. Tag,
  49. Tree,
  50. TreeEntry,
  51. hex_to_filename,
  52. hex_to_sha,
  53. object_class,
  54. sha_to_hex,
  55. valid_hexsha,
  56. )
  57. from .pack import (
  58. PACK_SPOOL_FILE_MAX_SIZE,
  59. ObjectContainer,
  60. Pack,
  61. PackData,
  62. PackedObjectContainer,
  63. PackFileDisappeared,
  64. PackHint,
  65. PackIndexer,
  66. PackInflater,
  67. PackStreamCopier,
  68. UnpackedObject,
  69. extend_pack,
  70. full_unpacked_object,
  71. generate_unpacked_objects,
  72. iter_sha1,
  73. load_pack_index_file,
  74. pack_objects_to_data,
  75. write_pack_data,
  76. write_pack_index,
  77. )
  78. from .protocol import DEPTH_INFINITE
  79. from .refs import PEELED_TAG_SUFFIX, Ref
  80. INFODIR = "info"
  81. PACKDIR = "pack"
  82. # use permissions consistent with Git; just readable by everyone
  83. # TODO: should packs also be non-writable on Windows? if so, that
  84. # would requite some rather significant adjustments to the test suite
  85. PACK_MODE = 0o444 if sys.platform != "win32" else 0o644
  86. # Grace period for cleaning up temporary pack files (in seconds)
  87. # Matches git's default of 2 weeks
  88. DEFAULT_TEMPFILE_GRACE_PERIOD = 14 * 24 * 60 * 60 # 2 weeks
  89. def find_shallow(store, heads, depth):
  90. """Find shallow commits according to a given depth.
  91. Args:
  92. store: An ObjectStore for looking up objects.
  93. heads: Iterable of head SHAs to start walking from.
  94. depth: The depth of ancestors to include. A depth of one includes
  95. only the heads themselves.
  96. Returns: A tuple of (shallow, not_shallow), sets of SHAs that should be
  97. considered shallow and unshallow according to the arguments. Note that
  98. these sets may overlap if a commit is reachable along multiple paths.
  99. """
  100. parents = {}
  101. def get_parents(sha):
  102. result = parents.get(sha, None)
  103. if not result:
  104. result = store[sha].parents
  105. parents[sha] = result
  106. return result
  107. todo = [] # stack of (sha, depth)
  108. for head_sha in heads:
  109. obj = store[head_sha]
  110. # Peel tags if necessary
  111. while isinstance(obj, Tag):
  112. _, sha = obj.object
  113. obj = store[sha]
  114. if isinstance(obj, Commit):
  115. todo.append((obj.id, 1))
  116. not_shallow = set()
  117. shallow = set()
  118. while todo:
  119. sha, cur_depth = todo.pop()
  120. if cur_depth < depth:
  121. not_shallow.add(sha)
  122. new_depth = cur_depth + 1
  123. todo.extend((p, new_depth) for p in get_parents(sha))
  124. else:
  125. shallow.add(sha)
  126. return shallow, not_shallow
  127. def get_depth(
  128. store,
  129. head,
  130. get_parents=lambda commit: commit.parents,
  131. max_depth=None,
  132. ):
  133. """Return the current available depth for the given head.
  134. For commits with multiple parents, the largest possible depth will be
  135. returned.
  136. Args:
  137. head: commit to start from
  138. get_parents: optional function for getting the parents of a commit
  139. max_depth: maximum depth to search
  140. """
  141. if head not in store:
  142. return 0
  143. current_depth = 1
  144. queue = [(head, current_depth)]
  145. while queue and (max_depth is None or current_depth < max_depth):
  146. e, depth = queue.pop(0)
  147. current_depth = max(current_depth, depth)
  148. cmt = store[e]
  149. if isinstance(cmt, Tag):
  150. _cls, sha = cmt.object
  151. cmt = store[sha]
  152. queue.extend(
  153. (parent, depth + 1) for parent in get_parents(cmt) if parent in store
  154. )
  155. return current_depth
  156. class PackContainer(Protocol):
  157. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  158. """Add a new pack."""
  159. class BaseObjectStore:
  160. """Object store interface."""
  161. def determine_wants_all(
  162. self, refs: dict[Ref, ObjectID], depth: Optional[int] = None
  163. ) -> list[ObjectID]:
  164. def _want_deepen(sha):
  165. if not depth:
  166. return False
  167. if depth == DEPTH_INFINITE:
  168. return True
  169. return depth > self._get_depth(sha)
  170. return [
  171. sha
  172. for (ref, sha) in refs.items()
  173. if (sha not in self or _want_deepen(sha))
  174. and not ref.endswith(PEELED_TAG_SUFFIX)
  175. and not sha == ZERO_SHA
  176. ]
  177. def contains_loose(self, sha) -> bool:
  178. """Check if a particular object is present by SHA1 and is loose."""
  179. raise NotImplementedError(self.contains_loose)
  180. def __contains__(self, sha1: bytes) -> bool:
  181. """Check if a particular object is present by SHA1.
  182. This method makes no distinction between loose and packed objects.
  183. """
  184. return self.contains_loose(sha1)
  185. @property
  186. def packs(self):
  187. """Iterable of pack objects."""
  188. raise NotImplementedError
  189. def get_raw(self, name) -> tuple[int, bytes]:
  190. """Obtain the raw text for an object.
  191. Args:
  192. name: sha for the object.
  193. Returns: tuple with numeric type and object contents.
  194. """
  195. raise NotImplementedError(self.get_raw)
  196. def __getitem__(self, sha1: ObjectID) -> ShaFile:
  197. """Obtain an object by SHA1."""
  198. type_num, uncomp = self.get_raw(sha1)
  199. return ShaFile.from_raw_string(type_num, uncomp, sha=sha1)
  200. def __iter__(self):
  201. """Iterate over the SHAs that are present in this store."""
  202. raise NotImplementedError(self.__iter__)
  203. def add_object(self, obj) -> None:
  204. """Add a single object to this object store."""
  205. raise NotImplementedError(self.add_object)
  206. def add_objects(self, objects, progress=None) -> None:
  207. """Add a set of objects to this object store.
  208. Args:
  209. objects: Iterable over a list of (object, path) tuples
  210. """
  211. raise NotImplementedError(self.add_objects)
  212. def tree_changes(
  213. self,
  214. source,
  215. target,
  216. want_unchanged=False,
  217. include_trees=False,
  218. change_type_same=False,
  219. rename_detector=None,
  220. ):
  221. """Find the differences between the contents of two trees.
  222. Args:
  223. source: SHA1 of the source tree
  224. target: SHA1 of the target tree
  225. want_unchanged: Whether unchanged files should be reported
  226. include_trees: Whether to include trees
  227. change_type_same: Whether to report files changing
  228. type in the same entry.
  229. Returns: Iterator over tuples with
  230. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  231. """
  232. from .diff_tree import tree_changes
  233. for change in tree_changes(
  234. self,
  235. source,
  236. target,
  237. want_unchanged=want_unchanged,
  238. include_trees=include_trees,
  239. change_type_same=change_type_same,
  240. rename_detector=rename_detector,
  241. ):
  242. yield (
  243. (change.old.path, change.new.path),
  244. (change.old.mode, change.new.mode),
  245. (change.old.sha, change.new.sha),
  246. )
  247. def iter_tree_contents(self, tree_id, include_trees=False):
  248. """Iterate the contents of a tree and all subtrees.
  249. Iteration is depth-first pre-order, as in e.g. os.walk.
  250. Args:
  251. tree_id: SHA1 of the tree.
  252. include_trees: If True, include tree objects in the iteration.
  253. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  254. tree.
  255. """
  256. warnings.warn(
  257. "Please use dulwich.object_store.iter_tree_contents",
  258. DeprecationWarning,
  259. stacklevel=2,
  260. )
  261. return iter_tree_contents(self, tree_id, include_trees=include_trees)
  262. def iterobjects_subset(
  263. self, shas: Iterable[bytes], *, allow_missing: bool = False
  264. ) -> Iterator[ShaFile]:
  265. for sha in shas:
  266. try:
  267. yield self[sha]
  268. except KeyError:
  269. if not allow_missing:
  270. raise
  271. def find_missing_objects(
  272. self,
  273. haves,
  274. wants,
  275. shallow=None,
  276. progress=None,
  277. get_tagged=None,
  278. get_parents=lambda commit: commit.parents,
  279. ):
  280. """Find the missing objects required for a set of revisions.
  281. Args:
  282. haves: Iterable over SHAs already in common.
  283. wants: Iterable over SHAs of objects to fetch.
  284. shallow: Set of shallow commit SHA1s to skip
  285. progress: Simple progress function that will be called with
  286. updated progress strings.
  287. get_tagged: Function that returns a dict of pointed-to sha ->
  288. tag sha for including tags.
  289. get_parents: Optional function for getting the parents of a
  290. commit.
  291. Returns: Iterator over (sha, path) pairs.
  292. """
  293. warnings.warn("Please use MissingObjectFinder(store)", DeprecationWarning)
  294. finder = MissingObjectFinder(
  295. self,
  296. haves=haves,
  297. wants=wants,
  298. shallow=shallow,
  299. progress=progress,
  300. get_tagged=get_tagged,
  301. get_parents=get_parents,
  302. )
  303. return iter(finder)
  304. def find_common_revisions(self, graphwalker):
  305. """Find which revisions this store has in common using graphwalker.
  306. Args:
  307. graphwalker: A graphwalker object.
  308. Returns: List of SHAs that are in common
  309. """
  310. haves = []
  311. sha = next(graphwalker)
  312. while sha:
  313. if sha in self:
  314. haves.append(sha)
  315. graphwalker.ack(sha)
  316. sha = next(graphwalker)
  317. return haves
  318. def generate_pack_data(
  319. self, have, want, shallow=None, progress=None, ofs_delta=True
  320. ) -> tuple[int, Iterator[UnpackedObject]]:
  321. """Generate pack data objects for a set of wants/haves.
  322. Args:
  323. have: List of SHA1s of objects that should not be sent
  324. want: List of SHA1s of objects that should be sent
  325. shallow: Set of shallow commit SHA1s to skip
  326. ofs_delta: Whether OFS deltas can be included
  327. progress: Optional progress reporting method
  328. """
  329. # Note that the pack-specific implementation below is more efficient,
  330. # as it reuses deltas
  331. missing_objects = MissingObjectFinder(
  332. self, haves=have, wants=want, shallow=shallow, progress=progress
  333. )
  334. object_ids = list(missing_objects)
  335. return pack_objects_to_data(
  336. [(self[oid], path) for oid, path in object_ids],
  337. ofs_delta=ofs_delta,
  338. progress=progress,
  339. )
  340. def peel_sha(self, sha):
  341. """Peel all tags from a SHA.
  342. Args:
  343. sha: The object SHA to peel.
  344. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  345. intermediate tags; if the original ref does not point to a tag,
  346. this will equal the original SHA1.
  347. """
  348. warnings.warn(
  349. "Please use dulwich.object_store.peel_sha()",
  350. DeprecationWarning,
  351. stacklevel=2,
  352. )
  353. return peel_sha(self, sha)[1]
  354. def _get_depth(
  355. self,
  356. head,
  357. get_parents=lambda commit: commit.parents,
  358. max_depth=None,
  359. ):
  360. """Return the current available depth for the given head.
  361. For commits with multiple parents, the largest possible depth will be
  362. returned.
  363. Args:
  364. head: commit to start from
  365. get_parents: optional function for getting the parents of a commit
  366. max_depth: maximum depth to search
  367. """
  368. return get_depth(self, head, get_parents=get_parents, max_depth=max_depth)
  369. def close(self) -> None:
  370. """Close any files opened by this object store."""
  371. # Default implementation is a NO-OP
  372. def prune(self, grace_period: Optional[int] = None) -> None:
  373. """Prune/clean up this object store.
  374. This includes removing orphaned temporary files and other
  375. housekeeping tasks. Default implementation is a NO-OP.
  376. Args:
  377. grace_period: Grace period in seconds for removing temporary files.
  378. If None, uses the default grace period.
  379. """
  380. # Default implementation is a NO-OP
  381. def iter_prefix(self, prefix: bytes) -> Iterator[ObjectID]:
  382. """Iterate over all SHA1s that start with a given prefix.
  383. The default implementation is a naive iteration over all objects.
  384. However, subclasses may override this method with more efficient
  385. implementations.
  386. """
  387. for sha in self:
  388. if sha.startswith(prefix):
  389. yield sha
  390. def get_commit_graph(self):
  391. """Get the commit graph for this object store.
  392. Returns:
  393. CommitGraph object if available, None otherwise
  394. """
  395. return None
  396. def write_commit_graph(self, refs=None, reachable=True) -> None:
  397. """Write a commit graph file for this object store.
  398. Args:
  399. refs: List of refs to include. If None, includes all refs from object store.
  400. reachable: If True, includes all commits reachable from refs.
  401. If False, only includes the direct ref targets.
  402. Note:
  403. Default implementation does nothing. Subclasses should override
  404. this method to provide commit graph writing functionality.
  405. """
  406. raise NotImplementedError(self.write_commit_graph)
  407. def get_object_mtime(self, sha):
  408. """Get the modification time of an object.
  409. Args:
  410. sha: SHA1 of the object
  411. Returns:
  412. Modification time as seconds since epoch
  413. Raises:
  414. KeyError: if the object is not found
  415. """
  416. # Default implementation raises KeyError
  417. # Subclasses should override to provide actual mtime
  418. raise KeyError(sha)
  419. class PackBasedObjectStore(BaseObjectStore, PackedObjectContainer):
  420. def __init__(self, pack_compression_level=-1, pack_index_version=None) -> None:
  421. self._pack_cache: dict[str, Pack] = {}
  422. self.pack_compression_level = pack_compression_level
  423. self.pack_index_version = pack_index_version
  424. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  425. """Add a new pack to this object store."""
  426. raise NotImplementedError(self.add_pack)
  427. def add_pack_data(
  428. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  429. ) -> None:
  430. """Add pack data to this object store.
  431. Args:
  432. count: Number of items to add
  433. """
  434. if count == 0:
  435. # Don't bother writing an empty pack file
  436. return
  437. f, commit, abort = self.add_pack()
  438. try:
  439. write_pack_data(
  440. f.write,
  441. unpacked_objects,
  442. num_records=count,
  443. progress=progress,
  444. compression_level=self.pack_compression_level,
  445. )
  446. except BaseException:
  447. abort()
  448. raise
  449. else:
  450. return commit()
  451. @property
  452. def alternates(self):
  453. return []
  454. def contains_packed(self, sha) -> bool:
  455. """Check if a particular object is present by SHA1 and is packed.
  456. This does not check alternates.
  457. """
  458. for pack in self.packs:
  459. try:
  460. if sha in pack:
  461. return True
  462. except PackFileDisappeared:
  463. pass
  464. return False
  465. def __contains__(self, sha) -> bool:
  466. """Check if a particular object is present by SHA1.
  467. This method makes no distinction between loose and packed objects.
  468. """
  469. if self.contains_packed(sha) or self.contains_loose(sha):
  470. return True
  471. for alternate in self.alternates:
  472. if sha in alternate:
  473. return True
  474. return False
  475. def _add_cached_pack(self, base_name, pack) -> None:
  476. """Add a newly appeared pack to the cache by path."""
  477. prev_pack = self._pack_cache.get(base_name)
  478. if prev_pack is not pack:
  479. self._pack_cache[base_name] = pack
  480. if prev_pack:
  481. prev_pack.close()
  482. def generate_pack_data(
  483. self, have, want, shallow=None, progress=None, ofs_delta=True
  484. ) -> tuple[int, Iterator[UnpackedObject]]:
  485. """Generate pack data objects for a set of wants/haves.
  486. Args:
  487. have: List of SHA1s of objects that should not be sent
  488. want: List of SHA1s of objects that should be sent
  489. shallow: Set of shallow commit SHA1s to skip
  490. ofs_delta: Whether OFS deltas can be included
  491. progress: Optional progress reporting method
  492. """
  493. missing_objects = MissingObjectFinder(
  494. self, haves=have, wants=want, shallow=shallow, progress=progress
  495. )
  496. remote_has = missing_objects.get_remote_has()
  497. object_ids = list(missing_objects)
  498. return len(object_ids), generate_unpacked_objects(
  499. cast(PackedObjectContainer, self),
  500. object_ids,
  501. progress=progress,
  502. ofs_delta=ofs_delta,
  503. other_haves=remote_has,
  504. )
  505. def _clear_cached_packs(self) -> None:
  506. pack_cache = self._pack_cache
  507. self._pack_cache = {}
  508. while pack_cache:
  509. (name, pack) = pack_cache.popitem()
  510. pack.close()
  511. def _iter_cached_packs(self):
  512. return self._pack_cache.values()
  513. def _update_pack_cache(self) -> list[Pack]:
  514. raise NotImplementedError(self._update_pack_cache)
  515. def close(self) -> None:
  516. self._clear_cached_packs()
  517. @property
  518. def packs(self):
  519. """List with pack objects."""
  520. return list(self._iter_cached_packs()) + list(self._update_pack_cache())
  521. def count_pack_files(self) -> int:
  522. """Count the number of pack files.
  523. Returns:
  524. Number of pack files (excluding those with .keep files)
  525. """
  526. count = 0
  527. for pack in self.packs:
  528. # Check if there's a .keep file for this pack
  529. keep_path = pack._basename + ".keep"
  530. if not os.path.exists(keep_path):
  531. count += 1
  532. return count
  533. def _iter_alternate_objects(self):
  534. """Iterate over the SHAs of all the objects in alternate stores."""
  535. for alternate in self.alternates:
  536. yield from alternate
  537. def _iter_loose_objects(self):
  538. """Iterate over the SHAs of all loose objects."""
  539. raise NotImplementedError(self._iter_loose_objects)
  540. def _get_loose_object(self, sha) -> Optional[ShaFile]:
  541. raise NotImplementedError(self._get_loose_object)
  542. def delete_loose_object(self, sha) -> None:
  543. """Delete a loose object.
  544. This method only handles loose objects. For packed objects,
  545. use repack(exclude=...) to exclude them during repacking.
  546. """
  547. raise NotImplementedError(self.delete_loose_object)
  548. def _remove_pack(self, name) -> None:
  549. raise NotImplementedError(self._remove_pack)
  550. def pack_loose_objects(self):
  551. """Pack loose objects.
  552. Returns: Number of objects packed
  553. """
  554. objects = set()
  555. for sha in self._iter_loose_objects():
  556. objects.add((self._get_loose_object(sha), None))
  557. self.add_objects(list(objects))
  558. for obj, path in objects:
  559. self.delete_loose_object(obj.id)
  560. return len(objects)
  561. def repack(self, exclude=None):
  562. """Repack the packs in this repository.
  563. Note that this implementation is fairly naive and currently keeps all
  564. objects in memory while it repacks.
  565. Args:
  566. exclude: Optional set of object SHAs to exclude from repacking
  567. """
  568. if exclude is None:
  569. exclude = set()
  570. loose_objects = set()
  571. excluded_loose_objects = set()
  572. for sha in self._iter_loose_objects():
  573. if sha not in exclude:
  574. loose_objects.add(self._get_loose_object(sha))
  575. else:
  576. excluded_loose_objects.add(sha)
  577. objects = {(obj, None) for obj in loose_objects}
  578. old_packs = {p.name(): p for p in self.packs}
  579. for name, pack in old_packs.items():
  580. objects.update(
  581. (obj, None) for obj in pack.iterobjects() if obj.id not in exclude
  582. )
  583. # Only create a new pack if there are objects to pack
  584. if objects:
  585. # The name of the consolidated pack might match the name of a
  586. # pre-existing pack. Take care not to remove the newly created
  587. # consolidated pack.
  588. consolidated = self.add_objects(objects)
  589. old_packs.pop(consolidated.name(), None)
  590. # Delete loose objects that were packed
  591. for obj in loose_objects:
  592. self.delete_loose_object(obj.id)
  593. # Delete excluded loose objects
  594. for sha in excluded_loose_objects:
  595. self.delete_loose_object(sha)
  596. for name, pack in old_packs.items():
  597. self._remove_pack(pack)
  598. self._update_pack_cache()
  599. return len(objects)
  600. def __iter__(self):
  601. """Iterate over the SHAs that are present in this store."""
  602. self._update_pack_cache()
  603. for pack in self._iter_cached_packs():
  604. try:
  605. yield from pack
  606. except PackFileDisappeared:
  607. pass
  608. yield from self._iter_loose_objects()
  609. yield from self._iter_alternate_objects()
  610. def contains_loose(self, sha):
  611. """Check if a particular object is present by SHA1 and is loose.
  612. This does not check alternates.
  613. """
  614. return self._get_loose_object(sha) is not None
  615. def get_raw(self, name):
  616. """Obtain the raw fulltext for an object.
  617. Args:
  618. name: sha for the object.
  619. Returns: tuple with numeric type and object contents.
  620. """
  621. if name == ZERO_SHA:
  622. raise KeyError(name)
  623. if len(name) == 40:
  624. sha = hex_to_sha(name)
  625. hexsha = name
  626. elif len(name) == 20:
  627. sha = name
  628. hexsha = None
  629. else:
  630. raise AssertionError(f"Invalid object name {name!r}")
  631. for pack in self._iter_cached_packs():
  632. try:
  633. return pack.get_raw(sha)
  634. except (KeyError, PackFileDisappeared):
  635. pass
  636. if hexsha is None:
  637. hexsha = sha_to_hex(name)
  638. ret = self._get_loose_object(hexsha)
  639. if ret is not None:
  640. return ret.type_num, ret.as_raw_string()
  641. # Maybe something else has added a pack with the object
  642. # in the mean time?
  643. for pack in self._update_pack_cache():
  644. try:
  645. return pack.get_raw(sha)
  646. except KeyError:
  647. pass
  648. for alternate in self.alternates:
  649. try:
  650. return alternate.get_raw(hexsha)
  651. except KeyError:
  652. pass
  653. raise KeyError(hexsha)
  654. def iter_unpacked_subset(
  655. self,
  656. shas: set[bytes],
  657. include_comp: bool = False,
  658. allow_missing: bool = False,
  659. convert_ofs_delta: bool = True,
  660. ) -> Iterator[UnpackedObject]:
  661. todo: set[bytes] = set(shas)
  662. for p in self._iter_cached_packs():
  663. for unpacked in p.iter_unpacked_subset(
  664. todo,
  665. include_comp=include_comp,
  666. allow_missing=True,
  667. convert_ofs_delta=convert_ofs_delta,
  668. ):
  669. yield unpacked
  670. hexsha = sha_to_hex(unpacked.sha())
  671. todo.remove(hexsha)
  672. # Maybe something else has added a pack with the object
  673. # in the mean time?
  674. for p in self._update_pack_cache():
  675. for unpacked in p.iter_unpacked_subset(
  676. todo,
  677. include_comp=include_comp,
  678. allow_missing=True,
  679. convert_ofs_delta=convert_ofs_delta,
  680. ):
  681. yield unpacked
  682. hexsha = sha_to_hex(unpacked.sha())
  683. todo.remove(hexsha)
  684. for alternate in self.alternates:
  685. for unpacked in alternate.iter_unpacked_subset(
  686. todo,
  687. include_comp=include_comp,
  688. allow_missing=True,
  689. convert_ofs_delta=convert_ofs_delta,
  690. ):
  691. yield unpacked
  692. hexsha = sha_to_hex(unpacked.sha())
  693. todo.remove(hexsha)
  694. def iterobjects_subset(
  695. self, shas: Iterable[bytes], *, allow_missing: bool = False
  696. ) -> Iterator[ShaFile]:
  697. todo: set[bytes] = set(shas)
  698. for p in self._iter_cached_packs():
  699. for o in p.iterobjects_subset(todo, allow_missing=True):
  700. yield o
  701. todo.remove(o.id)
  702. # Maybe something else has added a pack with the object
  703. # in the mean time?
  704. for p in self._update_pack_cache():
  705. for o in p.iterobjects_subset(todo, allow_missing=True):
  706. yield o
  707. todo.remove(o.id)
  708. for alternate in self.alternates:
  709. for o in alternate.iterobjects_subset(todo, allow_missing=True):
  710. yield o
  711. todo.remove(o.id)
  712. for oid in todo:
  713. o = self._get_loose_object(oid)
  714. if o is not None:
  715. yield o
  716. elif not allow_missing:
  717. raise KeyError(oid)
  718. def get_unpacked_object(
  719. self, sha1: bytes, *, include_comp: bool = False
  720. ) -> UnpackedObject:
  721. """Obtain the unpacked object.
  722. Args:
  723. sha1: sha for the object.
  724. """
  725. if sha1 == ZERO_SHA:
  726. raise KeyError(sha1)
  727. if len(sha1) == 40:
  728. sha = hex_to_sha(sha1)
  729. hexsha = sha1
  730. elif len(sha1) == 20:
  731. sha = sha1
  732. hexsha = None
  733. else:
  734. raise AssertionError(f"Invalid object sha1 {sha1!r}")
  735. for pack in self._iter_cached_packs():
  736. try:
  737. return pack.get_unpacked_object(sha, include_comp=include_comp)
  738. except (KeyError, PackFileDisappeared):
  739. pass
  740. if hexsha is None:
  741. hexsha = sha_to_hex(sha1)
  742. # Maybe something else has added a pack with the object
  743. # in the mean time?
  744. for pack in self._update_pack_cache():
  745. try:
  746. return pack.get_unpacked_object(sha, include_comp=include_comp)
  747. except KeyError:
  748. pass
  749. for alternate in self.alternates:
  750. try:
  751. return alternate.get_unpacked_object(hexsha, include_comp=include_comp)
  752. except KeyError:
  753. pass
  754. raise KeyError(hexsha)
  755. def add_objects(
  756. self,
  757. objects: Sequence[tuple[ShaFile, Optional[str]]],
  758. progress: Optional[Callable[[str], None]] = None,
  759. ) -> None:
  760. """Add a set of objects to this object store.
  761. Args:
  762. objects: Iterable over (object, path) tuples, should support
  763. __len__.
  764. Returns: Pack object of the objects written.
  765. """
  766. count = len(objects)
  767. record_iter = (full_unpacked_object(o) for (o, p) in objects)
  768. return self.add_pack_data(count, record_iter, progress=progress)
  769. class DiskObjectStore(PackBasedObjectStore):
  770. """Git-style object store that exists on disk."""
  771. path: Union[str, os.PathLike]
  772. pack_dir: Union[str, os.PathLike]
  773. def __init__(
  774. self,
  775. path: Union[str, os.PathLike],
  776. loose_compression_level=-1,
  777. pack_compression_level=-1,
  778. pack_index_version=None,
  779. ) -> None:
  780. """Open an object store.
  781. Args:
  782. path: Path of the object store.
  783. loose_compression_level: zlib compression level for loose objects
  784. pack_compression_level: zlib compression level for pack objects
  785. pack_index_version: pack index version to use (1, 2, or 3)
  786. """
  787. super().__init__(
  788. pack_compression_level=pack_compression_level,
  789. pack_index_version=pack_index_version,
  790. )
  791. self.path = path
  792. self.pack_dir = os.path.join(self.path, PACKDIR)
  793. self._alternates = None
  794. self.loose_compression_level = loose_compression_level
  795. self.pack_compression_level = pack_compression_level
  796. self.pack_index_version = pack_index_version
  797. # Commit graph support - lazy loaded
  798. self._commit_graph = None
  799. def __repr__(self) -> str:
  800. return f"<{self.__class__.__name__}({self.path!r})>"
  801. @classmethod
  802. def from_config(cls, path: Union[str, os.PathLike], config):
  803. try:
  804. default_compression_level = int(
  805. config.get((b"core",), b"compression").decode()
  806. )
  807. except KeyError:
  808. default_compression_level = -1
  809. try:
  810. loose_compression_level = int(
  811. config.get((b"core",), b"looseCompression").decode()
  812. )
  813. except KeyError:
  814. loose_compression_level = default_compression_level
  815. try:
  816. pack_compression_level = int(
  817. config.get((b"core",), "packCompression").decode()
  818. )
  819. except KeyError:
  820. pack_compression_level = default_compression_level
  821. try:
  822. pack_index_version = int(config.get((b"pack",), b"indexVersion").decode())
  823. except KeyError:
  824. pack_index_version = None
  825. return cls(
  826. path, loose_compression_level, pack_compression_level, pack_index_version
  827. )
  828. @property
  829. def alternates(self):
  830. if self._alternates is not None:
  831. return self._alternates
  832. self._alternates = []
  833. for path in self._read_alternate_paths():
  834. self._alternates.append(DiskObjectStore(path))
  835. return self._alternates
  836. def _read_alternate_paths(self):
  837. try:
  838. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb")
  839. except FileNotFoundError:
  840. return
  841. with f:
  842. for line in f.readlines():
  843. line = line.rstrip(b"\n")
  844. if line.startswith(b"#"):
  845. continue
  846. if os.path.isabs(line):
  847. yield os.fsdecode(line)
  848. else:
  849. yield os.fsdecode(os.path.join(os.fsencode(self.path), line))
  850. def add_alternate_path(self, path) -> None:
  851. """Add an alternate path to this object store."""
  852. try:
  853. os.mkdir(os.path.join(self.path, INFODIR))
  854. except FileExistsError:
  855. pass
  856. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  857. with GitFile(alternates_path, "wb") as f:
  858. try:
  859. orig_f = open(alternates_path, "rb")
  860. except FileNotFoundError:
  861. pass
  862. else:
  863. with orig_f:
  864. f.write(orig_f.read())
  865. f.write(os.fsencode(path) + b"\n")
  866. if not os.path.isabs(path):
  867. path = os.path.join(self.path, path)
  868. self.alternates.append(DiskObjectStore(path))
  869. def _update_pack_cache(self):
  870. """Read and iterate over new pack files and cache them."""
  871. try:
  872. pack_dir_contents = os.listdir(self.pack_dir)
  873. except FileNotFoundError:
  874. self.close()
  875. return []
  876. pack_files = set()
  877. for name in pack_dir_contents:
  878. if name.startswith("pack-") and name.endswith(".pack"):
  879. # verify that idx exists first (otherwise the pack was not yet
  880. # fully written)
  881. idx_name = os.path.splitext(name)[0] + ".idx"
  882. if idx_name in pack_dir_contents:
  883. pack_name = name[: -len(".pack")]
  884. pack_files.add(pack_name)
  885. # Open newly appeared pack files
  886. new_packs = []
  887. for f in pack_files:
  888. if f not in self._pack_cache:
  889. pack = Pack(os.path.join(self.pack_dir, f))
  890. new_packs.append(pack)
  891. self._pack_cache[f] = pack
  892. # Remove disappeared pack files
  893. for f in set(self._pack_cache) - pack_files:
  894. self._pack_cache.pop(f).close()
  895. return new_packs
  896. def _get_shafile_path(self, sha):
  897. # Check from object dir
  898. return hex_to_filename(self.path, sha)
  899. def _iter_loose_objects(self):
  900. for base in os.listdir(self.path):
  901. if len(base) != 2:
  902. continue
  903. for rest in os.listdir(os.path.join(self.path, base)):
  904. sha = os.fsencode(base + rest)
  905. if not valid_hexsha(sha):
  906. continue
  907. yield sha
  908. def count_loose_objects(self) -> int:
  909. """Count the number of loose objects in the object store.
  910. Returns:
  911. Number of loose objects
  912. """
  913. count = 0
  914. if not os.path.exists(self.path):
  915. return 0
  916. for i in range(256):
  917. subdir = os.path.join(self.path, f"{i:02x}")
  918. try:
  919. count += len(
  920. [
  921. name
  922. for name in os.listdir(subdir)
  923. if len(name) == 38 # 40 - 2 for the prefix
  924. ]
  925. )
  926. except FileNotFoundError:
  927. # Directory may have been removed or is inaccessible
  928. continue
  929. return count
  930. def _get_loose_object(self, sha):
  931. path = self._get_shafile_path(sha)
  932. try:
  933. return ShaFile.from_path(path)
  934. except FileNotFoundError:
  935. return None
  936. def delete_loose_object(self, sha) -> None:
  937. os.remove(self._get_shafile_path(sha))
  938. def get_object_mtime(self, sha):
  939. """Get the modification time of an object.
  940. Args:
  941. sha: SHA1 of the object
  942. Returns:
  943. Modification time as seconds since epoch
  944. Raises:
  945. KeyError: if the object is not found
  946. """
  947. # First check if it's a loose object
  948. if self.contains_loose(sha):
  949. path = self._get_shafile_path(sha)
  950. try:
  951. return os.path.getmtime(path)
  952. except FileNotFoundError:
  953. pass
  954. # Check if it's in a pack file
  955. for pack in self.packs:
  956. try:
  957. if sha in pack:
  958. # Use the pack file's mtime for packed objects
  959. pack_path = pack._data_path
  960. try:
  961. return os.path.getmtime(pack_path)
  962. except (FileNotFoundError, AttributeError):
  963. pass
  964. except PackFileDisappeared:
  965. pass
  966. raise KeyError(sha)
  967. def _remove_pack(self, pack) -> None:
  968. try:
  969. del self._pack_cache[os.path.basename(pack._basename)]
  970. except KeyError:
  971. pass
  972. pack.close()
  973. os.remove(pack.data.path)
  974. os.remove(pack.index.path)
  975. def _get_pack_basepath(self, entries):
  976. suffix = iter_sha1(entry[0] for entry in entries)
  977. # TODO: Handle self.pack_dir being bytes
  978. suffix = suffix.decode("ascii")
  979. return os.path.join(self.pack_dir, "pack-" + suffix)
  980. def _complete_pack(self, f, path, num_objects, indexer, progress=None):
  981. """Move a specific file containing a pack into the pack directory.
  982. Note: The file should be on the same file system as the
  983. packs directory.
  984. Args:
  985. f: Open file object for the pack.
  986. path: Path to the pack file.
  987. indexer: A PackIndexer for indexing the pack.
  988. """
  989. entries = []
  990. for i, entry in enumerate(indexer):
  991. if progress is not None:
  992. progress(f"generating index: {i}/{num_objects}\r".encode("ascii"))
  993. entries.append(entry)
  994. pack_sha, extra_entries = extend_pack(
  995. f,
  996. indexer.ext_refs(),
  997. get_raw=self.get_raw,
  998. compression_level=self.pack_compression_level,
  999. progress=progress,
  1000. )
  1001. f.flush()
  1002. try:
  1003. fileno = f.fileno()
  1004. except AttributeError:
  1005. pass
  1006. else:
  1007. os.fsync(fileno)
  1008. f.close()
  1009. entries.extend(extra_entries)
  1010. # Move the pack in.
  1011. entries.sort()
  1012. pack_base_name = self._get_pack_basepath(entries)
  1013. for pack in self.packs:
  1014. if pack._basename == pack_base_name:
  1015. return pack
  1016. target_pack_path = pack_base_name + ".pack"
  1017. target_index_path = pack_base_name + ".idx"
  1018. if sys.platform == "win32":
  1019. # Windows might have the target pack file lingering. Attempt
  1020. # removal, silently passing if the target does not exist.
  1021. with suppress(FileNotFoundError):
  1022. os.remove(target_pack_path)
  1023. os.rename(path, target_pack_path)
  1024. # Write the index.
  1025. with GitFile(target_index_path, "wb", mask=PACK_MODE) as index_file:
  1026. write_pack_index(
  1027. index_file, entries, pack_sha, version=self.pack_index_version
  1028. )
  1029. # Add the pack to the store and return it.
  1030. final_pack = Pack(pack_base_name)
  1031. final_pack.check_length_and_checksum()
  1032. self._add_cached_pack(pack_base_name, final_pack)
  1033. return final_pack
  1034. def add_thin_pack(self, read_all, read_some, progress=None):
  1035. """Add a new thin pack to this object store.
  1036. Thin packs are packs that contain deltas with parents that exist
  1037. outside the pack. They should never be placed in the object store
  1038. directly, and always indexed and completed as they are copied.
  1039. Args:
  1040. read_all: Read function that blocks until the number of
  1041. requested bytes are read.
  1042. read_some: Read function that returns at least one byte, but may
  1043. not return the number of bytes requested.
  1044. Returns: A Pack object pointing at the now-completed thin pack in the
  1045. objects/pack directory.
  1046. """
  1047. import tempfile
  1048. fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_")
  1049. with os.fdopen(fd, "w+b") as f:
  1050. os.chmod(path, PACK_MODE)
  1051. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  1052. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  1053. copier.verify(progress=progress)
  1054. return self._complete_pack(f, path, len(copier), indexer, progress=progress)
  1055. def add_pack(self):
  1056. """Add a new pack to this object store.
  1057. Returns: Fileobject to write to, a commit function to
  1058. call when the pack is finished and an abort
  1059. function.
  1060. """
  1061. import tempfile
  1062. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  1063. f = os.fdopen(fd, "w+b")
  1064. os.chmod(path, PACK_MODE)
  1065. def commit():
  1066. if f.tell() > 0:
  1067. f.seek(0)
  1068. with PackData(path, f) as pd:
  1069. indexer = PackIndexer.for_pack_data(
  1070. pd, resolve_ext_ref=self.get_raw
  1071. )
  1072. return self._complete_pack(f, path, len(pd), indexer)
  1073. else:
  1074. f.close()
  1075. os.remove(path)
  1076. return None
  1077. def abort() -> None:
  1078. f.close()
  1079. os.remove(path)
  1080. return f, commit, abort
  1081. def add_object(self, obj) -> None:
  1082. """Add a single object to this object store.
  1083. Args:
  1084. obj: Object to add
  1085. """
  1086. path = self._get_shafile_path(obj.id)
  1087. dir = os.path.dirname(path)
  1088. try:
  1089. os.mkdir(dir)
  1090. except FileExistsError:
  1091. pass
  1092. if os.path.exists(path):
  1093. return # Already there, no need to write again
  1094. with GitFile(path, "wb", mask=PACK_MODE) as f:
  1095. f.write(
  1096. obj.as_legacy_object(compression_level=self.loose_compression_level)
  1097. )
  1098. @classmethod
  1099. def init(cls, path: Union[str, os.PathLike]):
  1100. try:
  1101. os.mkdir(path)
  1102. except FileExistsError:
  1103. pass
  1104. os.mkdir(os.path.join(path, "info"))
  1105. os.mkdir(os.path.join(path, PACKDIR))
  1106. return cls(path)
  1107. def iter_prefix(self, prefix):
  1108. if len(prefix) < 2:
  1109. yield from super().iter_prefix(prefix)
  1110. return
  1111. seen = set()
  1112. dir = prefix[:2].decode()
  1113. rest = prefix[2:].decode()
  1114. try:
  1115. for name in os.listdir(os.path.join(self.path, dir)):
  1116. if name.startswith(rest):
  1117. sha = os.fsencode(dir + name)
  1118. if sha not in seen:
  1119. seen.add(sha)
  1120. yield sha
  1121. except FileNotFoundError:
  1122. pass
  1123. for p in self.packs:
  1124. bin_prefix = (
  1125. binascii.unhexlify(prefix)
  1126. if len(prefix) % 2 == 0
  1127. else binascii.unhexlify(prefix[:-1])
  1128. )
  1129. for sha in p.index.iter_prefix(bin_prefix):
  1130. sha = sha_to_hex(sha)
  1131. if sha.startswith(prefix) and sha not in seen:
  1132. seen.add(sha)
  1133. yield sha
  1134. for alternate in self.alternates:
  1135. for sha in alternate.iter_prefix(prefix):
  1136. if sha not in seen:
  1137. seen.add(sha)
  1138. yield sha
  1139. def get_commit_graph(self):
  1140. """Get the commit graph for this object store.
  1141. Returns:
  1142. CommitGraph object if available, None otherwise
  1143. """
  1144. if self._commit_graph is None:
  1145. from .commit_graph import read_commit_graph
  1146. # Look for commit graph in our objects directory
  1147. graph_file = os.path.join(self.path, "info", "commit-graph")
  1148. if os.path.exists(graph_file):
  1149. self._commit_graph = read_commit_graph(graph_file)
  1150. return self._commit_graph
  1151. def write_commit_graph(self, refs=None, reachable=True) -> None:
  1152. """Write a commit graph file for this object store.
  1153. Args:
  1154. refs: List of refs to include. If None, includes all refs from object store.
  1155. reachable: If True, includes all commits reachable from refs.
  1156. If False, only includes the direct ref targets.
  1157. """
  1158. from .commit_graph import get_reachable_commits
  1159. if refs is None:
  1160. # Get all commit objects from the object store
  1161. all_refs = []
  1162. # Iterate through all objects to find commits
  1163. for sha in self:
  1164. try:
  1165. obj = self[sha]
  1166. if obj.type_name == b"commit":
  1167. all_refs.append(sha)
  1168. except KeyError:
  1169. continue
  1170. else:
  1171. # Use provided refs
  1172. all_refs = refs
  1173. if not all_refs:
  1174. return # No commits to include
  1175. if reachable:
  1176. # Get all reachable commits
  1177. commit_ids = get_reachable_commits(self, all_refs)
  1178. else:
  1179. # Just use the direct ref targets - ensure they're hex ObjectIDs
  1180. commit_ids = []
  1181. for ref in all_refs:
  1182. if isinstance(ref, bytes) and len(ref) == 40:
  1183. # Already hex ObjectID
  1184. commit_ids.append(ref)
  1185. elif isinstance(ref, bytes) and len(ref) == 20:
  1186. # Binary SHA, convert to hex ObjectID
  1187. from .objects import sha_to_hex
  1188. commit_ids.append(sha_to_hex(ref))
  1189. else:
  1190. # Assume it's already correct format
  1191. commit_ids.append(ref)
  1192. if commit_ids:
  1193. # Write commit graph directly to our object store path
  1194. # Generate the commit graph
  1195. from .commit_graph import generate_commit_graph
  1196. graph = generate_commit_graph(self, commit_ids)
  1197. if graph.entries:
  1198. # Ensure the info directory exists
  1199. info_dir = os.path.join(self.path, "info")
  1200. os.makedirs(info_dir, exist_ok=True)
  1201. # Write using GitFile for atomic operation
  1202. graph_path = os.path.join(info_dir, "commit-graph")
  1203. with GitFile(graph_path, "wb") as f:
  1204. graph.write_to_file(f)
  1205. # Clear cached commit graph so it gets reloaded
  1206. self._commit_graph = None
  1207. def prune(self, grace_period: Optional[int] = None) -> None:
  1208. """Prune/clean up this object store.
  1209. This removes temporary files that were left behind by interrupted
  1210. pack operations. These are files that start with 'tmp_pack_' in the
  1211. repository directory or files with .pack extension but no corresponding
  1212. .idx file in the pack directory.
  1213. Args:
  1214. grace_period: Grace period in seconds for removing temporary files.
  1215. If None, uses DEFAULT_TEMPFILE_GRACE_PERIOD.
  1216. """
  1217. import glob
  1218. if grace_period is None:
  1219. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  1220. # Clean up tmp_pack_* files in the repository directory
  1221. for tmp_file in glob.glob(os.path.join(self.path, "tmp_pack_*")):
  1222. # Check if file is old enough (more than grace period)
  1223. mtime = os.path.getmtime(tmp_file)
  1224. if time.time() - mtime > grace_period:
  1225. os.remove(tmp_file)
  1226. # Clean up orphaned .pack files without corresponding .idx files
  1227. try:
  1228. pack_dir_contents = os.listdir(self.pack_dir)
  1229. except FileNotFoundError:
  1230. return
  1231. pack_files = {}
  1232. idx_files = set()
  1233. for name in pack_dir_contents:
  1234. if name.endswith(".pack"):
  1235. base_name = name[:-5] # Remove .pack extension
  1236. pack_files[base_name] = name
  1237. elif name.endswith(".idx"):
  1238. base_name = name[:-4] # Remove .idx extension
  1239. idx_files.add(base_name)
  1240. # Remove .pack files without corresponding .idx files
  1241. for base_name, pack_name in pack_files.items():
  1242. if base_name not in idx_files:
  1243. pack_path = os.path.join(self.pack_dir, pack_name)
  1244. # Check if file is old enough (more than grace period)
  1245. mtime = os.path.getmtime(pack_path)
  1246. if time.time() - mtime > grace_period:
  1247. os.remove(pack_path)
  1248. class MemoryObjectStore(BaseObjectStore):
  1249. """Object store that keeps all objects in memory."""
  1250. def __init__(self) -> None:
  1251. super().__init__()
  1252. self._data: dict[str, ShaFile] = {}
  1253. self.pack_compression_level = -1
  1254. def _to_hexsha(self, sha):
  1255. if len(sha) == 40:
  1256. return sha
  1257. elif len(sha) == 20:
  1258. return sha_to_hex(sha)
  1259. else:
  1260. raise ValueError(f"Invalid sha {sha!r}")
  1261. def contains_loose(self, sha):
  1262. """Check if a particular object is present by SHA1 and is loose."""
  1263. return self._to_hexsha(sha) in self._data
  1264. def contains_packed(self, sha) -> bool:
  1265. """Check if a particular object is present by SHA1 and is packed."""
  1266. return False
  1267. def __iter__(self):
  1268. """Iterate over the SHAs that are present in this store."""
  1269. return iter(self._data.keys())
  1270. @property
  1271. def packs(self):
  1272. """List with pack objects."""
  1273. return []
  1274. def get_raw(self, name: ObjectID):
  1275. """Obtain the raw text for an object.
  1276. Args:
  1277. name: sha for the object.
  1278. Returns: tuple with numeric type and object contents.
  1279. """
  1280. obj = self[self._to_hexsha(name)]
  1281. return obj.type_num, obj.as_raw_string()
  1282. def __getitem__(self, name: ObjectID):
  1283. return self._data[self._to_hexsha(name)].copy()
  1284. def __delitem__(self, name: ObjectID) -> None:
  1285. """Delete an object from this store, for testing only."""
  1286. del self._data[self._to_hexsha(name)]
  1287. def add_object(self, obj) -> None:
  1288. """Add a single object to this object store."""
  1289. self._data[obj.id] = obj.copy()
  1290. def add_objects(self, objects, progress=None) -> None:
  1291. """Add a set of objects to this object store.
  1292. Args:
  1293. objects: Iterable over a list of (object, path) tuples
  1294. """
  1295. for obj, path in objects:
  1296. self.add_object(obj)
  1297. def add_pack(self):
  1298. """Add a new pack to this object store.
  1299. Because this object store doesn't support packs, we extract and add the
  1300. individual objects.
  1301. Returns: Fileobject to write to and a commit function to
  1302. call when the pack is finished.
  1303. """
  1304. from tempfile import SpooledTemporaryFile
  1305. f = SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-")
  1306. def commit() -> None:
  1307. size = f.tell()
  1308. if size > 0:
  1309. f.seek(0)
  1310. p = PackData.from_file(f, size)
  1311. for obj in PackInflater.for_pack_data(p, self.get_raw):
  1312. self.add_object(obj)
  1313. p.close()
  1314. f.close()
  1315. else:
  1316. f.close()
  1317. def abort() -> None:
  1318. f.close()
  1319. return f, commit, abort
  1320. def add_pack_data(
  1321. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  1322. ) -> None:
  1323. """Add pack data to this object store.
  1324. Args:
  1325. count: Number of items to add
  1326. """
  1327. if count == 0:
  1328. return
  1329. # Since MemoryObjectStore doesn't support pack files, we need to
  1330. # extract individual objects. To handle deltas properly, we write
  1331. # to a temporary pack and then use PackInflater to resolve them.
  1332. f, commit, abort = self.add_pack()
  1333. try:
  1334. write_pack_data(
  1335. f.write,
  1336. unpacked_objects,
  1337. num_records=count,
  1338. progress=progress,
  1339. )
  1340. except BaseException:
  1341. abort()
  1342. raise
  1343. else:
  1344. commit()
  1345. def add_thin_pack(self, read_all, read_some, progress=None) -> None:
  1346. """Add a new thin pack to this object store.
  1347. Thin packs are packs that contain deltas with parents that exist
  1348. outside the pack. Because this object store doesn't support packs, we
  1349. extract and add the individual objects.
  1350. Args:
  1351. read_all: Read function that blocks until the number of
  1352. requested bytes are read.
  1353. read_some: Read function that returns at least one byte, but may
  1354. not return the number of bytes requested.
  1355. """
  1356. f, commit, abort = self.add_pack()
  1357. try:
  1358. copier = PackStreamCopier(read_all, read_some, f)
  1359. copier.verify()
  1360. except BaseException:
  1361. abort()
  1362. raise
  1363. else:
  1364. commit()
  1365. class ObjectIterator(Protocol):
  1366. """Interface for iterating over objects."""
  1367. def iterobjects(self) -> Iterator[ShaFile]:
  1368. raise NotImplementedError(self.iterobjects)
  1369. def tree_lookup_path(lookup_obj, root_sha, path):
  1370. """Look up an object in a Git tree.
  1371. Args:
  1372. lookup_obj: Callback for retrieving object by SHA1
  1373. root_sha: SHA1 of the root tree
  1374. path: Path to lookup
  1375. Returns: A tuple of (mode, SHA) of the resulting path.
  1376. """
  1377. tree = lookup_obj(root_sha)
  1378. if not isinstance(tree, Tree):
  1379. raise NotTreeError(root_sha)
  1380. return tree.lookup_path(lookup_obj, path)
  1381. def _collect_filetree_revs(
  1382. obj_store: ObjectContainer, tree_sha: ObjectID, kset: set[ObjectID]
  1383. ) -> None:
  1384. """Collect SHA1s of files and directories for specified tree.
  1385. Args:
  1386. obj_store: Object store to get objects by SHA from
  1387. tree_sha: tree reference to walk
  1388. kset: set to fill with references to files and directories
  1389. """
  1390. filetree = obj_store[tree_sha]
  1391. assert isinstance(filetree, Tree)
  1392. for name, mode, sha in filetree.iteritems():
  1393. if not S_ISGITLINK(mode) and sha not in kset:
  1394. kset.add(sha)
  1395. if stat.S_ISDIR(mode):
  1396. _collect_filetree_revs(obj_store, sha, kset)
  1397. def _split_commits_and_tags(
  1398. obj_store: ObjectContainer, lst, *, ignore_unknown=False
  1399. ) -> tuple[set[bytes], set[bytes], set[bytes]]:
  1400. """Split object id list into three lists with commit, tag, and other SHAs.
  1401. Commits referenced by tags are included into commits
  1402. list as well. Only SHA1s known in this repository will get
  1403. through, and unless ignore_unknown argument is True, KeyError
  1404. is thrown for SHA1 missing in the repository
  1405. Args:
  1406. obj_store: Object store to get objects by SHA1 from
  1407. lst: Collection of commit and tag SHAs
  1408. ignore_unknown: True to skip SHA1 missing in the repository
  1409. silently.
  1410. Returns: A tuple of (commits, tags, others) SHA1s
  1411. """
  1412. commits: set[bytes] = set()
  1413. tags: set[bytes] = set()
  1414. others: set[bytes] = set()
  1415. for e in lst:
  1416. try:
  1417. o = obj_store[e]
  1418. except KeyError:
  1419. if not ignore_unknown:
  1420. raise
  1421. else:
  1422. if isinstance(o, Commit):
  1423. commits.add(e)
  1424. elif isinstance(o, Tag):
  1425. tags.add(e)
  1426. tagged = o.object[1]
  1427. c, t, os = _split_commits_and_tags(
  1428. obj_store, [tagged], ignore_unknown=ignore_unknown
  1429. )
  1430. commits |= c
  1431. tags |= t
  1432. others |= os
  1433. else:
  1434. others.add(e)
  1435. return (commits, tags, others)
  1436. class MissingObjectFinder:
  1437. """Find the objects missing from another object store.
  1438. Args:
  1439. object_store: Object store containing at least all objects to be
  1440. sent
  1441. haves: SHA1s of commits not to send (already present in target)
  1442. wants: SHA1s of commits to send
  1443. progress: Optional function to report progress to.
  1444. get_tagged: Function that returns a dict of pointed-to sha -> tag
  1445. sha for including tags.
  1446. get_parents: Optional function for getting the parents of a commit.
  1447. """
  1448. def __init__(
  1449. self,
  1450. object_store,
  1451. haves,
  1452. wants,
  1453. *,
  1454. shallow=None,
  1455. progress=None,
  1456. get_tagged=None,
  1457. get_parents=lambda commit: commit.parents,
  1458. ) -> None:
  1459. self.object_store = object_store
  1460. if shallow is None:
  1461. shallow = set()
  1462. self._get_parents = get_parents
  1463. # process Commits and Tags differently
  1464. # Note, while haves may list commits/tags not available locally,
  1465. # and such SHAs would get filtered out by _split_commits_and_tags,
  1466. # wants shall list only known SHAs, and otherwise
  1467. # _split_commits_and_tags fails with KeyError
  1468. have_commits, have_tags, have_others = _split_commits_and_tags(
  1469. object_store, haves, ignore_unknown=True
  1470. )
  1471. want_commits, want_tags, want_others = _split_commits_and_tags(
  1472. object_store, wants, ignore_unknown=False
  1473. )
  1474. # all_ancestors is a set of commits that shall not be sent
  1475. # (complete repository up to 'haves')
  1476. all_ancestors = _collect_ancestors(
  1477. object_store, have_commits, shallow=shallow, get_parents=self._get_parents
  1478. )[0]
  1479. # all_missing - complete set of commits between haves and wants
  1480. # common - commits from all_ancestors we hit into while
  1481. # traversing parent hierarchy of wants
  1482. missing_commits, common_commits = _collect_ancestors(
  1483. object_store,
  1484. want_commits,
  1485. all_ancestors,
  1486. shallow=shallow,
  1487. get_parents=self._get_parents,
  1488. )
  1489. self.remote_has: set[bytes] = set()
  1490. # Now, fill sha_done with commits and revisions of
  1491. # files and directories known to be both locally
  1492. # and on target. Thus these commits and files
  1493. # won't get selected for fetch
  1494. for h in common_commits:
  1495. self.remote_has.add(h)
  1496. cmt = object_store[h]
  1497. _collect_filetree_revs(object_store, cmt.tree, self.remote_has)
  1498. # record tags we have as visited, too
  1499. for t in have_tags:
  1500. self.remote_has.add(t)
  1501. self.sha_done = set(self.remote_has)
  1502. # in fact, what we 'want' is commits, tags, and others
  1503. # we've found missing
  1504. self.objects_to_send: set[
  1505. tuple[ObjectID, Optional[bytes], Optional[int], bool]
  1506. ] = {(w, None, Commit.type_num, False) for w in missing_commits}
  1507. missing_tags = want_tags.difference(have_tags)
  1508. self.objects_to_send.update(
  1509. {(w, None, Tag.type_num, False) for w in missing_tags}
  1510. )
  1511. missing_others = want_others.difference(have_others)
  1512. self.objects_to_send.update({(w, None, None, False) for w in missing_others})
  1513. if progress is None:
  1514. self.progress = lambda x: None
  1515. else:
  1516. self.progress = progress
  1517. self._tagged = (get_tagged and get_tagged()) or {}
  1518. def get_remote_has(self):
  1519. return self.remote_has
  1520. def add_todo(
  1521. self, entries: Iterable[tuple[ObjectID, Optional[bytes], Optional[int], bool]]
  1522. ) -> None:
  1523. self.objects_to_send.update([e for e in entries if e[0] not in self.sha_done])
  1524. def __next__(self) -> tuple[bytes, Optional[PackHint]]:
  1525. while True:
  1526. if not self.objects_to_send:
  1527. self.progress(
  1528. f"counting objects: {len(self.sha_done)}, done.\n".encode("ascii")
  1529. )
  1530. raise StopIteration
  1531. (sha, name, type_num, leaf) = self.objects_to_send.pop()
  1532. if sha not in self.sha_done:
  1533. break
  1534. if not leaf:
  1535. o = self.object_store[sha]
  1536. if isinstance(o, Commit):
  1537. self.add_todo([(o.tree, b"", Tree.type_num, False)])
  1538. elif isinstance(o, Tree):
  1539. self.add_todo(
  1540. [
  1541. (
  1542. s,
  1543. n,
  1544. (Blob.type_num if stat.S_ISREG(m) else Tree.type_num),
  1545. not stat.S_ISDIR(m),
  1546. )
  1547. for n, m, s in o.iteritems()
  1548. if not S_ISGITLINK(m)
  1549. ]
  1550. )
  1551. elif isinstance(o, Tag):
  1552. self.add_todo([(o.object[1], None, o.object[0].type_num, False)])
  1553. if sha in self._tagged:
  1554. self.add_todo([(self._tagged[sha], None, None, True)])
  1555. self.sha_done.add(sha)
  1556. if len(self.sha_done) % 1000 == 0:
  1557. self.progress(f"counting objects: {len(self.sha_done)}\r".encode("ascii"))
  1558. if type_num is None:
  1559. pack_hint = None
  1560. else:
  1561. pack_hint = (type_num, name)
  1562. return (sha, pack_hint)
  1563. def __iter__(self):
  1564. return self
  1565. class ObjectStoreGraphWalker:
  1566. """Graph walker that finds what commits are missing from an object store."""
  1567. heads: set[ObjectID]
  1568. """Revisions without descendants in the local repo."""
  1569. get_parents: Callable[[ObjectID], ObjectID]
  1570. """Function to retrieve parents in the local repo."""
  1571. shallow: set[ObjectID]
  1572. def __init__(
  1573. self,
  1574. local_heads: Iterable[ObjectID],
  1575. get_parents,
  1576. shallow: Optional[set[ObjectID]] = None,
  1577. update_shallow=None,
  1578. ) -> None:
  1579. """Create a new instance.
  1580. Args:
  1581. local_heads: Heads to start search with
  1582. get_parents: Function for finding the parents of a SHA1.
  1583. """
  1584. self.heads = set(local_heads)
  1585. self.get_parents = get_parents
  1586. self.parents: dict[ObjectID, Optional[list[ObjectID]]] = {}
  1587. if shallow is None:
  1588. shallow = set()
  1589. self.shallow = shallow
  1590. self.update_shallow = update_shallow
  1591. def nak(self) -> None:
  1592. """Nothing in common was found."""
  1593. def ack(self, sha: ObjectID) -> None:
  1594. """Ack that a revision and its ancestors are present in the source."""
  1595. if len(sha) != 40:
  1596. raise ValueError(f"unexpected sha {sha!r} received")
  1597. ancestors = {sha}
  1598. # stop if we run out of heads to remove
  1599. while self.heads:
  1600. for a in ancestors:
  1601. if a in self.heads:
  1602. self.heads.remove(a)
  1603. # collect all ancestors
  1604. new_ancestors = set()
  1605. for a in ancestors:
  1606. ps = self.parents.get(a)
  1607. if ps is not None:
  1608. new_ancestors.update(ps)
  1609. self.parents[a] = None
  1610. # no more ancestors; stop
  1611. if not new_ancestors:
  1612. break
  1613. ancestors = new_ancestors
  1614. def next(self):
  1615. """Iterate over ancestors of heads in the target."""
  1616. if self.heads:
  1617. ret = self.heads.pop()
  1618. try:
  1619. ps = self.get_parents(ret)
  1620. except KeyError:
  1621. return None
  1622. self.parents[ret] = ps
  1623. self.heads.update([p for p in ps if p not in self.parents])
  1624. return ret
  1625. return None
  1626. __next__ = next
  1627. def commit_tree_changes(object_store, tree, changes):
  1628. """Commit a specified set of changes to a tree structure.
  1629. This will apply a set of changes on top of an existing tree, storing new
  1630. objects in object_store.
  1631. changes are a list of tuples with (path, mode, object_sha).
  1632. Paths can be both blobs and trees. See the mode and
  1633. object sha to None deletes the path.
  1634. This method works especially well if there are only a small
  1635. number of changes to a big tree. For a large number of changes
  1636. to a large tree, use e.g. commit_tree.
  1637. Args:
  1638. object_store: Object store to store new objects in
  1639. and retrieve old ones from.
  1640. tree: Original tree root
  1641. changes: changes to apply
  1642. Returns: New tree root object
  1643. """
  1644. # TODO(jelmer): Save up the objects and add them using .add_objects
  1645. # rather than with individual calls to .add_object.
  1646. nested_changes = {}
  1647. for path, new_mode, new_sha in changes:
  1648. try:
  1649. (dirname, subpath) = path.split(b"/", 1)
  1650. except ValueError:
  1651. if new_sha is None:
  1652. del tree[path]
  1653. else:
  1654. tree[path] = (new_mode, new_sha)
  1655. else:
  1656. nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha))
  1657. for name, subchanges in nested_changes.items():
  1658. try:
  1659. orig_subtree = object_store[tree[name][1]]
  1660. except KeyError:
  1661. orig_subtree = Tree()
  1662. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1663. if len(subtree) == 0:
  1664. del tree[name]
  1665. else:
  1666. tree[name] = (stat.S_IFDIR, subtree.id)
  1667. object_store.add_object(tree)
  1668. return tree
  1669. class OverlayObjectStore(BaseObjectStore):
  1670. """Object store that can overlay multiple object stores."""
  1671. def __init__(self, bases, add_store=None) -> None:
  1672. self.bases = bases
  1673. self.add_store = add_store
  1674. def add_object(self, object):
  1675. if self.add_store is None:
  1676. raise NotImplementedError(self.add_object)
  1677. return self.add_store.add_object(object)
  1678. def add_objects(self, objects, progress=None):
  1679. if self.add_store is None:
  1680. raise NotImplementedError(self.add_object)
  1681. return self.add_store.add_objects(objects, progress)
  1682. @property
  1683. def packs(self):
  1684. ret = []
  1685. for b in self.bases:
  1686. ret.extend(b.packs)
  1687. return ret
  1688. def __iter__(self):
  1689. done = set()
  1690. for b in self.bases:
  1691. for o_id in b:
  1692. if o_id not in done:
  1693. yield o_id
  1694. done.add(o_id)
  1695. def iterobjects_subset(
  1696. self, shas: Iterable[bytes], *, allow_missing: bool = False
  1697. ) -> Iterator[ShaFile]:
  1698. todo = set(shas)
  1699. found: set[bytes] = set()
  1700. for b in self.bases:
  1701. # Create a copy of todo for each base to avoid modifying
  1702. # the set while iterating through it
  1703. current_todo = todo - found
  1704. for o in b.iterobjects_subset(current_todo, allow_missing=True):
  1705. yield o
  1706. found.add(o.id)
  1707. # Check for any remaining objects not found
  1708. missing = todo - found
  1709. if missing and not allow_missing:
  1710. raise KeyError(next(iter(missing)))
  1711. def iter_unpacked_subset(
  1712. self,
  1713. shas: Iterable[bytes],
  1714. *,
  1715. include_comp=False,
  1716. allow_missing: bool = False,
  1717. convert_ofs_delta=True,
  1718. ) -> Iterator[ShaFile]:
  1719. todo = set(shas)
  1720. for b in self.bases:
  1721. for o in b.iter_unpacked_subset(
  1722. todo,
  1723. include_comp=include_comp,
  1724. allow_missing=True,
  1725. convert_ofs_delta=convert_ofs_delta,
  1726. ):
  1727. yield o
  1728. todo.remove(o.id)
  1729. if todo and not allow_missing:
  1730. raise KeyError(o.id)
  1731. def get_raw(self, sha_id):
  1732. for b in self.bases:
  1733. try:
  1734. return b.get_raw(sha_id)
  1735. except KeyError:
  1736. pass
  1737. raise KeyError(sha_id)
  1738. def contains_packed(self, sha) -> bool:
  1739. for b in self.bases:
  1740. if b.contains_packed(sha):
  1741. return True
  1742. return False
  1743. def contains_loose(self, sha) -> bool:
  1744. for b in self.bases:
  1745. if b.contains_loose(sha):
  1746. return True
  1747. return False
  1748. def read_packs_file(f):
  1749. """Yield the packs listed in a packs file."""
  1750. for line in f.read().splitlines():
  1751. if not line:
  1752. continue
  1753. (kind, name) = line.split(b" ", 1)
  1754. if kind != b"P":
  1755. continue
  1756. yield os.fsdecode(name)
  1757. class BucketBasedObjectStore(PackBasedObjectStore):
  1758. """Object store implementation that uses a bucket store like S3 as backend."""
  1759. def _iter_loose_objects(self):
  1760. """Iterate over the SHAs of all loose objects."""
  1761. return iter([])
  1762. def _get_loose_object(self, sha) -> None:
  1763. return None
  1764. def delete_loose_object(self, sha) -> None:
  1765. # Doesn't exist..
  1766. pass
  1767. def _remove_pack(self, name) -> None:
  1768. raise NotImplementedError(self._remove_pack)
  1769. def _iter_pack_names(self) -> Iterator[str]:
  1770. raise NotImplementedError(self._iter_pack_names)
  1771. def _get_pack(self, name) -> Pack:
  1772. raise NotImplementedError(self._get_pack)
  1773. def _update_pack_cache(self):
  1774. pack_files = set(self._iter_pack_names())
  1775. # Open newly appeared pack files
  1776. new_packs = []
  1777. for f in pack_files:
  1778. if f not in self._pack_cache:
  1779. pack = self._get_pack(f)
  1780. new_packs.append(pack)
  1781. self._pack_cache[f] = pack
  1782. # Remove disappeared pack files
  1783. for f in set(self._pack_cache) - pack_files:
  1784. self._pack_cache.pop(f).close()
  1785. return new_packs
  1786. def _upload_pack(self, basename, pack_file, index_file) -> None:
  1787. raise NotImplementedError
  1788. def add_pack(self):
  1789. """Add a new pack to this object store.
  1790. Returns: Fileobject to write to, a commit function to
  1791. call when the pack is finished and an abort
  1792. function.
  1793. """
  1794. import tempfile
  1795. pf = tempfile.SpooledTemporaryFile(
  1796. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1797. )
  1798. def commit():
  1799. if pf.tell() == 0:
  1800. pf.close()
  1801. return None
  1802. pf.seek(0)
  1803. p = PackData(pf.name, pf)
  1804. entries = p.sorted_entries()
  1805. basename = iter_sha1(entry[0] for entry in entries).decode("ascii")
  1806. idxf = tempfile.SpooledTemporaryFile(
  1807. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1808. )
  1809. checksum = p.get_stored_checksum()
  1810. write_pack_index(idxf, entries, checksum, version=self.pack_index_version)
  1811. idxf.seek(0)
  1812. idx = load_pack_index_file(basename + ".idx", idxf)
  1813. for pack in self.packs:
  1814. if pack.get_stored_checksum() == p.get_stored_checksum():
  1815. p.close()
  1816. idx.close()
  1817. pf.close()
  1818. idxf.close()
  1819. return pack
  1820. pf.seek(0)
  1821. idxf.seek(0)
  1822. self._upload_pack(basename, pf, idxf)
  1823. final_pack = Pack.from_objects(p, idx)
  1824. self._add_cached_pack(basename, final_pack)
  1825. pf.close()
  1826. idxf.close()
  1827. return final_pack
  1828. return pf, commit, pf.close
  1829. def _collect_ancestors(
  1830. store: ObjectContainer,
  1831. heads,
  1832. common: frozenset[ObjectID] = frozenset(),
  1833. shallow: frozenset[ObjectID] = frozenset(),
  1834. get_parents=lambda commit: commit.parents,
  1835. ):
  1836. """Collect all ancestors of heads up to (excluding) those in common.
  1837. Args:
  1838. heads: commits to start from
  1839. common: commits to end at, or empty set to walk repository
  1840. completely
  1841. get_parents: Optional function for getting the parents of a
  1842. commit.
  1843. Returns: a tuple (A, B) where A - all commits reachable
  1844. from heads but not present in common, B - common (shared) elements
  1845. that are directly reachable from heads
  1846. """
  1847. bases = set()
  1848. commits = set()
  1849. queue = []
  1850. queue.extend(heads)
  1851. while queue:
  1852. e = queue.pop(0)
  1853. if e in common:
  1854. bases.add(e)
  1855. elif e not in commits:
  1856. commits.add(e)
  1857. if e in shallow:
  1858. continue
  1859. cmt = store[e]
  1860. queue.extend(get_parents(cmt))
  1861. return (commits, bases)
  1862. def iter_tree_contents(
  1863. store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False
  1864. ):
  1865. """Iterate the contents of a tree and all subtrees.
  1866. Iteration is depth-first pre-order, as in e.g. os.walk.
  1867. Args:
  1868. tree_id: SHA1 of the tree.
  1869. include_trees: If True, include tree objects in the iteration.
  1870. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  1871. tree.
  1872. """
  1873. if tree_id is None:
  1874. return
  1875. # This could be fairly easily generalized to >2 trees if we find a use
  1876. # case.
  1877. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)]
  1878. while todo:
  1879. entry = todo.pop()
  1880. if stat.S_ISDIR(entry.mode):
  1881. extra = []
  1882. tree = store[entry.sha]
  1883. assert isinstance(tree, Tree)
  1884. for subentry in tree.iteritems(name_order=True):
  1885. extra.append(subentry.in_path(entry.path))
  1886. todo.extend(reversed(extra))
  1887. if not stat.S_ISDIR(entry.mode) or include_trees:
  1888. yield entry
  1889. def peel_sha(store: ObjectContainer, sha: bytes) -> tuple[ShaFile, ShaFile]:
  1890. """Peel all tags from a SHA.
  1891. Args:
  1892. sha: The object SHA to peel.
  1893. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  1894. intermediate tags; if the original ref does not point to a tag,
  1895. this will equal the original SHA1.
  1896. """
  1897. unpeeled = obj = store[sha]
  1898. obj_class = object_class(obj.type_name)
  1899. while obj_class is Tag:
  1900. assert isinstance(obj, Tag)
  1901. obj_class, sha = obj.object
  1902. obj = store[sha]
  1903. return unpeeled, obj