object_store.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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. if name.startswith("pack-") and name.endswith(".pack"):
  408. # verify that idx exists first (otherwise the pack was not yet fully written)
  409. idx_name = os.path.splitext(name)[0] + ".idx"
  410. if idx_name in pack_dir_contents:
  411. pack_name = name[:-len(".pack")]
  412. pack_files.add(pack_name)
  413. # Open newly appeared pack files
  414. for f in pack_files:
  415. if f not in self._pack_cache:
  416. self._pack_cache[f] = Pack(os.path.join(self.pack_dir, f))
  417. # Remove disappeared pack files
  418. for f in set(self._pack_cache) - pack_files:
  419. self._pack_cache.pop(f).close()
  420. def _pack_cache_stale(self):
  421. try:
  422. return os.stat(self.pack_dir).st_mtime > self._pack_cache_time
  423. except OSError as e:
  424. if e.errno == errno.ENOENT:
  425. return True
  426. raise
  427. def _get_shafile_path(self, sha):
  428. # Check from object dir
  429. return hex_to_filename(self.path, sha)
  430. def _iter_loose_objects(self):
  431. for base in os.listdir(self.path):
  432. if len(base) != 2:
  433. continue
  434. for rest in os.listdir(os.path.join(self.path, base)):
  435. yield (base+rest).encode(sys.getfilesystemencoding())
  436. def _get_loose_object(self, sha):
  437. path = self._get_shafile_path(sha)
  438. try:
  439. return ShaFile.from_path(path)
  440. except (OSError, IOError) as e:
  441. if e.errno == errno.ENOENT:
  442. return None
  443. raise
  444. def _remove_loose_object(self, sha):
  445. os.remove(self._get_shafile_path(sha))
  446. def _get_pack_basepath(self, entries):
  447. suffix = iter_sha1(entry[0] for entry in entries)
  448. # TODO: Handle self.pack_dir being bytes
  449. suffix = suffix.decode('ascii')
  450. return os.path.join(self.pack_dir, "pack-" + suffix)
  451. def _complete_thin_pack(self, f, path, copier, indexer):
  452. """Move a specific file containing a pack into the pack directory.
  453. :note: The file should be on the same file system as the
  454. packs directory.
  455. :param f: Open file object for the pack.
  456. :param path: Path to the pack file.
  457. :param copier: A PackStreamCopier to use for writing pack data.
  458. :param indexer: A PackIndexer for indexing the pack.
  459. """
  460. entries = list(indexer)
  461. # Update the header with the new number of objects.
  462. f.seek(0)
  463. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  464. # Must flush before reading (http://bugs.python.org/issue3207)
  465. f.flush()
  466. # Rescan the rest of the pack, computing the SHA with the new header.
  467. new_sha = compute_file_sha(f, end_ofs=-20)
  468. # Must reposition before writing (http://bugs.python.org/issue3207)
  469. f.seek(0, os.SEEK_CUR)
  470. # Complete the pack.
  471. for ext_sha in indexer.ext_refs():
  472. assert len(ext_sha) == 20
  473. type_num, data = self.get_raw(ext_sha)
  474. offset = f.tell()
  475. crc32 = write_pack_object(f, type_num, data, sha=new_sha)
  476. entries.append((ext_sha, offset, crc32))
  477. pack_sha = new_sha.digest()
  478. f.write(pack_sha)
  479. f.close()
  480. # Move the pack in.
  481. entries.sort()
  482. pack_base_name = self._get_pack_basepath(entries)
  483. if sys.platform == 'win32':
  484. try:
  485. os.rename(path, pack_base_name + '.pack')
  486. except WindowsError:
  487. os.remove(pack_base_name + '.pack')
  488. os.rename(path, pack_base_name + '.pack')
  489. else:
  490. os.rename(path, pack_base_name + '.pack')
  491. # Write the index.
  492. index_file = GitFile(pack_base_name + '.idx', 'wb')
  493. try:
  494. write_pack_index_v2(index_file, entries, pack_sha)
  495. index_file.close()
  496. finally:
  497. index_file.abort()
  498. # Add the pack to the store and return it.
  499. final_pack = Pack(pack_base_name)
  500. final_pack.check_length_and_checksum()
  501. self._add_known_pack(pack_base_name, final_pack)
  502. return final_pack
  503. def add_thin_pack(self, read_all, read_some):
  504. """Add a new thin pack to this object store.
  505. Thin packs are packs that contain deltas with parents that exist outside
  506. the pack. They should never be placed in the object store directly, and
  507. always indexed and completed as they are copied.
  508. :param read_all: Read function that blocks until the number of requested
  509. bytes are read.
  510. :param read_some: Read function that returns at least one byte, but may
  511. not return the number of bytes requested.
  512. :return: A Pack object pointing at the now-completed thin pack in the
  513. objects/pack directory.
  514. """
  515. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  516. with os.fdopen(fd, 'w+b') as f:
  517. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  518. copier = PackStreamCopier(read_all, read_some, f,
  519. delta_iter=indexer)
  520. copier.verify()
  521. return self._complete_thin_pack(f, path, copier, indexer)
  522. def move_in_pack(self, path):
  523. """Move a specific file containing a pack into the pack directory.
  524. :note: The file should be on the same file system as the
  525. packs directory.
  526. :param path: Path to the pack file.
  527. """
  528. with PackData(path) as p:
  529. entries = p.sorted_entries()
  530. basename = self._get_pack_basepath(entries)
  531. with GitFile(basename+".idx", "wb") as f:
  532. write_pack_index_v2(f, entries, p.get_stored_checksum())
  533. os.rename(path, basename + ".pack")
  534. final_pack = Pack(basename)
  535. self._add_known_pack(basename, final_pack)
  536. return final_pack
  537. def add_pack(self):
  538. """Add a new pack to this object store.
  539. :return: Fileobject to write to, a commit function to
  540. call when the pack is finished and an abort
  541. function.
  542. """
  543. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  544. f = os.fdopen(fd, 'wb')
  545. def commit():
  546. os.fsync(fd)
  547. f.close()
  548. if os.path.getsize(path) > 0:
  549. return self.move_in_pack(path)
  550. else:
  551. os.remove(path)
  552. return None
  553. def abort():
  554. f.close()
  555. os.remove(path)
  556. return f, commit, abort
  557. def add_object(self, obj):
  558. """Add a single object to this object store.
  559. :param obj: Object to add
  560. """
  561. path = self._get_shafile_path(obj.id)
  562. dir = os.path.dirname(path)
  563. try:
  564. os.mkdir(dir)
  565. except OSError as e:
  566. if e.errno != errno.EEXIST:
  567. raise
  568. if os.path.exists(path):
  569. return # Already there, no need to write again
  570. with GitFile(path, 'wb') as f:
  571. f.write(obj.as_legacy_object())
  572. @classmethod
  573. def init(cls, path):
  574. try:
  575. os.mkdir(path)
  576. except OSError as e:
  577. if e.errno != errno.EEXIST:
  578. raise
  579. os.mkdir(os.path.join(path, "info"))
  580. os.mkdir(os.path.join(path, PACKDIR))
  581. return cls(path)
  582. class MemoryObjectStore(BaseObjectStore):
  583. """Object store that keeps all objects in memory."""
  584. def __init__(self):
  585. super(MemoryObjectStore, self).__init__()
  586. self._data = {}
  587. def _to_hexsha(self, sha):
  588. if len(sha) == 40:
  589. return sha
  590. elif len(sha) == 20:
  591. return sha_to_hex(sha)
  592. else:
  593. raise ValueError("Invalid sha %r" % (sha,))
  594. def contains_loose(self, sha):
  595. """Check if a particular object is present by SHA1 and is loose."""
  596. return self._to_hexsha(sha) in self._data
  597. def contains_packed(self, sha):
  598. """Check if a particular object is present by SHA1 and is packed."""
  599. return False
  600. def __iter__(self):
  601. """Iterate over the SHAs that are present in this store."""
  602. return iter(self._data.keys())
  603. @property
  604. def packs(self):
  605. """List with pack objects."""
  606. return []
  607. def get_raw(self, name):
  608. """Obtain the raw text for an object.
  609. :param name: sha for the object.
  610. :return: tuple with numeric type and object contents.
  611. """
  612. obj = self[self._to_hexsha(name)]
  613. return obj.type_num, obj.as_raw_string()
  614. def __getitem__(self, name):
  615. return self._data[self._to_hexsha(name)].copy()
  616. def __delitem__(self, name):
  617. """Delete an object from this store, for testing only."""
  618. del self._data[self._to_hexsha(name)]
  619. def add_object(self, obj):
  620. """Add a single object to this object store.
  621. """
  622. self._data[obj.id] = obj.copy()
  623. def add_objects(self, objects):
  624. """Add a set of objects to this object store.
  625. :param objects: Iterable over a list of (object, path) tuples
  626. """
  627. for obj, path in objects:
  628. self.add_object(obj)
  629. def add_pack(self):
  630. """Add a new pack to this object store.
  631. Because this object store doesn't support packs, we extract and add the
  632. individual objects.
  633. :return: Fileobject to write to and a commit function to
  634. call when the pack is finished.
  635. """
  636. f = BytesIO()
  637. def commit():
  638. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  639. f.close()
  640. for obj in PackInflater.for_pack_data(p, self.get_raw):
  641. self.add_object(obj)
  642. def abort():
  643. pass
  644. return f, commit, abort
  645. def _complete_thin_pack(self, f, indexer):
  646. """Complete a thin pack by adding external references.
  647. :param f: Open file object for the pack.
  648. :param indexer: A PackIndexer for indexing the pack.
  649. """
  650. entries = list(indexer)
  651. # Update the header with the new number of objects.
  652. f.seek(0)
  653. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  654. # Rescan the rest of the pack, computing the SHA with the new header.
  655. new_sha = compute_file_sha(f, end_ofs=-20)
  656. # Complete the pack.
  657. for ext_sha in indexer.ext_refs():
  658. assert len(ext_sha) == 20
  659. type_num, data = self.get_raw(ext_sha)
  660. write_pack_object(f, type_num, data, sha=new_sha)
  661. pack_sha = new_sha.digest()
  662. f.write(pack_sha)
  663. def add_thin_pack(self, read_all, read_some):
  664. """Add a new thin pack to this object store.
  665. Thin packs are packs that contain deltas with parents that exist outside
  666. the pack. Because this object store doesn't support packs, we extract
  667. and add the individual objects.
  668. :param read_all: Read function that blocks until the number of requested
  669. bytes are read.
  670. :param read_some: Read function that returns at least one byte, but may
  671. not return the number of bytes requested.
  672. """
  673. f, commit, abort = self.add_pack()
  674. try:
  675. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  676. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  677. copier.verify()
  678. self._complete_thin_pack(f, indexer)
  679. except:
  680. abort()
  681. raise
  682. else:
  683. commit()
  684. class ObjectImporter(object):
  685. """Interface for importing objects."""
  686. def __init__(self, count):
  687. """Create a new ObjectImporter.
  688. :param count: Number of objects that's going to be imported.
  689. """
  690. self.count = count
  691. def add_object(self, object):
  692. """Add an object."""
  693. raise NotImplementedError(self.add_object)
  694. def finish(self, object):
  695. """Finish the import and write objects to disk."""
  696. raise NotImplementedError(self.finish)
  697. class ObjectIterator(object):
  698. """Interface for iterating over objects."""
  699. def iterobjects(self):
  700. raise NotImplementedError(self.iterobjects)
  701. class ObjectStoreIterator(ObjectIterator):
  702. """ObjectIterator that works on top of an ObjectStore."""
  703. def __init__(self, store, sha_iter):
  704. """Create a new ObjectIterator.
  705. :param store: Object store to retrieve from
  706. :param sha_iter: Iterator over (sha, path) tuples
  707. """
  708. self.store = store
  709. self.sha_iter = sha_iter
  710. self._shas = []
  711. def __iter__(self):
  712. """Yield tuple with next object and path."""
  713. for sha, path in self.itershas():
  714. yield self.store[sha], path
  715. def iterobjects(self):
  716. """Iterate over just the objects."""
  717. for o, path in self:
  718. yield o
  719. def itershas(self):
  720. """Iterate over the SHAs."""
  721. for sha in self._shas:
  722. yield sha
  723. for sha in self.sha_iter:
  724. self._shas.append(sha)
  725. yield sha
  726. def __contains__(self, needle):
  727. """Check if an object is present.
  728. :note: This checks if the object is present in
  729. the underlying object store, not if it would
  730. be yielded by the iterator.
  731. :param needle: SHA1 of the object to check for
  732. """
  733. return needle in self.store
  734. def __getitem__(self, key):
  735. """Find an object by SHA1.
  736. :note: This retrieves the object from the underlying
  737. object store. It will also succeed if the object would
  738. not be returned by the iterator.
  739. """
  740. return self.store[key]
  741. def __len__(self):
  742. """Return the number of objects."""
  743. return len(list(self.itershas()))
  744. def tree_lookup_path(lookup_obj, root_sha, path):
  745. """Look up an object in a Git tree.
  746. :param lookup_obj: Callback for retrieving object by SHA1
  747. :param root_sha: SHA1 of the root tree
  748. :param path: Path to lookup
  749. :return: A tuple of (mode, SHA) of the resulting path.
  750. """
  751. tree = lookup_obj(root_sha)
  752. if not isinstance(tree, Tree):
  753. raise NotTreeError(root_sha)
  754. return tree.lookup_path(lookup_obj, path)
  755. def _collect_filetree_revs(obj_store, tree_sha, kset):
  756. """Collect SHA1s of files and directories for specified tree.
  757. :param obj_store: Object store to get objects by SHA from
  758. :param tree_sha: tree reference to walk
  759. :param kset: set to fill with references to files and directories
  760. """
  761. filetree = obj_store[tree_sha]
  762. for name, mode, sha in filetree.iteritems():
  763. if not S_ISGITLINK(mode) and sha not in kset:
  764. kset.add(sha)
  765. if stat.S_ISDIR(mode):
  766. _collect_filetree_revs(obj_store, sha, kset)
  767. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  768. """Split object id list into three lists with commit, tag, and other SHAs.
  769. Commits referenced by tags are included into commits
  770. list as well. Only SHA1s known in this repository will get
  771. through, and unless ignore_unknown argument is True, KeyError
  772. is thrown for SHA1 missing in the repository
  773. :param obj_store: Object store to get objects by SHA1 from
  774. :param lst: Collection of commit and tag SHAs
  775. :param ignore_unknown: True to skip SHA1 missing in the repository
  776. silently.
  777. :return: A tuple of (commits, tags, others) SHA1s
  778. """
  779. commits = set()
  780. tags = set()
  781. others = set()
  782. for e in lst:
  783. try:
  784. o = obj_store[e]
  785. except KeyError:
  786. if not ignore_unknown:
  787. raise
  788. else:
  789. if isinstance(o, Commit):
  790. commits.add(e)
  791. elif isinstance(o, Tag):
  792. tags.add(e)
  793. tagged = o.object[1]
  794. c, t, o = _split_commits_and_tags(
  795. obj_store, [tagged], ignore_unknown=ignore_unknown)
  796. commits |= c
  797. tags |= t
  798. others |= o
  799. else:
  800. others.add(e)
  801. return (commits, tags, others)
  802. class MissingObjectFinder(object):
  803. """Find the objects missing from another object store.
  804. :param object_store: Object store containing at least all objects to be
  805. sent
  806. :param haves: SHA1s of commits not to send (already present in target)
  807. :param wants: SHA1s of commits to send
  808. :param progress: Optional function to report progress to.
  809. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  810. sha for including tags.
  811. :param get_parents: Optional function for getting the parents of a commit.
  812. :param tagged: dict of pointed-to sha -> tag sha for including tags
  813. """
  814. def __init__(self, object_store, haves, wants, progress=None,
  815. get_tagged=None, get_parents=lambda commit: commit.parents):
  816. self.object_store = object_store
  817. self._get_parents = get_parents
  818. # process Commits and Tags differently
  819. # Note, while haves may list commits/tags not available locally,
  820. # and such SHAs would get filtered out by _split_commits_and_tags,
  821. # wants shall list only known SHAs, and otherwise
  822. # _split_commits_and_tags fails with KeyError
  823. have_commits, have_tags, have_others = (
  824. _split_commits_and_tags(object_store, haves, True))
  825. want_commits, want_tags, want_others = (
  826. _split_commits_and_tags(object_store, wants, False))
  827. # all_ancestors is a set of commits that shall not be sent
  828. # (complete repository up to 'haves')
  829. all_ancestors = object_store._collect_ancestors(
  830. have_commits, get_parents=self._get_parents)[0]
  831. # all_missing - complete set of commits between haves and wants
  832. # common - commits from all_ancestors we hit into while
  833. # traversing parent hierarchy of wants
  834. missing_commits, common_commits = object_store._collect_ancestors(
  835. want_commits, all_ancestors, get_parents=self._get_parents)
  836. self.sha_done = set()
  837. # Now, fill sha_done with commits and revisions of
  838. # files and directories known to be both locally
  839. # and on target. Thus these commits and files
  840. # won't get selected for fetch
  841. for h in common_commits:
  842. self.sha_done.add(h)
  843. cmt = object_store[h]
  844. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  845. # record tags we have as visited, too
  846. for t in have_tags:
  847. self.sha_done.add(t)
  848. missing_tags = want_tags.difference(have_tags)
  849. missing_others = want_others.difference(have_others)
  850. # in fact, what we 'want' is commits, tags, and others
  851. # we've found missing
  852. wants = missing_commits.union(missing_tags)
  853. wants = wants.union(missing_others)
  854. self.objects_to_send = set([(w, None, False) for w in wants])
  855. if progress is None:
  856. self.progress = lambda x: None
  857. else:
  858. self.progress = progress
  859. self._tagged = get_tagged and get_tagged() or {}
  860. def add_todo(self, entries):
  861. self.objects_to_send.update([e for e in entries
  862. if not e[0] in self.sha_done])
  863. def next(self):
  864. while True:
  865. if not self.objects_to_send:
  866. return None
  867. (sha, name, leaf) = self.objects_to_send.pop()
  868. if sha not in self.sha_done:
  869. break
  870. if not leaf:
  871. o = self.object_store[sha]
  872. if isinstance(o, Commit):
  873. self.add_todo([(o.tree, "", False)])
  874. elif isinstance(o, Tree):
  875. self.add_todo([(s, n, not stat.S_ISDIR(m))
  876. for n, m, s in o.iteritems()
  877. if not S_ISGITLINK(m)])
  878. elif isinstance(o, Tag):
  879. self.add_todo([(o.object[1], None, False)])
  880. if sha in self._tagged:
  881. self.add_todo([(self._tagged[sha], None, True)])
  882. self.sha_done.add(sha)
  883. self.progress(("counting objects: %d\r" % len(self.sha_done)).encode('ascii'))
  884. return (sha, name)
  885. __next__ = next
  886. class ObjectStoreGraphWalker(object):
  887. """Graph walker that finds what commits are missing from an object store.
  888. :ivar heads: Revisions without descendants in the local repo
  889. :ivar get_parents: Function to retrieve parents in the local repo
  890. """
  891. def __init__(self, local_heads, get_parents):
  892. """Create a new instance.
  893. :param local_heads: Heads to start search with
  894. :param get_parents: Function for finding the parents of a SHA1.
  895. """
  896. self.heads = set(local_heads)
  897. self.get_parents = get_parents
  898. self.parents = {}
  899. def ack(self, sha):
  900. """Ack that a revision and its ancestors are present in the source."""
  901. if len(sha) != 40:
  902. raise ValueError("unexpected sha %r received" % sha)
  903. ancestors = set([sha])
  904. # stop if we run out of heads to remove
  905. while self.heads:
  906. for a in ancestors:
  907. if a in self.heads:
  908. self.heads.remove(a)
  909. # collect all ancestors
  910. new_ancestors = set()
  911. for a in ancestors:
  912. ps = self.parents.get(a)
  913. if ps is not None:
  914. new_ancestors.update(ps)
  915. self.parents[a] = None
  916. # no more ancestors; stop
  917. if not new_ancestors:
  918. break
  919. ancestors = new_ancestors
  920. def next(self):
  921. """Iterate over ancestors of heads in the target."""
  922. if self.heads:
  923. ret = self.heads.pop()
  924. ps = self.get_parents(ret)
  925. self.parents[ret] = ps
  926. self.heads.update([p for p in ps if not p in self.parents])
  927. return ret
  928. return None
  929. __next__ = next