object_store.py 44 KB

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