object_store.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. # and others
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Git object store interfaces and implementation."""
  22. from io import BytesIO
  23. import os
  24. import stat
  25. import sys
  26. from dulwich.diff_tree import (
  27. tree_changes,
  28. walk_trees,
  29. )
  30. from dulwich.errors import (
  31. NotTreeError,
  32. )
  33. from dulwich.file import GitFile
  34. from dulwich.objects import (
  35. Commit,
  36. ShaFile,
  37. Tag,
  38. Tree,
  39. ZERO_SHA,
  40. hex_to_sha,
  41. sha_to_hex,
  42. hex_to_filename,
  43. S_ISGITLINK,
  44. object_class,
  45. valid_hexsha,
  46. )
  47. from dulwich.pack import (
  48. Pack,
  49. PackData,
  50. PackInflater,
  51. PackFileDisappeared,
  52. iter_sha1,
  53. pack_objects_to_data,
  54. write_pack_header,
  55. write_pack_index_v2,
  56. write_pack_data,
  57. write_pack_object,
  58. compute_file_sha,
  59. PackIndexer,
  60. PackStreamCopier,
  61. )
  62. from dulwich.refs import ANNOTATED_TAG_SUFFIX
  63. INFODIR = 'info'
  64. PACKDIR = 'pack'
  65. class BaseObjectStore(object):
  66. """Object store interface."""
  67. def determine_wants_all(self, refs):
  68. return [sha for (ref, sha) in refs.items()
  69. if sha not in self and
  70. not ref.endswith(ANNOTATED_TAG_SUFFIX) and
  71. not sha == ZERO_SHA]
  72. def iter_shas(self, shas):
  73. """Iterate over the objects for the specified shas.
  74. Args:
  75. shas: Iterable object with SHAs
  76. Returns: Object iterator
  77. """
  78. return ObjectStoreIterator(self, shas)
  79. def contains_loose(self, sha):
  80. """Check if a particular object is present by SHA1 and is loose."""
  81. raise NotImplementedError(self.contains_loose)
  82. def contains_packed(self, sha):
  83. """Check if a particular object is present by SHA1 and is packed."""
  84. raise NotImplementedError(self.contains_packed)
  85. def __contains__(self, sha):
  86. """Check if a particular object is present by SHA1.
  87. This method makes no distinction between loose and packed objects.
  88. """
  89. return self.contains_packed(sha) or self.contains_loose(sha)
  90. @property
  91. def packs(self):
  92. """Iterable of pack objects."""
  93. raise NotImplementedError
  94. def get_raw(self, name):
  95. """Obtain the raw text for an object.
  96. Args:
  97. name: sha for the object.
  98. Returns: tuple with numeric type and object contents.
  99. """
  100. raise NotImplementedError(self.get_raw)
  101. def __getitem__(self, sha):
  102. """Obtain an object by SHA1."""
  103. type_num, uncomp = self.get_raw(sha)
  104. return ShaFile.from_raw_string(type_num, uncomp, sha=sha)
  105. def __iter__(self):
  106. """Iterate over the SHAs that are present in this store."""
  107. raise NotImplementedError(self.__iter__)
  108. def add_object(self, obj):
  109. """Add a single object to this object store.
  110. """
  111. raise NotImplementedError(self.add_object)
  112. def add_objects(self, objects, progress=None):
  113. """Add a set of objects to this object store.
  114. Args:
  115. objects: Iterable over a list of (object, path) tuples
  116. """
  117. raise NotImplementedError(self.add_objects)
  118. def add_pack_data(self, count, pack_data, progress=None):
  119. """Add pack data to this object store.
  120. Args:
  121. num_items: Number of items to add
  122. pack_data: Iterator over pack data tuples
  123. """
  124. if count == 0:
  125. # Don't bother writing an empty pack file
  126. return
  127. f, commit, abort = self.add_pack()
  128. try:
  129. write_pack_data(
  130. f, count, pack_data, progress,
  131. compression_level=self.pack_compression_level)
  132. except BaseException:
  133. abort()
  134. raise
  135. else:
  136. return commit()
  137. def tree_changes(self, source, target, want_unchanged=False,
  138. include_trees=False, change_type_same=False,
  139. rename_detector=None):
  140. """Find the differences between the contents of two trees
  141. Args:
  142. source: SHA1 of the source tree
  143. target: SHA1 of the target tree
  144. want_unchanged: Whether unchanged files should be reported
  145. include_trees: Whether to include trees
  146. change_type_same: Whether to report files changing
  147. type in the same entry.
  148. Returns: Iterator over tuples with
  149. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  150. """
  151. for change in tree_changes(self, source, target,
  152. want_unchanged=want_unchanged,
  153. include_trees=include_trees,
  154. change_type_same=change_type_same,
  155. rename_detector=rename_detector):
  156. yield ((change.old.path, change.new.path),
  157. (change.old.mode, change.new.mode),
  158. (change.old.sha, change.new.sha))
  159. def iter_tree_contents(self, tree_id, include_trees=False):
  160. """Iterate the contents of a tree and all subtrees.
  161. Iteration is depth-first pre-order, as in e.g. os.walk.
  162. Args:
  163. tree_id: SHA1 of the tree.
  164. include_trees: If True, include tree objects in the iteration.
  165. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  166. tree.
  167. """
  168. for entry, _ in walk_trees(self, tree_id, None):
  169. if ((entry.mode is not None and
  170. not stat.S_ISDIR(entry.mode)) or include_trees):
  171. yield entry
  172. def find_missing_objects(self, haves, wants, shallow=None, progress=None,
  173. get_tagged=None,
  174. get_parents=lambda commit: commit.parents,
  175. depth=None):
  176. """Find the missing objects required for a set of revisions.
  177. Args:
  178. haves: Iterable over SHAs already in common.
  179. wants: Iterable over SHAs of objects to fetch.
  180. shallow: Set of shallow commit SHA1s to skip
  181. progress: Simple progress function that will be called with
  182. updated progress strings.
  183. get_tagged: Function that returns a dict of pointed-to sha ->
  184. tag sha for including tags.
  185. get_parents: Optional function for getting the parents of a
  186. commit.
  187. Returns: Iterator over (sha, path) pairs.
  188. """
  189. finder = MissingObjectFinder(self, haves, wants, shallow, progress,
  190. get_tagged, get_parents=get_parents)
  191. return iter(finder.next, None)
  192. def find_common_revisions(self, graphwalker):
  193. """Find which revisions this store has in common using graphwalker.
  194. Args:
  195. graphwalker: A graphwalker object.
  196. Returns: List of SHAs that are in common
  197. """
  198. haves = []
  199. sha = next(graphwalker)
  200. while sha:
  201. if sha in self:
  202. haves.append(sha)
  203. graphwalker.ack(sha)
  204. sha = next(graphwalker)
  205. return haves
  206. def generate_pack_contents(self, have, want, shallow=None, progress=None):
  207. """Iterate over the contents of a pack file.
  208. Args:
  209. have: List of SHA1s of objects that should not be sent
  210. want: List of SHA1s of objects that should be sent
  211. shallow: Set of shallow commit SHA1s to skip
  212. progress: Optional progress reporting method
  213. """
  214. missing = self.find_missing_objects(have, want, shallow, progress)
  215. return self.iter_shas(missing)
  216. def generate_pack_data(self, have, want, shallow=None, progress=None,
  217. ofs_delta=True):
  218. """Generate pack data objects for a set of wants/haves.
  219. Args:
  220. have: List of SHA1s of objects that should not be sent
  221. want: List of SHA1s of objects that should be sent
  222. shallow: Set of shallow commit SHA1s to skip
  223. ofs_delta: Whether OFS deltas can be included
  224. progress: Optional progress reporting method
  225. """
  226. # TODO(jelmer): More efficient implementation
  227. return pack_objects_to_data(
  228. self.generate_pack_contents(have, want, shallow, progress))
  229. def peel_sha(self, sha):
  230. """Peel all tags from a SHA.
  231. Args:
  232. sha: The object SHA to peel.
  233. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  234. intermediate tags; if the original ref does not point to a tag,
  235. this will equal the original SHA1.
  236. """
  237. obj = self[sha]
  238. obj_class = object_class(obj.type_name)
  239. while obj_class is Tag:
  240. obj_class, sha = obj.object
  241. obj = self[sha]
  242. return obj
  243. def _collect_ancestors(self, heads, common=set(), shallow=set(),
  244. get_parents=lambda commit: commit.parents):
  245. """Collect all ancestors of heads up to (excluding) those in common.
  246. Args:
  247. heads: commits to start from
  248. common: commits to end at, or empty set to walk repository
  249. completely
  250. get_parents: Optional function for getting the parents of a
  251. commit.
  252. Returns: a tuple (A, B) where A - all commits reachable
  253. from heads but not present in common, B - common (shared) elements
  254. that are directly reachable from heads
  255. """
  256. bases = set()
  257. commits = set()
  258. queue = []
  259. queue.extend(heads)
  260. while queue:
  261. e = queue.pop(0)
  262. if e in common:
  263. bases.add(e)
  264. elif e not in commits:
  265. commits.add(e)
  266. if e in shallow:
  267. continue
  268. cmt = self[e]
  269. queue.extend(get_parents(cmt))
  270. return (commits, bases)
  271. def close(self):
  272. """Close any files opened by this object store."""
  273. # Default implementation is a NO-OP
  274. class PackBasedObjectStore(BaseObjectStore):
  275. def __init__(self, pack_compression_level=-1):
  276. self._pack_cache = {}
  277. self.pack_compression_level = pack_compression_level
  278. @property
  279. def alternates(self):
  280. return []
  281. def contains_packed(self, sha):
  282. """Check if a particular object is present by SHA1 and is packed.
  283. This does not check alternates.
  284. """
  285. for pack in self.packs:
  286. try:
  287. if sha in pack:
  288. return True
  289. except PackFileDisappeared:
  290. pass
  291. return False
  292. def __contains__(self, sha):
  293. """Check if a particular object is present by SHA1.
  294. This method makes no distinction between loose and packed objects.
  295. """
  296. if self.contains_packed(sha) or self.contains_loose(sha):
  297. return True
  298. for alternate in self.alternates:
  299. if sha in alternate:
  300. return True
  301. return False
  302. def _add_cached_pack(self, base_name, pack):
  303. """Add a newly appeared pack to the cache by path.
  304. """
  305. prev_pack = self._pack_cache.get(base_name)
  306. if prev_pack is not pack:
  307. self._pack_cache[base_name] = pack
  308. if prev_pack:
  309. prev_pack.close()
  310. def _clear_cached_packs(self):
  311. pack_cache = self._pack_cache
  312. self._pack_cache = {}
  313. while pack_cache:
  314. (name, pack) = pack_cache.popitem()
  315. pack.close()
  316. def _iter_cached_packs(self):
  317. return self._pack_cache.values()
  318. def _update_pack_cache(self):
  319. raise NotImplementedError(self._update_pack_cache)
  320. def close(self):
  321. self._clear_cached_packs()
  322. @property
  323. def packs(self):
  324. """List with pack objects."""
  325. return (
  326. list(self._iter_cached_packs()) + list(self._update_pack_cache()))
  327. def _iter_alternate_objects(self):
  328. """Iterate over the SHAs of all the objects in alternate stores."""
  329. for alternate in self.alternates:
  330. for alternate_object in alternate:
  331. yield alternate_object
  332. def _iter_loose_objects(self):
  333. """Iterate over the SHAs of all loose objects."""
  334. raise NotImplementedError(self._iter_loose_objects)
  335. def _get_loose_object(self, sha):
  336. raise NotImplementedError(self._get_loose_object)
  337. def _remove_loose_object(self, sha):
  338. raise NotImplementedError(self._remove_loose_object)
  339. def _remove_pack(self, name):
  340. raise NotImplementedError(self._remove_pack)
  341. def pack_loose_objects(self):
  342. """Pack loose objects.
  343. Returns: Number of objects packed
  344. """
  345. objects = set()
  346. for sha in self._iter_loose_objects():
  347. objects.add((self._get_loose_object(sha), None))
  348. self.add_objects(list(objects))
  349. for obj, path in objects:
  350. self._remove_loose_object(obj.id)
  351. return len(objects)
  352. def repack(self):
  353. """Repack the packs in this repository.
  354. Note that this implementation is fairly naive and currently keeps all
  355. objects in memory while it repacks.
  356. """
  357. loose_objects = set()
  358. for sha in self._iter_loose_objects():
  359. loose_objects.add(self._get_loose_object(sha))
  360. objects = {(obj, None) for obj in loose_objects}
  361. old_packs = {p.name(): p for p in self.packs}
  362. for name, pack in old_packs.items():
  363. objects.update((obj, None) for obj in pack.iterobjects())
  364. # The name of the consolidated pack might match the name of a
  365. # pre-existing pack. Take care not to remove the newly created
  366. # consolidated pack.
  367. consolidated = self.add_objects(objects)
  368. old_packs.pop(consolidated.name(), None)
  369. for obj in loose_objects:
  370. self._remove_loose_object(obj.id)
  371. for name, pack in old_packs.items():
  372. self._remove_pack(pack)
  373. self._update_pack_cache()
  374. return len(objects)
  375. def __iter__(self):
  376. """Iterate over the SHAs that are present in this store."""
  377. self._update_pack_cache()
  378. for pack in self._iter_cached_packs():
  379. try:
  380. for sha in pack:
  381. yield sha
  382. except PackFileDisappeared:
  383. pass
  384. for sha in self._iter_loose_objects():
  385. yield sha
  386. for sha in self._iter_alternate_objects():
  387. yield sha
  388. def contains_loose(self, sha):
  389. """Check if a particular object is present by SHA1 and is loose.
  390. This does not check alternates.
  391. """
  392. return self._get_loose_object(sha) is not None
  393. def get_raw(self, name):
  394. """Obtain the raw fulltext for an object.
  395. Args:
  396. name: sha for the object.
  397. Returns: tuple with numeric type and object contents.
  398. """
  399. if name == ZERO_SHA:
  400. raise KeyError(name)
  401. if len(name) == 40:
  402. sha = hex_to_sha(name)
  403. hexsha = name
  404. elif len(name) == 20:
  405. sha = name
  406. hexsha = None
  407. else:
  408. raise AssertionError("Invalid object name %r" % (name, ))
  409. for pack in self._iter_cached_packs():
  410. try:
  411. return pack.get_raw(sha)
  412. except (KeyError, PackFileDisappeared):
  413. pass
  414. if hexsha is None:
  415. hexsha = sha_to_hex(name)
  416. ret = self._get_loose_object(hexsha)
  417. if ret is not None:
  418. return ret.type_num, ret.as_raw_string()
  419. # Maybe something else has added a pack with the object
  420. # in the mean time?
  421. for pack in self._update_pack_cache():
  422. try:
  423. return pack.get_raw(sha)
  424. except KeyError:
  425. pass
  426. for alternate in self.alternates:
  427. try:
  428. return alternate.get_raw(hexsha)
  429. except KeyError:
  430. pass
  431. raise KeyError(hexsha)
  432. def add_objects(self, objects, progress=None):
  433. """Add a set of objects to this object store.
  434. Args:
  435. objects: Iterable over (object, path) tuples, should support
  436. __len__.
  437. Returns: Pack object of the objects written.
  438. """
  439. return self.add_pack_data(
  440. *pack_objects_to_data(objects),
  441. progress=progress)
  442. class DiskObjectStore(PackBasedObjectStore):
  443. """Git-style object store that exists on disk."""
  444. def __init__(self, path, loose_compression_level=-1,
  445. pack_compression_level=-1):
  446. """Open an object store.
  447. Args:
  448. path: Path of the object store.
  449. loose_compression_level: zlib compression level for loose objects
  450. pack_compression_level: zlib compression level for pack objects
  451. """
  452. super(DiskObjectStore, self).__init__(
  453. pack_compression_level=pack_compression_level)
  454. self.path = path
  455. self.pack_dir = os.path.join(self.path, PACKDIR)
  456. self._alternates = None
  457. self.loose_compression_level = loose_compression_level
  458. self.pack_compression_level = pack_compression_level
  459. def __repr__(self):
  460. return "<%s(%r)>" % (self.__class__.__name__, self.path)
  461. @classmethod
  462. def from_config(cls, path, config):
  463. try:
  464. default_compression_level = int(config.get(
  465. (b'core', ), b'compression').decode())
  466. except KeyError:
  467. default_compression_level = -1
  468. try:
  469. loose_compression_level = int(config.get(
  470. (b'core', ), b'looseCompression').decode())
  471. except KeyError:
  472. loose_compression_level = default_compression_level
  473. try:
  474. pack_compression_level = int(config.get(
  475. (b'core', ), 'packCompression').decode())
  476. except KeyError:
  477. pack_compression_level = default_compression_level
  478. return cls(path, loose_compression_level, pack_compression_level)
  479. @property
  480. def alternates(self):
  481. if self._alternates is not None:
  482. return self._alternates
  483. self._alternates = []
  484. for path in self._read_alternate_paths():
  485. self._alternates.append(DiskObjectStore(path))
  486. return self._alternates
  487. def _read_alternate_paths(self):
  488. try:
  489. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), 'rb')
  490. except FileNotFoundError:
  491. return
  492. with f:
  493. for line in f.readlines():
  494. line = line.rstrip(b"\n")
  495. if line[0] == b"#":
  496. continue
  497. if os.path.isabs(line):
  498. yield os.fsdecode(line)
  499. else:
  500. yield os.fsdecode(os.path.join(self.path, line))
  501. def add_alternate_path(self, path):
  502. """Add an alternate path to this object store.
  503. """
  504. try:
  505. os.mkdir(os.path.join(self.path, INFODIR))
  506. except FileExistsError:
  507. pass
  508. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  509. with GitFile(alternates_path, 'wb') as f:
  510. try:
  511. orig_f = open(alternates_path, 'rb')
  512. except FileNotFoundError:
  513. pass
  514. else:
  515. with orig_f:
  516. f.write(orig_f.read())
  517. f.write(os.fsencode(path) + b"\n")
  518. if not os.path.isabs(path):
  519. path = os.path.join(self.path, path)
  520. self.alternates.append(DiskObjectStore(path))
  521. def _update_pack_cache(self):
  522. """Read and iterate over new pack files and cache them."""
  523. try:
  524. pack_dir_contents = os.listdir(self.pack_dir)
  525. except FileNotFoundError:
  526. self.close()
  527. return []
  528. pack_files = set()
  529. for name in pack_dir_contents:
  530. if name.startswith("pack-") and name.endswith(".pack"):
  531. # verify that idx exists first (otherwise the pack was not yet
  532. # fully written)
  533. idx_name = os.path.splitext(name)[0] + ".idx"
  534. if idx_name in pack_dir_contents:
  535. pack_name = name[:-len(".pack")]
  536. pack_files.add(pack_name)
  537. # Open newly appeared pack files
  538. new_packs = []
  539. for f in pack_files:
  540. if f not in self._pack_cache:
  541. pack = Pack(os.path.join(self.pack_dir, f))
  542. new_packs.append(pack)
  543. self._pack_cache[f] = pack
  544. # Remove disappeared pack files
  545. for f in set(self._pack_cache) - pack_files:
  546. self._pack_cache.pop(f).close()
  547. return new_packs
  548. def _get_shafile_path(self, sha):
  549. # Check from object dir
  550. return hex_to_filename(self.path, sha)
  551. def _iter_loose_objects(self):
  552. for base in os.listdir(self.path):
  553. if len(base) != 2:
  554. continue
  555. for rest in os.listdir(os.path.join(self.path, base)):
  556. sha = os.fsencode(base+rest)
  557. if not valid_hexsha(sha):
  558. continue
  559. yield sha
  560. def _get_loose_object(self, sha):
  561. path = self._get_shafile_path(sha)
  562. try:
  563. return ShaFile.from_path(path)
  564. except FileNotFoundError:
  565. return None
  566. def _remove_loose_object(self, sha):
  567. os.remove(self._get_shafile_path(sha))
  568. def _remove_pack(self, pack):
  569. try:
  570. del self._pack_cache[os.path.basename(pack._basename)]
  571. except KeyError:
  572. pass
  573. pack.close()
  574. os.remove(pack.data.path)
  575. os.remove(pack.index.path)
  576. def _get_pack_basepath(self, entries):
  577. suffix = iter_sha1(entry[0] for entry in entries)
  578. # TODO: Handle self.pack_dir being bytes
  579. suffix = suffix.decode('ascii')
  580. return os.path.join(self.pack_dir, "pack-" + suffix)
  581. def _complete_thin_pack(self, f, path, copier, indexer):
  582. """Move a specific file containing a pack into the pack directory.
  583. Note: The file should be on the same file system as the
  584. packs directory.
  585. Args:
  586. f: Open file object for the pack.
  587. path: Path to the pack file.
  588. copier: A PackStreamCopier to use for writing pack data.
  589. indexer: A PackIndexer for indexing the pack.
  590. """
  591. entries = list(indexer)
  592. # Update the header with the new number of objects.
  593. f.seek(0)
  594. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  595. # Must flush before reading (http://bugs.python.org/issue3207)
  596. f.flush()
  597. # Rescan the rest of the pack, computing the SHA with the new header.
  598. new_sha = compute_file_sha(f, end_ofs=-20)
  599. # Must reposition before writing (http://bugs.python.org/issue3207)
  600. f.seek(0, os.SEEK_CUR)
  601. # Complete the pack.
  602. for ext_sha in indexer.ext_refs():
  603. assert len(ext_sha) == 20
  604. type_num, data = self.get_raw(ext_sha)
  605. offset = f.tell()
  606. crc32 = write_pack_object(
  607. f, type_num, data, sha=new_sha,
  608. compression_level=self.pack_compression_level)
  609. entries.append((ext_sha, offset, crc32))
  610. pack_sha = new_sha.digest()
  611. f.write(pack_sha)
  612. f.close()
  613. # Move the pack in.
  614. entries.sort()
  615. pack_base_name = self._get_pack_basepath(entries)
  616. target_pack = pack_base_name + '.pack'
  617. if sys.platform == 'win32':
  618. # Windows might have the target pack file lingering. Attempt
  619. # removal, silently passing if the target does not exist.
  620. try:
  621. os.remove(target_pack)
  622. except FileNotFoundError:
  623. pass
  624. os.rename(path, target_pack)
  625. # Write the index.
  626. index_file = GitFile(pack_base_name + '.idx', 'wb')
  627. try:
  628. write_pack_index_v2(index_file, entries, pack_sha)
  629. index_file.close()
  630. finally:
  631. index_file.abort()
  632. # Add the pack to the store and return it.
  633. final_pack = Pack(pack_base_name)
  634. final_pack.check_length_and_checksum()
  635. self._add_cached_pack(pack_base_name, final_pack)
  636. return final_pack
  637. def add_thin_pack(self, read_all, read_some):
  638. """Add a new thin pack to this object store.
  639. Thin packs are packs that contain deltas with parents that exist
  640. outside the pack. They should never be placed in the object store
  641. directly, and always indexed and completed as they are copied.
  642. Args:
  643. read_all: Read function that blocks until the number of
  644. requested bytes are read.
  645. read_some: Read function that returns at least one byte, but may
  646. not return the number of bytes requested.
  647. Returns: A Pack object pointing at the now-completed thin pack in the
  648. objects/pack directory.
  649. """
  650. import tempfile
  651. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  652. with os.fdopen(fd, 'w+b') as f:
  653. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  654. copier = PackStreamCopier(read_all, read_some, f,
  655. delta_iter=indexer)
  656. copier.verify()
  657. return self._complete_thin_pack(f, path, copier, indexer)
  658. def move_in_pack(self, path):
  659. """Move a specific file containing a pack into the pack directory.
  660. Note: The file should be on the same file system as the
  661. packs directory.
  662. Args:
  663. path: Path to the pack file.
  664. """
  665. with PackData(path) as p:
  666. entries = p.sorted_entries()
  667. basename = self._get_pack_basepath(entries)
  668. index_name = basename + ".idx"
  669. if not os.path.exists(index_name):
  670. with GitFile(index_name, "wb") as f:
  671. write_pack_index_v2(f, entries, p.get_stored_checksum())
  672. for pack in self.packs:
  673. if pack._basename == basename:
  674. return pack
  675. target_pack = basename + '.pack'
  676. if sys.platform == 'win32':
  677. # Windows might have the target pack file lingering. Attempt
  678. # removal, silently passing if the target does not exist.
  679. try:
  680. os.remove(target_pack)
  681. except FileNotFoundError:
  682. pass
  683. os.rename(path, target_pack)
  684. final_pack = Pack(basename)
  685. self._add_cached_pack(basename, final_pack)
  686. return final_pack
  687. def add_pack(self):
  688. """Add a new pack to this object store.
  689. Returns: Fileobject to write to, a commit function to
  690. call when the pack is finished and an abort
  691. function.
  692. """
  693. import tempfile
  694. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  695. f = os.fdopen(fd, 'wb')
  696. def commit():
  697. f.flush()
  698. os.fsync(fd)
  699. f.close()
  700. if os.path.getsize(path) > 0:
  701. return self.move_in_pack(path)
  702. else:
  703. os.remove(path)
  704. return None
  705. def abort():
  706. f.close()
  707. os.remove(path)
  708. return f, commit, abort
  709. def add_object(self, obj):
  710. """Add a single object to this object store.
  711. Args:
  712. obj: Object to add
  713. """
  714. path = self._get_shafile_path(obj.id)
  715. dir = os.path.dirname(path)
  716. try:
  717. os.mkdir(dir)
  718. except FileExistsError:
  719. pass
  720. if os.path.exists(path):
  721. return # Already there, no need to write again
  722. with GitFile(path, 'wb') as f:
  723. f.write(obj.as_legacy_object(
  724. compression_level=self.loose_compression_level))
  725. @classmethod
  726. def init(cls, path):
  727. try:
  728. os.mkdir(path)
  729. except FileExistsError:
  730. pass
  731. os.mkdir(os.path.join(path, "info"))
  732. os.mkdir(os.path.join(path, PACKDIR))
  733. return cls(path)
  734. class MemoryObjectStore(BaseObjectStore):
  735. """Object store that keeps all objects in memory."""
  736. def __init__(self):
  737. super(MemoryObjectStore, self).__init__()
  738. self._data = {}
  739. self.pack_compression_level = -1
  740. def _to_hexsha(self, sha):
  741. if len(sha) == 40:
  742. return sha
  743. elif len(sha) == 20:
  744. return sha_to_hex(sha)
  745. else:
  746. raise ValueError("Invalid sha %r" % (sha,))
  747. def contains_loose(self, sha):
  748. """Check if a particular object is present by SHA1 and is loose."""
  749. return self._to_hexsha(sha) in self._data
  750. def contains_packed(self, sha):
  751. """Check if a particular object is present by SHA1 and is packed."""
  752. return False
  753. def __iter__(self):
  754. """Iterate over the SHAs that are present in this store."""
  755. return iter(self._data.keys())
  756. @property
  757. def packs(self):
  758. """List with pack objects."""
  759. return []
  760. def get_raw(self, name):
  761. """Obtain the raw text for an object.
  762. Args:
  763. name: sha for the object.
  764. Returns: tuple with numeric type and object contents.
  765. """
  766. obj = self[self._to_hexsha(name)]
  767. return obj.type_num, obj.as_raw_string()
  768. def __getitem__(self, name):
  769. return self._data[self._to_hexsha(name)].copy()
  770. def __delitem__(self, name):
  771. """Delete an object from this store, for testing only."""
  772. del self._data[self._to_hexsha(name)]
  773. def add_object(self, obj):
  774. """Add a single object to this object store.
  775. """
  776. self._data[obj.id] = obj.copy()
  777. def add_objects(self, objects, progress=None):
  778. """Add a set of objects to this object store.
  779. Args:
  780. objects: Iterable over a list of (object, path) tuples
  781. """
  782. for obj, path in objects:
  783. self.add_object(obj)
  784. def add_pack(self):
  785. """Add a new pack to this object store.
  786. Because this object store doesn't support packs, we extract and add the
  787. individual objects.
  788. Returns: Fileobject to write to and a commit function to
  789. call when the pack is finished.
  790. """
  791. f = BytesIO()
  792. def commit():
  793. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  794. f.close()
  795. for obj in PackInflater.for_pack_data(p, self.get_raw):
  796. self.add_object(obj)
  797. def abort():
  798. pass
  799. return f, commit, abort
  800. def _complete_thin_pack(self, f, indexer):
  801. """Complete a thin pack by adding external references.
  802. Args:
  803. f: Open file object for the pack.
  804. indexer: A PackIndexer for indexing the pack.
  805. """
  806. entries = list(indexer)
  807. # Update the header with the new number of objects.
  808. f.seek(0)
  809. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  810. # Rescan the rest of the pack, computing the SHA with the new header.
  811. new_sha = compute_file_sha(f, end_ofs=-20)
  812. # Complete the pack.
  813. for ext_sha in indexer.ext_refs():
  814. assert len(ext_sha) == 20
  815. type_num, data = self.get_raw(ext_sha)
  816. write_pack_object(
  817. f, type_num, data, sha=new_sha)
  818. pack_sha = new_sha.digest()
  819. f.write(pack_sha)
  820. def add_thin_pack(self, read_all, read_some):
  821. """Add a new thin pack to this object store.
  822. Thin packs are packs that contain deltas with parents that exist
  823. outside the pack. Because this object store doesn't support packs, we
  824. extract and add the individual objects.
  825. Args:
  826. read_all: Read function that blocks until the number of
  827. requested bytes are read.
  828. read_some: Read function that returns at least one byte, but may
  829. not return the number of bytes requested.
  830. """
  831. f, commit, abort = self.add_pack()
  832. try:
  833. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  834. copier = PackStreamCopier(read_all, read_some, f,
  835. delta_iter=indexer)
  836. copier.verify()
  837. self._complete_thin_pack(f, indexer)
  838. except BaseException:
  839. abort()
  840. raise
  841. else:
  842. commit()
  843. class ObjectIterator(object):
  844. """Interface for iterating over objects."""
  845. def iterobjects(self):
  846. raise NotImplementedError(self.iterobjects)
  847. class ObjectStoreIterator(ObjectIterator):
  848. """ObjectIterator that works on top of an ObjectStore."""
  849. def __init__(self, store, sha_iter):
  850. """Create a new ObjectIterator.
  851. Args:
  852. store: Object store to retrieve from
  853. sha_iter: Iterator over (sha, path) tuples
  854. """
  855. self.store = store
  856. self.sha_iter = sha_iter
  857. self._shas = []
  858. def __iter__(self):
  859. """Yield tuple with next object and path."""
  860. for sha, path in self.itershas():
  861. yield self.store[sha], path
  862. def iterobjects(self):
  863. """Iterate over just the objects."""
  864. for o, path in self:
  865. yield o
  866. def itershas(self):
  867. """Iterate over the SHAs."""
  868. for sha in self._shas:
  869. yield sha
  870. for sha in self.sha_iter:
  871. self._shas.append(sha)
  872. yield sha
  873. def __contains__(self, needle):
  874. """Check if an object is present.
  875. Note: This checks if the object is present in
  876. the underlying object store, not if it would
  877. be yielded by the iterator.
  878. Args:
  879. needle: SHA1 of the object to check for
  880. """
  881. if needle == ZERO_SHA:
  882. return False
  883. return needle in self.store
  884. def __getitem__(self, key):
  885. """Find an object by SHA1.
  886. Note: This retrieves the object from the underlying
  887. object store. It will also succeed if the object would
  888. not be returned by the iterator.
  889. """
  890. return self.store[key]
  891. def __len__(self):
  892. """Return the number of objects."""
  893. return len(list(self.itershas()))
  894. def empty(self):
  895. import warnings
  896. warnings.warn('Use bool() instead.', DeprecationWarning)
  897. return self._empty()
  898. def _empty(self):
  899. it = self.itershas()
  900. try:
  901. next(it)
  902. except StopIteration:
  903. return True
  904. else:
  905. return False
  906. def __bool__(self):
  907. """Indicate whether this object has contents."""
  908. return not self._empty()
  909. def tree_lookup_path(lookup_obj, root_sha, path):
  910. """Look up an object in a Git tree.
  911. Args:
  912. lookup_obj: Callback for retrieving object by SHA1
  913. root_sha: SHA1 of the root tree
  914. path: Path to lookup
  915. Returns: A tuple of (mode, SHA) of the resulting path.
  916. """
  917. tree = lookup_obj(root_sha)
  918. if not isinstance(tree, Tree):
  919. raise NotTreeError(root_sha)
  920. return tree.lookup_path(lookup_obj, path)
  921. def _collect_filetree_revs(obj_store, tree_sha, kset):
  922. """Collect SHA1s of files and directories for specified tree.
  923. Args:
  924. obj_store: Object store to get objects by SHA from
  925. tree_sha: tree reference to walk
  926. kset: set to fill with references to files and directories
  927. """
  928. filetree = obj_store[tree_sha]
  929. for name, mode, sha in filetree.iteritems():
  930. if not S_ISGITLINK(mode) and sha not in kset:
  931. kset.add(sha)
  932. if stat.S_ISDIR(mode):
  933. _collect_filetree_revs(obj_store, sha, kset)
  934. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  935. """Split object id list into three lists with commit, tag, and other SHAs.
  936. Commits referenced by tags are included into commits
  937. list as well. Only SHA1s known in this repository will get
  938. through, and unless ignore_unknown argument is True, KeyError
  939. is thrown for SHA1 missing in the repository
  940. Args:
  941. obj_store: Object store to get objects by SHA1 from
  942. lst: Collection of commit and tag SHAs
  943. ignore_unknown: True to skip SHA1 missing in the repository
  944. silently.
  945. Returns: A tuple of (commits, tags, others) SHA1s
  946. """
  947. commits = set()
  948. tags = set()
  949. others = set()
  950. for e in lst:
  951. try:
  952. o = obj_store[e]
  953. except KeyError:
  954. if not ignore_unknown:
  955. raise
  956. else:
  957. if isinstance(o, Commit):
  958. commits.add(e)
  959. elif isinstance(o, Tag):
  960. tags.add(e)
  961. tagged = o.object[1]
  962. c, t, o = _split_commits_and_tags(
  963. obj_store, [tagged], ignore_unknown=ignore_unknown)
  964. commits |= c
  965. tags |= t
  966. others |= o
  967. else:
  968. others.add(e)
  969. return (commits, tags, others)
  970. class MissingObjectFinder(object):
  971. """Find the objects missing from another object store.
  972. Args:
  973. object_store: Object store containing at least all objects to be
  974. sent
  975. haves: SHA1s of commits not to send (already present in target)
  976. wants: SHA1s of commits to send
  977. progress: Optional function to report progress to.
  978. get_tagged: Function that returns a dict of pointed-to sha -> tag
  979. sha for including tags.
  980. get_parents: Optional function for getting the parents of a commit.
  981. tagged: dict of pointed-to sha -> tag sha for including tags
  982. """
  983. def __init__(self, object_store, haves, wants, shallow=None, progress=None,
  984. get_tagged=None, get_parents=lambda commit: commit.parents):
  985. self.object_store = object_store
  986. if shallow is None:
  987. shallow = set()
  988. self._get_parents = get_parents
  989. # process Commits and Tags differently
  990. # Note, while haves may list commits/tags not available locally,
  991. # and such SHAs would get filtered out by _split_commits_and_tags,
  992. # wants shall list only known SHAs, and otherwise
  993. # _split_commits_and_tags fails with KeyError
  994. have_commits, have_tags, have_others = (
  995. _split_commits_and_tags(object_store, haves, True))
  996. want_commits, want_tags, want_others = (
  997. _split_commits_and_tags(object_store, wants, False))
  998. # all_ancestors is a set of commits that shall not be sent
  999. # (complete repository up to 'haves')
  1000. all_ancestors = object_store._collect_ancestors(
  1001. have_commits, shallow=shallow, get_parents=self._get_parents)[0]
  1002. # all_missing - complete set of commits between haves and wants
  1003. # common - commits from all_ancestors we hit into while
  1004. # traversing parent hierarchy of wants
  1005. missing_commits, common_commits = object_store._collect_ancestors(
  1006. want_commits, all_ancestors, shallow=shallow,
  1007. get_parents=self._get_parents)
  1008. self.sha_done = set()
  1009. # Now, fill sha_done with commits and revisions of
  1010. # files and directories known to be both locally
  1011. # and on target. Thus these commits and files
  1012. # won't get selected for fetch
  1013. for h in common_commits:
  1014. self.sha_done.add(h)
  1015. cmt = object_store[h]
  1016. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  1017. # record tags we have as visited, too
  1018. for t in have_tags:
  1019. self.sha_done.add(t)
  1020. missing_tags = want_tags.difference(have_tags)
  1021. missing_others = want_others.difference(have_others)
  1022. # in fact, what we 'want' is commits, tags, and others
  1023. # we've found missing
  1024. wants = missing_commits.union(missing_tags)
  1025. wants = wants.union(missing_others)
  1026. self.objects_to_send = set([(w, None, False) for w in wants])
  1027. if progress is None:
  1028. self.progress = lambda x: None
  1029. else:
  1030. self.progress = progress
  1031. self._tagged = get_tagged and get_tagged() or {}
  1032. def add_todo(self, entries):
  1033. self.objects_to_send.update([e for e in entries
  1034. if not e[0] in self.sha_done])
  1035. def next(self):
  1036. while True:
  1037. if not self.objects_to_send:
  1038. return None
  1039. (sha, name, leaf) = self.objects_to_send.pop()
  1040. if sha not in self.sha_done:
  1041. break
  1042. if not leaf:
  1043. o = self.object_store[sha]
  1044. if isinstance(o, Commit):
  1045. self.add_todo([(o.tree, "", False)])
  1046. elif isinstance(o, Tree):
  1047. self.add_todo([(s, n, not stat.S_ISDIR(m))
  1048. for n, m, s in o.iteritems()
  1049. if not S_ISGITLINK(m)])
  1050. elif isinstance(o, Tag):
  1051. self.add_todo([(o.object[1], None, False)])
  1052. if sha in self._tagged:
  1053. self.add_todo([(self._tagged[sha], None, True)])
  1054. self.sha_done.add(sha)
  1055. self.progress(("counting objects: %d\r" %
  1056. len(self.sha_done)).encode('ascii'))
  1057. return (sha, name)
  1058. __next__ = next
  1059. class ObjectStoreGraphWalker(object):
  1060. """Graph walker that finds what commits are missing from an object store.
  1061. :ivar heads: Revisions without descendants in the local repo
  1062. :ivar get_parents: Function to retrieve parents in the local repo
  1063. """
  1064. def __init__(self, local_heads, get_parents, shallow=None):
  1065. """Create a new instance.
  1066. Args:
  1067. local_heads: Heads to start search with
  1068. get_parents: Function for finding the parents of a SHA1.
  1069. """
  1070. self.heads = set(local_heads)
  1071. self.get_parents = get_parents
  1072. self.parents = {}
  1073. if shallow is None:
  1074. shallow = set()
  1075. self.shallow = shallow
  1076. def ack(self, sha):
  1077. """Ack that a revision and its ancestors are present in the source."""
  1078. if len(sha) != 40:
  1079. raise ValueError("unexpected sha %r received" % sha)
  1080. ancestors = set([sha])
  1081. # stop if we run out of heads to remove
  1082. while self.heads:
  1083. for a in ancestors:
  1084. if a in self.heads:
  1085. self.heads.remove(a)
  1086. # collect all ancestors
  1087. new_ancestors = set()
  1088. for a in ancestors:
  1089. ps = self.parents.get(a)
  1090. if ps is not None:
  1091. new_ancestors.update(ps)
  1092. self.parents[a] = None
  1093. # no more ancestors; stop
  1094. if not new_ancestors:
  1095. break
  1096. ancestors = new_ancestors
  1097. def next(self):
  1098. """Iterate over ancestors of heads in the target."""
  1099. if self.heads:
  1100. ret = self.heads.pop()
  1101. ps = self.get_parents(ret)
  1102. self.parents[ret] = ps
  1103. self.heads.update(
  1104. [p for p in ps if p not in self.parents])
  1105. return ret
  1106. return None
  1107. __next__ = next
  1108. def commit_tree_changes(object_store, tree, changes):
  1109. """Commit a specified set of changes to a tree structure.
  1110. This will apply a set of changes on top of an existing tree, storing new
  1111. objects in object_store.
  1112. changes are a list of tuples with (path, mode, object_sha).
  1113. Paths can be both blobs and trees. See the mode and
  1114. object sha to None deletes the path.
  1115. This method works especially well if there are only a small
  1116. number of changes to a big tree. For a large number of changes
  1117. to a large tree, use e.g. commit_tree.
  1118. Args:
  1119. object_store: Object store to store new objects in
  1120. and retrieve old ones from.
  1121. tree: Original tree root
  1122. changes: changes to apply
  1123. Returns: New tree root object
  1124. """
  1125. # TODO(jelmer): Save up the objects and add them using .add_objects
  1126. # rather than with individual calls to .add_object.
  1127. nested_changes = {}
  1128. for (path, new_mode, new_sha) in changes:
  1129. try:
  1130. (dirname, subpath) = path.split(b'/', 1)
  1131. except ValueError:
  1132. if new_sha is None:
  1133. del tree[path]
  1134. else:
  1135. tree[path] = (new_mode, new_sha)
  1136. else:
  1137. nested_changes.setdefault(dirname, []).append(
  1138. (subpath, new_mode, new_sha))
  1139. for name, subchanges in nested_changes.items():
  1140. try:
  1141. orig_subtree = object_store[tree[name][1]]
  1142. except KeyError:
  1143. orig_subtree = Tree()
  1144. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1145. if len(subtree) == 0:
  1146. del tree[name]
  1147. else:
  1148. tree[name] = (stat.S_IFDIR, subtree.id)
  1149. object_store.add_object(tree)
  1150. return tree
  1151. class OverlayObjectStore(BaseObjectStore):
  1152. """Object store that can overlay multiple object stores."""
  1153. def __init__(self, bases, add_store=None):
  1154. self.bases = bases
  1155. self.add_store = add_store
  1156. def add_object(self, object):
  1157. if self.add_store is None:
  1158. raise NotImplementedError(self.add_object)
  1159. return self.add_store.add_object(object)
  1160. def add_objects(self, objects, progress=None):
  1161. if self.add_store is None:
  1162. raise NotImplementedError(self.add_object)
  1163. return self.add_store.add_objects(objects, progress)
  1164. @property
  1165. def packs(self):
  1166. ret = []
  1167. for b in self.bases:
  1168. ret.extend(b.packs)
  1169. return ret
  1170. def __iter__(self):
  1171. done = set()
  1172. for b in self.bases:
  1173. for o_id in b:
  1174. if o_id not in done:
  1175. yield o_id
  1176. done.add(o_id)
  1177. def get_raw(self, sha_id):
  1178. for b in self.bases:
  1179. try:
  1180. return b.get_raw(sha_id)
  1181. except KeyError:
  1182. pass
  1183. raise KeyError(sha_id)
  1184. def contains_packed(self, sha):
  1185. for b in self.bases:
  1186. if b.contains_packed(sha):
  1187. return True
  1188. return False
  1189. def contains_loose(self, sha):
  1190. for b in self.bases:
  1191. if b.contains_loose(sha):
  1192. return True
  1193. return False
  1194. def read_packs_file(f):
  1195. """Yield the packs listed in a packs file."""
  1196. for line in f.read().splitlines():
  1197. if not line:
  1198. continue
  1199. (kind, name) = line.split(b" ", 1)
  1200. if kind != b"P":
  1201. continue
  1202. yield os.fsdecode(name)