object_store.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  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 errno
  24. from itertools import chain
  25. import os
  26. import stat
  27. import sys
  28. import tempfile
  29. from dulwich.diff_tree import (
  30. tree_changes,
  31. walk_trees,
  32. )
  33. from dulwich.errors import (
  34. NotTreeError,
  35. )
  36. from dulwich.file import GitFile
  37. from dulwich.objects import (
  38. Commit,
  39. ShaFile,
  40. Tag,
  41. Tree,
  42. ZERO_SHA,
  43. hex_to_sha,
  44. sha_to_hex,
  45. hex_to_filename,
  46. S_ISGITLINK,
  47. object_class,
  48. )
  49. from dulwich.pack import (
  50. Pack,
  51. PackData,
  52. PackInflater,
  53. iter_sha1,
  54. write_pack_header,
  55. write_pack_index_v2,
  56. write_pack_object,
  57. write_pack_objects,
  58. compute_file_sha,
  59. PackIndexer,
  60. PackStreamCopier,
  61. )
  62. INFODIR = 'info'
  63. PACKDIR = 'pack'
  64. class BaseObjectStore(object):
  65. """Object store interface."""
  66. def determine_wants_all(self, refs):
  67. return [sha for (ref, sha) in refs.items()
  68. if not sha in self and not ref.endswith(b"^{}") and
  69. not sha == ZERO_SHA]
  70. def iter_shas(self, shas):
  71. """Iterate over the objects for the specified shas.
  72. :param shas: Iterable object with SHAs
  73. :return: Object iterator
  74. """
  75. return ObjectStoreIterator(self, shas)
  76. def contains_loose(self, sha):
  77. """Check if a particular object is present by SHA1 and is loose."""
  78. raise NotImplementedError(self.contains_loose)
  79. def contains_packed(self, sha):
  80. """Check if a particular object is present by SHA1 and is packed."""
  81. raise NotImplementedError(self.contains_packed)
  82. def __contains__(self, sha):
  83. """Check if a particular object is present by SHA1.
  84. This method makes no distinction between loose and packed objects.
  85. """
  86. return self.contains_packed(sha) or self.contains_loose(sha)
  87. @property
  88. def packs(self):
  89. """Iterable of pack objects."""
  90. raise NotImplementedError
  91. def get_raw(self, name):
  92. """Obtain the raw text for an object.
  93. :param name: sha for the object.
  94. :return: tuple with numeric type and object contents.
  95. """
  96. raise NotImplementedError(self.get_raw)
  97. def __getitem__(self, sha):
  98. """Obtain an object by SHA1."""
  99. type_num, uncomp = self.get_raw(sha)
  100. return ShaFile.from_raw_string(type_num, uncomp, sha=sha)
  101. def __iter__(self):
  102. """Iterate over the SHAs that are present in this store."""
  103. raise NotImplementedError(self.__iter__)
  104. def add_object(self, obj):
  105. """Add a single object to this object store.
  106. """
  107. raise NotImplementedError(self.add_object)
  108. def add_objects(self, objects):
  109. """Add a set of objects to this object store.
  110. :param objects: Iterable over a list of (object, path) tuples
  111. """
  112. raise NotImplementedError(self.add_objects)
  113. def tree_changes(self, source, target, want_unchanged=False):
  114. """Find the differences between the contents of two trees
  115. :param source: SHA1 of the source tree
  116. :param target: SHA1 of the target tree
  117. :param want_unchanged: Whether unchanged files should be reported
  118. :return: Iterator over tuples with
  119. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  120. """
  121. for change in tree_changes(self, source, target,
  122. want_unchanged=want_unchanged):
  123. yield ((change.old.path, change.new.path),
  124. (change.old.mode, change.new.mode),
  125. (change.old.sha, change.new.sha))
  126. def iter_tree_contents(self, tree_id, include_trees=False):
  127. """Iterate the contents of a tree and all subtrees.
  128. Iteration is depth-first pre-order, as in e.g. os.walk.
  129. :param tree_id: SHA1 of the tree.
  130. :param include_trees: If True, include tree objects in the iteration.
  131. :return: Iterator over TreeEntry namedtuples for all the objects in a
  132. tree.
  133. """
  134. for entry, _ in walk_trees(self, tree_id, None):
  135. if not stat.S_ISDIR(entry.mode) or include_trees:
  136. yield entry
  137. def find_missing_objects(self, haves, wants, progress=None,
  138. get_tagged=None,
  139. get_parents=lambda commit: commit.parents):
  140. """Find the missing objects required for a set of revisions.
  141. :param haves: Iterable over SHAs already in common.
  142. :param wants: Iterable over SHAs of objects to fetch.
  143. :param progress: Simple progress function that will be called with
  144. updated progress strings.
  145. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  146. sha for including tags.
  147. :param get_parents: Optional function for getting the parents of a commit.
  148. :return: Iterator over (sha, path) pairs.
  149. """
  150. finder = MissingObjectFinder(self, haves, wants, progress, get_tagged, get_parents=get_parents)
  151. return iter(finder.next, None)
  152. def find_common_revisions(self, graphwalker):
  153. """Find which revisions this store has in common using graphwalker.
  154. :param graphwalker: A graphwalker object.
  155. :return: List of SHAs that are in common
  156. """
  157. haves = []
  158. sha = next(graphwalker)
  159. while sha:
  160. if sha in self:
  161. haves.append(sha)
  162. graphwalker.ack(sha)
  163. sha = next(graphwalker)
  164. return haves
  165. def generate_pack_contents(self, have, want, progress=None):
  166. """Iterate over the contents of a pack file.
  167. :param have: List of SHA1s of objects that should not be sent
  168. :param want: List of SHA1s of objects that should be sent
  169. :param progress: Optional progress reporting method
  170. """
  171. return self.iter_shas(self.find_missing_objects(have, want, progress))
  172. def peel_sha(self, sha):
  173. """Peel all tags from a SHA.
  174. :param sha: The object SHA to peel.
  175. :return: The fully-peeled SHA1 of a tag object, after peeling all
  176. intermediate tags; if the original ref does not point to a tag, this
  177. will equal the original SHA1.
  178. """
  179. obj = self[sha]
  180. obj_class = object_class(obj.type_name)
  181. while obj_class is Tag:
  182. obj_class, sha = obj.object
  183. obj = self[sha]
  184. return obj
  185. def _collect_ancestors(self, heads, common=set(),
  186. get_parents=lambda commit: commit.parents):
  187. """Collect all ancestors of heads up to (excluding) those in common.
  188. :param heads: commits to start from
  189. :param common: commits to end at, or empty set to walk repository
  190. completely
  191. :param get_parents: Optional function for getting the parents of a commit.
  192. :return: a tuple (A, B) where A - all commits reachable
  193. from heads but not present in common, B - common (shared) elements
  194. that are directly reachable from heads
  195. """
  196. bases = set()
  197. commits = set()
  198. queue = []
  199. queue.extend(heads)
  200. while queue:
  201. e = queue.pop(0)
  202. if e in common:
  203. bases.add(e)
  204. elif e not in commits:
  205. commits.add(e)
  206. cmt = self[e]
  207. queue.extend(get_parents(cmt))
  208. return (commits, bases)
  209. def close(self):
  210. """Close any files opened by this object store."""
  211. # Default implementation is a NO-OP
  212. class PackBasedObjectStore(BaseObjectStore):
  213. def __init__(self):
  214. self._pack_cache = {}
  215. @property
  216. def alternates(self):
  217. return []
  218. def contains_packed(self, sha):
  219. """Check if a particular object is present by SHA1 and is packed.
  220. This does not check alternates.
  221. """
  222. for pack in self.packs:
  223. if sha in pack:
  224. return True
  225. return False
  226. def __contains__(self, sha):
  227. """Check if a particular object is present by SHA1.
  228. This method makes no distinction between loose and packed objects.
  229. """
  230. if self.contains_packed(sha) or self.contains_loose(sha):
  231. return True
  232. for alternate in self.alternates:
  233. if sha in alternate:
  234. return True
  235. return False
  236. def _pack_cache_stale(self):
  237. """Check whether the pack cache is stale."""
  238. raise NotImplementedError(self._pack_cache_stale)
  239. def _add_known_pack(self, base_name, pack):
  240. """Add a newly appeared pack to the cache by path.
  241. """
  242. self._pack_cache[base_name] = pack
  243. def close(self):
  244. pack_cache = self._pack_cache
  245. self._pack_cache = {}
  246. while pack_cache:
  247. (name, pack) = pack_cache.popitem()
  248. pack.close()
  249. @property
  250. def packs(self):
  251. """List with pack objects."""
  252. if self._pack_cache is None or self._pack_cache_stale():
  253. self._update_pack_cache()
  254. return self._pack_cache.values()
  255. def _iter_alternate_objects(self):
  256. """Iterate over the SHAs of all the objects in alternate stores."""
  257. for alternate in self.alternates:
  258. for alternate_object in alternate:
  259. yield alternate_object
  260. def _iter_loose_objects(self):
  261. """Iterate over the SHAs of all loose objects."""
  262. raise NotImplementedError(self._iter_loose_objects)
  263. def _get_loose_object(self, sha):
  264. raise NotImplementedError(self._get_loose_object)
  265. def _remove_loose_object(self, sha):
  266. raise NotImplementedError(self._remove_loose_object)
  267. def pack_loose_objects(self):
  268. """Pack loose objects.
  269. :return: Number of objects packed
  270. """
  271. objects = set()
  272. for sha in self._iter_loose_objects():
  273. objects.add((self._get_loose_object(sha), None))
  274. self.add_objects(list(objects))
  275. for obj, path in objects:
  276. self._remove_loose_object(obj.id)
  277. return len(objects)
  278. def __iter__(self):
  279. """Iterate over the SHAs that are present in this store."""
  280. iterables = list(self.packs) + [self._iter_loose_objects()] + [self._iter_alternate_objects()]
  281. return chain(*iterables)
  282. def contains_loose(self, sha):
  283. """Check if a particular object is present by SHA1 and is loose.
  284. This does not check alternates.
  285. """
  286. return self._get_loose_object(sha) is not None
  287. def get_raw(self, name):
  288. """Obtain the raw text for an object.
  289. :param name: sha for the object.
  290. :return: tuple with numeric type and object contents.
  291. """
  292. if len(name) == 40:
  293. sha = hex_to_sha(name)
  294. hexsha = name
  295. elif len(name) == 20:
  296. sha = name
  297. hexsha = None
  298. else:
  299. raise AssertionError("Invalid object name %r" % name)
  300. for pack in self.packs:
  301. try:
  302. return pack.get_raw(sha)
  303. except KeyError:
  304. pass
  305. if hexsha is None:
  306. hexsha = sha_to_hex(name)
  307. ret = self._get_loose_object(hexsha)
  308. if ret is not None:
  309. return ret.type_num, ret.as_raw_string()
  310. for alternate in self.alternates:
  311. try:
  312. return alternate.get_raw(hexsha)
  313. except KeyError:
  314. pass
  315. raise KeyError(hexsha)
  316. def add_objects(self, objects):
  317. """Add a set of objects to this object store.
  318. :param objects: Iterable over (object, path) tuples, should support
  319. __len__.
  320. :return: Pack object of the objects written.
  321. """
  322. if len(objects) == 0:
  323. # Don't bother writing an empty pack file
  324. return
  325. f, commit, abort = self.add_pack()
  326. try:
  327. write_pack_objects(f, objects)
  328. except:
  329. abort()
  330. raise
  331. else:
  332. return commit()
  333. class DiskObjectStore(PackBasedObjectStore):
  334. """Git-style object store that exists on disk."""
  335. def __init__(self, path):
  336. """Open an object store.
  337. :param path: Path of the object store.
  338. """
  339. super(DiskObjectStore, self).__init__()
  340. self.path = path
  341. self.pack_dir = os.path.join(self.path, PACKDIR)
  342. self._pack_cache_time = 0
  343. self._pack_cache = {}
  344. self._alternates = None
  345. def __repr__(self):
  346. return "<%s(%r)>" % (self.__class__.__name__, self.path)
  347. @property
  348. def alternates(self):
  349. if self._alternates is not None:
  350. return self._alternates
  351. self._alternates = []
  352. for path in self._read_alternate_paths():
  353. self._alternates.append(DiskObjectStore(path))
  354. return self._alternates
  355. def _read_alternate_paths(self):
  356. try:
  357. f = GitFile(os.path.join(self.path, INFODIR, "alternates"),
  358. 'rb')
  359. except (OSError, IOError) as e:
  360. if e.errno == errno.ENOENT:
  361. return
  362. raise
  363. with f:
  364. for l in f.readlines():
  365. l = l.rstrip(b"\n")
  366. if l[0] == b"#":
  367. continue
  368. if os.path.isabs(l):
  369. yield l.decode(sys.getfilesystemencoding())
  370. else:
  371. yield os.path.join(self.path, l).decode(sys.getfilesystemencoding())
  372. def add_alternate_path(self, path):
  373. """Add an alternate path to this object store.
  374. """
  375. try:
  376. os.mkdir(os.path.join(self.path, INFODIR))
  377. except OSError as e:
  378. if e.errno != errno.EEXIST:
  379. raise
  380. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  381. with GitFile(alternates_path, 'wb') as f:
  382. try:
  383. orig_f = open(alternates_path, 'rb')
  384. except (OSError, IOError) as e:
  385. if e.errno != errno.ENOENT:
  386. raise
  387. else:
  388. with orig_f:
  389. f.write(orig_f.read())
  390. f.write(path.encode(sys.getfilesystemencoding()) + b"\n")
  391. if not os.path.isabs(path):
  392. path = os.path.join(self.path, path)
  393. self.alternates.append(DiskObjectStore(path))
  394. def _update_pack_cache(self):
  395. try:
  396. pack_dir_contents = os.listdir(self.pack_dir)
  397. except OSError as e:
  398. if e.errno == errno.ENOENT:
  399. self._pack_cache_time = 0
  400. self.close()
  401. return
  402. raise
  403. self._pack_cache_time = os.stat(self.pack_dir).st_mtime
  404. pack_files = set()
  405. for name in pack_dir_contents:
  406. assert isinstance(name, basestring if sys.version_info[0] == 2 else str)
  407. # TODO: verify that idx exists first
  408. if name.startswith("pack-") and name.endswith(".pack"):
  409. pack_files.add(name[:-len(".pack")])
  410. # Open newly appeared pack files
  411. for f in pack_files:
  412. if f not in self._pack_cache:
  413. self._pack_cache[f] = Pack(os.path.join(self.pack_dir, f))
  414. # Remove disappeared pack files
  415. for f in set(self._pack_cache) - pack_files:
  416. self._pack_cache.pop(f).close()
  417. def _pack_cache_stale(self):
  418. try:
  419. return os.stat(self.pack_dir).st_mtime > self._pack_cache_time
  420. except OSError as e:
  421. if e.errno == errno.ENOENT:
  422. return True
  423. raise
  424. def _get_shafile_path(self, sha):
  425. # Check from object dir
  426. return hex_to_filename(self.path, sha)
  427. def _iter_loose_objects(self):
  428. for base in os.listdir(self.path):
  429. if len(base) != 2:
  430. continue
  431. for rest in os.listdir(os.path.join(self.path, base)):
  432. yield (base+rest).encode(sys.getfilesystemencoding())
  433. def _get_loose_object(self, sha):
  434. path = self._get_shafile_path(sha)
  435. try:
  436. return ShaFile.from_path(path)
  437. except (OSError, IOError) as e:
  438. if e.errno == errno.ENOENT:
  439. return None
  440. raise
  441. def _remove_loose_object(self, sha):
  442. os.remove(self._get_shafile_path(sha))
  443. def _get_pack_basepath(self, entries):
  444. suffix = iter_sha1(entry[0] for entry in entries)
  445. # TODO: Handle self.pack_dir being bytes
  446. suffix = suffix.decode('ascii')
  447. return os.path.join(self.pack_dir, "pack-" + suffix)
  448. def _complete_thin_pack(self, f, path, copier, indexer):
  449. """Move a specific file containing a pack into the pack directory.
  450. :note: The file should be on the same file system as the
  451. packs directory.
  452. :param f: Open file object for the pack.
  453. :param path: Path to the pack file.
  454. :param copier: A PackStreamCopier to use for writing pack data.
  455. :param indexer: A PackIndexer for indexing the pack.
  456. """
  457. entries = list(indexer)
  458. # Update the header with the new number of objects.
  459. f.seek(0)
  460. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  461. # Must flush before reading (http://bugs.python.org/issue3207)
  462. f.flush()
  463. # Rescan the rest of the pack, computing the SHA with the new header.
  464. new_sha = compute_file_sha(f, end_ofs=-20)
  465. # Must reposition before writing (http://bugs.python.org/issue3207)
  466. f.seek(0, os.SEEK_CUR)
  467. # Complete the pack.
  468. for ext_sha in indexer.ext_refs():
  469. assert len(ext_sha) == 20
  470. type_num, data = self.get_raw(ext_sha)
  471. offset = f.tell()
  472. crc32 = write_pack_object(f, type_num, data, sha=new_sha)
  473. entries.append((ext_sha, offset, crc32))
  474. pack_sha = new_sha.digest()
  475. f.write(pack_sha)
  476. f.close()
  477. # Move the pack in.
  478. entries.sort()
  479. pack_base_name = self._get_pack_basepath(entries)
  480. if sys.platform == 'win32':
  481. try:
  482. os.rename(path, pack_base_name + '.pack')
  483. except WindowsError:
  484. os.remove(pack_base_name + '.pack')
  485. os.rename(path, pack_base_name + '.pack')
  486. else:
  487. os.rename(path, pack_base_name + '.pack')
  488. # Write the index.
  489. index_file = GitFile(pack_base_name + '.idx', 'wb')
  490. try:
  491. write_pack_index_v2(index_file, entries, pack_sha)
  492. index_file.close()
  493. finally:
  494. index_file.abort()
  495. # Add the pack to the store and return it.
  496. final_pack = Pack(pack_base_name)
  497. final_pack.check_length_and_checksum()
  498. self._add_known_pack(pack_base_name, final_pack)
  499. return final_pack
  500. def add_thin_pack(self, read_all, read_some):
  501. """Add a new thin pack to this object store.
  502. Thin packs are packs that contain deltas with parents that exist outside
  503. the pack. They should never be placed in the object store directly, and
  504. always indexed and completed as they are copied.
  505. :param read_all: Read function that blocks until the number of requested
  506. bytes are read.
  507. :param read_some: Read function that returns at least one byte, but may
  508. not return the number of bytes requested.
  509. :return: A Pack object pointing at the now-completed thin pack in the
  510. objects/pack directory.
  511. """
  512. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  513. with os.fdopen(fd, 'w+b') as f:
  514. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  515. copier = PackStreamCopier(read_all, read_some, f,
  516. delta_iter=indexer)
  517. copier.verify()
  518. return self._complete_thin_pack(f, path, copier, indexer)
  519. def move_in_pack(self, path):
  520. """Move a specific file containing a pack into the pack directory.
  521. :note: The file should be on the same file system as the
  522. packs directory.
  523. :param path: Path to the pack file.
  524. """
  525. with PackData(path) as p:
  526. entries = p.sorted_entries()
  527. basename = self._get_pack_basepath(entries)
  528. with GitFile(basename+".idx", "wb") as f:
  529. write_pack_index_v2(f, entries, p.get_stored_checksum())
  530. os.rename(path, basename + ".pack")
  531. final_pack = Pack(basename)
  532. self._add_known_pack(basename, final_pack)
  533. return final_pack
  534. def add_pack(self):
  535. """Add a new pack to this object store.
  536. :return: Fileobject to write to, a commit function to
  537. call when the pack is finished and an abort
  538. function.
  539. """
  540. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  541. f = os.fdopen(fd, 'wb')
  542. def commit():
  543. os.fsync(fd)
  544. f.close()
  545. if os.path.getsize(path) > 0:
  546. return self.move_in_pack(path)
  547. else:
  548. os.remove(path)
  549. return None
  550. def abort():
  551. f.close()
  552. os.remove(path)
  553. return f, commit, abort
  554. def add_object(self, obj):
  555. """Add a single object to this object store.
  556. :param obj: Object to add
  557. """
  558. path = self._get_shafile_path(obj.id)
  559. dir = os.path.dirname(path)
  560. try:
  561. os.mkdir(dir)
  562. except OSError as e:
  563. if e.errno != errno.EEXIST:
  564. raise
  565. if os.path.exists(path):
  566. return # Already there, no need to write again
  567. with GitFile(path, 'wb') as f:
  568. f.write(obj.as_legacy_object())
  569. @classmethod
  570. def init(cls, path):
  571. try:
  572. os.mkdir(path)
  573. except OSError as e:
  574. if e.errno != errno.EEXIST:
  575. raise
  576. os.mkdir(os.path.join(path, "info"))
  577. os.mkdir(os.path.join(path, PACKDIR))
  578. return cls(path)
  579. class MemoryObjectStore(BaseObjectStore):
  580. """Object store that keeps all objects in memory."""
  581. def __init__(self):
  582. super(MemoryObjectStore, self).__init__()
  583. self._data = {}
  584. def _to_hexsha(self, sha):
  585. if len(sha) == 40:
  586. return sha
  587. elif len(sha) == 20:
  588. return sha_to_hex(sha)
  589. else:
  590. raise ValueError("Invalid sha %r" % (sha,))
  591. def contains_loose(self, sha):
  592. """Check if a particular object is present by SHA1 and is loose."""
  593. return self._to_hexsha(sha) in self._data
  594. def contains_packed(self, sha):
  595. """Check if a particular object is present by SHA1 and is packed."""
  596. return False
  597. def __iter__(self):
  598. """Iterate over the SHAs that are present in this store."""
  599. return iter(self._data.keys())
  600. @property
  601. def packs(self):
  602. """List with pack objects."""
  603. return []
  604. def get_raw(self, name):
  605. """Obtain the raw text for an object.
  606. :param name: sha for the object.
  607. :return: tuple with numeric type and object contents.
  608. """
  609. obj = self[self._to_hexsha(name)]
  610. return obj.type_num, obj.as_raw_string()
  611. def __getitem__(self, name):
  612. return self._data[self._to_hexsha(name)].copy()
  613. def __delitem__(self, name):
  614. """Delete an object from this store, for testing only."""
  615. del self._data[self._to_hexsha(name)]
  616. def add_object(self, obj):
  617. """Add a single object to this object store.
  618. """
  619. self._data[obj.id] = obj.copy()
  620. def add_objects(self, objects):
  621. """Add a set of objects to this object store.
  622. :param objects: Iterable over a list of (object, path) tuples
  623. """
  624. for obj, path in objects:
  625. self.add_object(obj)
  626. def add_pack(self):
  627. """Add a new pack to this object store.
  628. Because this object store doesn't support packs, we extract and add the
  629. individual objects.
  630. :return: Fileobject to write to and a commit function to
  631. call when the pack is finished.
  632. """
  633. f = BytesIO()
  634. def commit():
  635. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  636. f.close()
  637. for obj in PackInflater.for_pack_data(p, self.get_raw):
  638. self.add_object(obj)
  639. def abort():
  640. pass
  641. return f, commit, abort
  642. def _complete_thin_pack(self, f, indexer):
  643. """Complete a thin pack by adding external references.
  644. :param f: Open file object for the pack.
  645. :param indexer: A PackIndexer for indexing the pack.
  646. """
  647. entries = list(indexer)
  648. # Update the header with the new number of objects.
  649. f.seek(0)
  650. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  651. # Rescan the rest of the pack, computing the SHA with the new header.
  652. new_sha = compute_file_sha(f, end_ofs=-20)
  653. # Complete the pack.
  654. for ext_sha in indexer.ext_refs():
  655. assert len(ext_sha) == 20
  656. type_num, data = self.get_raw(ext_sha)
  657. write_pack_object(f, type_num, data, sha=new_sha)
  658. pack_sha = new_sha.digest()
  659. f.write(pack_sha)
  660. def add_thin_pack(self, read_all, read_some):
  661. """Add a new thin pack to this object store.
  662. Thin packs are packs that contain deltas with parents that exist outside
  663. the pack. Because this object store doesn't support packs, we extract
  664. and add the individual objects.
  665. :param read_all: Read function that blocks until the number of requested
  666. bytes are read.
  667. :param read_some: Read function that returns at least one byte, but may
  668. not return the number of bytes requested.
  669. """
  670. f, commit, abort = self.add_pack()
  671. try:
  672. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  673. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  674. copier.verify()
  675. self._complete_thin_pack(f, indexer)
  676. except:
  677. abort()
  678. raise
  679. else:
  680. commit()
  681. class ObjectImporter(object):
  682. """Interface for importing objects."""
  683. def __init__(self, count):
  684. """Create a new ObjectImporter.
  685. :param count: Number of objects that's going to be imported.
  686. """
  687. self.count = count
  688. def add_object(self, object):
  689. """Add an object."""
  690. raise NotImplementedError(self.add_object)
  691. def finish(self, object):
  692. """Finish the import and write objects to disk."""
  693. raise NotImplementedError(self.finish)
  694. class ObjectIterator(object):
  695. """Interface for iterating over objects."""
  696. def iterobjects(self):
  697. raise NotImplementedError(self.iterobjects)
  698. class ObjectStoreIterator(ObjectIterator):
  699. """ObjectIterator that works on top of an ObjectStore."""
  700. def __init__(self, store, sha_iter):
  701. """Create a new ObjectIterator.
  702. :param store: Object store to retrieve from
  703. :param sha_iter: Iterator over (sha, path) tuples
  704. """
  705. self.store = store
  706. self.sha_iter = sha_iter
  707. self._shas = []
  708. def __iter__(self):
  709. """Yield tuple with next object and path."""
  710. for sha, path in self.itershas():
  711. yield self.store[sha], path
  712. def iterobjects(self):
  713. """Iterate over just the objects."""
  714. for o, path in self:
  715. yield o
  716. def itershas(self):
  717. """Iterate over the SHAs."""
  718. for sha in self._shas:
  719. yield sha
  720. for sha in self.sha_iter:
  721. self._shas.append(sha)
  722. yield sha
  723. def __contains__(self, needle):
  724. """Check if an object is present.
  725. :note: This checks if the object is present in
  726. the underlying object store, not if it would
  727. be yielded by the iterator.
  728. :param needle: SHA1 of the object to check for
  729. """
  730. return needle in self.store
  731. def __getitem__(self, key):
  732. """Find an object by SHA1.
  733. :note: This retrieves the object from the underlying
  734. object store. It will also succeed if the object would
  735. not be returned by the iterator.
  736. """
  737. return self.store[key]
  738. def __len__(self):
  739. """Return the number of objects."""
  740. return len(list(self.itershas()))
  741. def tree_lookup_path(lookup_obj, root_sha, path):
  742. """Look up an object in a Git tree.
  743. :param lookup_obj: Callback for retrieving object by SHA1
  744. :param root_sha: SHA1 of the root tree
  745. :param path: Path to lookup
  746. :return: A tuple of (mode, SHA) of the resulting path.
  747. """
  748. tree = lookup_obj(root_sha)
  749. if not isinstance(tree, Tree):
  750. raise NotTreeError(root_sha)
  751. return tree.lookup_path(lookup_obj, path)
  752. def _collect_filetree_revs(obj_store, tree_sha, kset):
  753. """Collect SHA1s of files and directories for specified tree.
  754. :param obj_store: Object store to get objects by SHA from
  755. :param tree_sha: tree reference to walk
  756. :param kset: set to fill with references to files and directories
  757. """
  758. filetree = obj_store[tree_sha]
  759. for name, mode, sha in filetree.iteritems():
  760. if not S_ISGITLINK(mode) and sha not in kset:
  761. kset.add(sha)
  762. if stat.S_ISDIR(mode):
  763. _collect_filetree_revs(obj_store, sha, kset)
  764. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  765. """Split object id list into three lists with commit, tag, and other SHAs.
  766. Commits referenced by tags are included into commits
  767. list as well. Only SHA1s known in this repository will get
  768. through, and unless ignore_unknown argument is True, KeyError
  769. is thrown for SHA1 missing in the repository
  770. :param obj_store: Object store to get objects by SHA1 from
  771. :param lst: Collection of commit and tag SHAs
  772. :param ignore_unknown: True to skip SHA1 missing in the repository
  773. silently.
  774. :return: A tuple of (commits, tags, others) SHA1s
  775. """
  776. commits = set()
  777. tags = set()
  778. others = set()
  779. for e in lst:
  780. try:
  781. o = obj_store[e]
  782. except KeyError:
  783. if not ignore_unknown:
  784. raise
  785. else:
  786. if isinstance(o, Commit):
  787. commits.add(e)
  788. elif isinstance(o, Tag):
  789. tags.add(e)
  790. tagged = o.object[1]
  791. c, t, o = _split_commits_and_tags(
  792. obj_store, [tagged], ignore_unknown=ignore_unknown)
  793. commits |= c
  794. tags |= t
  795. others |= o
  796. else:
  797. others.add(e)
  798. return (commits, tags, others)
  799. class MissingObjectFinder(object):
  800. """Find the objects missing from another object store.
  801. :param object_store: Object store containing at least all objects to be
  802. sent
  803. :param haves: SHA1s of commits not to send (already present in target)
  804. :param wants: SHA1s of commits to send
  805. :param progress: Optional function to report progress to.
  806. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  807. sha for including tags.
  808. :param get_parents: Optional function for getting the parents of a commit.
  809. :param tagged: dict of pointed-to sha -> tag sha for including tags
  810. """
  811. def __init__(self, object_store, haves, wants, progress=None,
  812. get_tagged=None, get_parents=lambda commit: commit.parents):
  813. self.object_store = object_store
  814. self._get_parents = get_parents
  815. # process Commits and Tags differently
  816. # Note, while haves may list commits/tags not available locally,
  817. # and such SHAs would get filtered out by _split_commits_and_tags,
  818. # wants shall list only known SHAs, and otherwise
  819. # _split_commits_and_tags fails with KeyError
  820. have_commits, have_tags, have_others = (
  821. _split_commits_and_tags(object_store, haves, True))
  822. want_commits, want_tags, want_others = (
  823. _split_commits_and_tags(object_store, wants, False))
  824. # all_ancestors is a set of commits that shall not be sent
  825. # (complete repository up to 'haves')
  826. all_ancestors = object_store._collect_ancestors(
  827. have_commits, get_parents=self._get_parents)[0]
  828. # all_missing - complete set of commits between haves and wants
  829. # common - commits from all_ancestors we hit into while
  830. # traversing parent hierarchy of wants
  831. missing_commits, common_commits = object_store._collect_ancestors(
  832. want_commits, all_ancestors, get_parents=self._get_parents)
  833. self.sha_done = set()
  834. # Now, fill sha_done with commits and revisions of
  835. # files and directories known to be both locally
  836. # and on target. Thus these commits and files
  837. # won't get selected for fetch
  838. for h in common_commits:
  839. self.sha_done.add(h)
  840. cmt = object_store[h]
  841. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  842. # record tags we have as visited, too
  843. for t in have_tags:
  844. self.sha_done.add(t)
  845. missing_tags = want_tags.difference(have_tags)
  846. missing_others = want_others.difference(have_others)
  847. # in fact, what we 'want' is commits, tags, and others
  848. # we've found missing
  849. wants = missing_commits.union(missing_tags)
  850. wants = wants.union(missing_others)
  851. self.objects_to_send = set([(w, None, False) for w in wants])
  852. if progress is None:
  853. self.progress = lambda x: None
  854. else:
  855. self.progress = progress
  856. self._tagged = get_tagged and get_tagged() or {}
  857. def add_todo(self, entries):
  858. self.objects_to_send.update([e for e in entries
  859. if not e[0] in self.sha_done])
  860. def next(self):
  861. while True:
  862. if not self.objects_to_send:
  863. return None
  864. (sha, name, leaf) = self.objects_to_send.pop()
  865. if sha not in self.sha_done:
  866. break
  867. if not leaf:
  868. o = self.object_store[sha]
  869. if isinstance(o, Commit):
  870. self.add_todo([(o.tree, "", False)])
  871. elif isinstance(o, Tree):
  872. self.add_todo([(s, n, not stat.S_ISDIR(m))
  873. for n, m, s in o.iteritems()
  874. if not S_ISGITLINK(m)])
  875. elif isinstance(o, Tag):
  876. self.add_todo([(o.object[1], None, False)])
  877. if sha in self._tagged:
  878. self.add_todo([(self._tagged[sha], None, True)])
  879. self.sha_done.add(sha)
  880. self.progress(("counting objects: %d\r" % len(self.sha_done)).encode('ascii'))
  881. return (sha, name)
  882. __next__ = next
  883. class ObjectStoreGraphWalker(object):
  884. """Graph walker that finds what commits are missing from an object store.
  885. :ivar heads: Revisions without descendants in the local repo
  886. :ivar get_parents: Function to retrieve parents in the local repo
  887. """
  888. def __init__(self, local_heads, get_parents):
  889. """Create a new instance.
  890. :param local_heads: Heads to start search with
  891. :param get_parents: Function for finding the parents of a SHA1.
  892. """
  893. self.heads = set(local_heads)
  894. self.get_parents = get_parents
  895. self.parents = {}
  896. def ack(self, sha):
  897. """Ack that a revision and its ancestors are present in the source."""
  898. if len(sha) != 40:
  899. raise ValueError("unexpected sha %r received" % sha)
  900. ancestors = set([sha])
  901. # stop if we run out of heads to remove
  902. while self.heads:
  903. for a in ancestors:
  904. if a in self.heads:
  905. self.heads.remove(a)
  906. # collect all ancestors
  907. new_ancestors = set()
  908. for a in ancestors:
  909. ps = self.parents.get(a)
  910. if ps is not None:
  911. new_ancestors.update(ps)
  912. self.parents[a] = None
  913. # no more ancestors; stop
  914. if not new_ancestors:
  915. break
  916. ancestors = new_ancestors
  917. def next(self):
  918. """Iterate over ancestors of heads in the target."""
  919. if self.heads:
  920. ret = self.heads.pop()
  921. ps = self.get_parents(ret)
  922. self.parents[ret] = ps
  923. self.heads.update([p for p in ps if not p in self.parents])
  924. return ret
  925. return None
  926. __next__ = next