object_store.py 42 KB

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