object_store.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. if sys.platform == 'win32':
  551. try:
  552. os.rename(path, pack_base_name + '.pack')
  553. except WindowsError:
  554. os.remove(pack_base_name + '.pack')
  555. os.rename(path, pack_base_name + '.pack')
  556. else:
  557. os.rename(path, pack_base_name + '.pack')
  558. # Write the index.
  559. index_file = GitFile(pack_base_name + '.idx', 'wb')
  560. try:
  561. write_pack_index_v2(index_file, entries, pack_sha)
  562. index_file.close()
  563. finally:
  564. index_file.abort()
  565. # Add the pack to the store and return it.
  566. final_pack = Pack(pack_base_name)
  567. final_pack.check_length_and_checksum()
  568. self._add_known_pack(pack_base_name, final_pack)
  569. return final_pack
  570. def add_thin_pack(self, read_all, read_some):
  571. """Add a new thin pack to this object store.
  572. Thin packs are packs that contain deltas with parents that exist
  573. outside the pack. They should never be placed in the object store
  574. directly, and always indexed and completed as they are copied.
  575. :param read_all: Read function that blocks until the number of
  576. requested bytes are read.
  577. :param read_some: Read function that returns at least one byte, but may
  578. not return the number of bytes requested.
  579. :return: A Pack object pointing at the now-completed thin pack in the
  580. objects/pack directory.
  581. """
  582. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  583. with os.fdopen(fd, 'w+b') as f:
  584. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  585. copier = PackStreamCopier(read_all, read_some, f,
  586. delta_iter=indexer)
  587. copier.verify()
  588. return self._complete_thin_pack(f, path, copier, indexer)
  589. def move_in_pack(self, path):
  590. """Move a specific file containing a pack into the pack directory.
  591. :note: The file should be on the same file system as the
  592. packs directory.
  593. :param path: Path to the pack file.
  594. """
  595. with PackData(path) as p:
  596. entries = p.sorted_entries()
  597. basename = self._get_pack_basepath(entries)
  598. with GitFile(basename+".idx", "wb") as f:
  599. write_pack_index_v2(f, entries, p.get_stored_checksum())
  600. if self._pack_cache is None or self._pack_cache_stale():
  601. self._update_pack_cache()
  602. try:
  603. return self._pack_cache[basename]
  604. except KeyError:
  605. pass
  606. else:
  607. os.unlink(path)
  608. try:
  609. os.rename(path, basename + ".pack")
  610. except OSError as e:
  611. if e.errno == errno.EEXIST:
  612. # This can happen on Windows..
  613. # It's safe to ignore this, since if the file already exists,
  614. # it should have the same contents as the one we just
  615. # generated.
  616. os.unlink(path)
  617. else:
  618. raise
  619. final_pack = Pack(basename)
  620. self._add_known_pack(basename, final_pack)
  621. return final_pack
  622. def add_pack(self):
  623. """Add a new pack to this object store.
  624. :return: Fileobject to write to, a commit function to
  625. call when the pack is finished and an abort
  626. function.
  627. """
  628. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  629. f = os.fdopen(fd, 'wb')
  630. def commit():
  631. f.flush()
  632. os.fsync(fd)
  633. f.close()
  634. if os.path.getsize(path) > 0:
  635. return self.move_in_pack(path)
  636. else:
  637. os.remove(path)
  638. return None
  639. def abort():
  640. f.close()
  641. os.remove(path)
  642. return f, commit, abort
  643. def add_object(self, obj):
  644. """Add a single object to this object store.
  645. :param obj: Object to add
  646. """
  647. path = self._get_shafile_path(obj.id)
  648. dir = os.path.dirname(path)
  649. try:
  650. os.mkdir(dir)
  651. except OSError as e:
  652. if e.errno != errno.EEXIST:
  653. raise
  654. if os.path.exists(path):
  655. return # Already there, no need to write again
  656. with GitFile(path, 'wb') as f:
  657. f.write(obj.as_legacy_object())
  658. @classmethod
  659. def init(cls, path):
  660. try:
  661. os.mkdir(path)
  662. except OSError as e:
  663. if e.errno != errno.EEXIST:
  664. raise
  665. os.mkdir(os.path.join(path, "info"))
  666. os.mkdir(os.path.join(path, PACKDIR))
  667. return cls(path)
  668. class MemoryObjectStore(BaseObjectStore):
  669. """Object store that keeps all objects in memory."""
  670. def __init__(self):
  671. super(MemoryObjectStore, self).__init__()
  672. self._data = {}
  673. def _to_hexsha(self, sha):
  674. if len(sha) == 40:
  675. return sha
  676. elif len(sha) == 20:
  677. return sha_to_hex(sha)
  678. else:
  679. raise ValueError("Invalid sha %r" % (sha,))
  680. def contains_loose(self, sha):
  681. """Check if a particular object is present by SHA1 and is loose."""
  682. return self._to_hexsha(sha) in self._data
  683. def contains_packed(self, sha):
  684. """Check if a particular object is present by SHA1 and is packed."""
  685. return False
  686. def __iter__(self):
  687. """Iterate over the SHAs that are present in this store."""
  688. return iter(self._data.keys())
  689. @property
  690. def packs(self):
  691. """List with pack objects."""
  692. return []
  693. def get_raw(self, name):
  694. """Obtain the raw text for an object.
  695. :param name: sha for the object.
  696. :return: tuple with numeric type and object contents.
  697. """
  698. obj = self[self._to_hexsha(name)]
  699. return obj.type_num, obj.as_raw_string()
  700. def __getitem__(self, name):
  701. return self._data[self._to_hexsha(name)].copy()
  702. def __delitem__(self, name):
  703. """Delete an object from this store, for testing only."""
  704. del self._data[self._to_hexsha(name)]
  705. def add_object(self, obj):
  706. """Add a single object to this object store.
  707. """
  708. self._data[obj.id] = obj.copy()
  709. def add_objects(self, objects, progress=None):
  710. """Add a set of objects to this object store.
  711. :param objects: Iterable over a list of (object, path) tuples
  712. """
  713. for obj, path in objects:
  714. self.add_object(obj)
  715. def add_pack(self):
  716. """Add a new pack to this object store.
  717. Because this object store doesn't support packs, we extract and add the
  718. individual objects.
  719. :return: Fileobject to write to and a commit function to
  720. call when the pack is finished.
  721. """
  722. f = BytesIO()
  723. def commit():
  724. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  725. f.close()
  726. for obj in PackInflater.for_pack_data(p, self.get_raw):
  727. self.add_object(obj)
  728. def abort():
  729. pass
  730. return f, commit, abort
  731. def _complete_thin_pack(self, f, indexer):
  732. """Complete a thin pack by adding external references.
  733. :param f: Open file object for the pack.
  734. :param indexer: A PackIndexer for indexing the pack.
  735. """
  736. entries = list(indexer)
  737. # Update the header with the new number of objects.
  738. f.seek(0)
  739. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  740. # Rescan the rest of the pack, computing the SHA with the new header.
  741. new_sha = compute_file_sha(f, end_ofs=-20)
  742. # Complete the pack.
  743. for ext_sha in indexer.ext_refs():
  744. assert len(ext_sha) == 20
  745. type_num, data = self.get_raw(ext_sha)
  746. write_pack_object(f, type_num, data, sha=new_sha)
  747. pack_sha = new_sha.digest()
  748. f.write(pack_sha)
  749. def add_thin_pack(self, read_all, read_some):
  750. """Add a new thin pack to this object store.
  751. Thin packs are packs that contain deltas with parents that exist
  752. outside the pack. Because this object store doesn't support packs, we
  753. extract and add the individual objects.
  754. :param read_all: Read function that blocks until the number of
  755. requested bytes are read.
  756. :param read_some: Read function that returns at least one byte, but may
  757. not return the number of bytes requested.
  758. """
  759. f, commit, abort = self.add_pack()
  760. try:
  761. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  762. copier = PackStreamCopier(read_all, read_some, f,
  763. delta_iter=indexer)
  764. copier.verify()
  765. self._complete_thin_pack(f, indexer)
  766. except BaseException:
  767. abort()
  768. raise
  769. else:
  770. commit()
  771. class ObjectIterator(object):
  772. """Interface for iterating over objects."""
  773. def iterobjects(self):
  774. raise NotImplementedError(self.iterobjects)
  775. class ObjectStoreIterator(ObjectIterator):
  776. """ObjectIterator that works on top of an ObjectStore."""
  777. def __init__(self, store, sha_iter):
  778. """Create a new ObjectIterator.
  779. :param store: Object store to retrieve from
  780. :param sha_iter: Iterator over (sha, path) tuples
  781. """
  782. self.store = store
  783. self.sha_iter = sha_iter
  784. self._shas = []
  785. def __iter__(self):
  786. """Yield tuple with next object and path."""
  787. for sha, path in self.itershas():
  788. yield self.store[sha], path
  789. def iterobjects(self):
  790. """Iterate over just the objects."""
  791. for o, path in self:
  792. yield o
  793. def itershas(self):
  794. """Iterate over the SHAs."""
  795. for sha in self._shas:
  796. yield sha
  797. for sha in self.sha_iter:
  798. self._shas.append(sha)
  799. yield sha
  800. def __contains__(self, needle):
  801. """Check if an object is present.
  802. :note: This checks if the object is present in
  803. the underlying object store, not if it would
  804. be yielded by the iterator.
  805. :param needle: SHA1 of the object to check for
  806. """
  807. return needle in self.store
  808. def __getitem__(self, key):
  809. """Find an object by SHA1.
  810. :note: This retrieves the object from the underlying
  811. object store. It will also succeed if the object would
  812. not be returned by the iterator.
  813. """
  814. return self.store[key]
  815. def __len__(self):
  816. """Return the number of objects."""
  817. return len(list(self.itershas()))
  818. def empty(self):
  819. iter = self.itershas()
  820. try:
  821. iter()
  822. except StopIteration:
  823. return True
  824. else:
  825. return False
  826. def __bool__(self):
  827. """Indicate whether this object has contents."""
  828. return not self.empty()
  829. def tree_lookup_path(lookup_obj, root_sha, path):
  830. """Look up an object in a Git tree.
  831. :param lookup_obj: Callback for retrieving object by SHA1
  832. :param root_sha: SHA1 of the root tree
  833. :param path: Path to lookup
  834. :return: A tuple of (mode, SHA) of the resulting path.
  835. """
  836. tree = lookup_obj(root_sha)
  837. if not isinstance(tree, Tree):
  838. raise NotTreeError(root_sha)
  839. return tree.lookup_path(lookup_obj, path)
  840. def _collect_filetree_revs(obj_store, tree_sha, kset):
  841. """Collect SHA1s of files and directories for specified tree.
  842. :param obj_store: Object store to get objects by SHA from
  843. :param tree_sha: tree reference to walk
  844. :param kset: set to fill with references to files and directories
  845. """
  846. filetree = obj_store[tree_sha]
  847. for name, mode, sha in filetree.iteritems():
  848. if not S_ISGITLINK(mode) and sha not in kset:
  849. kset.add(sha)
  850. if stat.S_ISDIR(mode):
  851. _collect_filetree_revs(obj_store, sha, kset)
  852. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  853. """Split object id list into three lists with commit, tag, and other SHAs.
  854. Commits referenced by tags are included into commits
  855. list as well. Only SHA1s known in this repository will get
  856. through, and unless ignore_unknown argument is True, KeyError
  857. is thrown for SHA1 missing in the repository
  858. :param obj_store: Object store to get objects by SHA1 from
  859. :param lst: Collection of commit and tag SHAs
  860. :param ignore_unknown: True to skip SHA1 missing in the repository
  861. silently.
  862. :return: A tuple of (commits, tags, others) SHA1s
  863. """
  864. commits = set()
  865. tags = set()
  866. others = set()
  867. for e in lst:
  868. try:
  869. o = obj_store[e]
  870. except KeyError:
  871. if not ignore_unknown:
  872. raise
  873. else:
  874. if isinstance(o, Commit):
  875. commits.add(e)
  876. elif isinstance(o, Tag):
  877. tags.add(e)
  878. tagged = o.object[1]
  879. c, t, o = _split_commits_and_tags(
  880. obj_store, [tagged], ignore_unknown=ignore_unknown)
  881. commits |= c
  882. tags |= t
  883. others |= o
  884. else:
  885. others.add(e)
  886. return (commits, tags, others)
  887. class MissingObjectFinder(object):
  888. """Find the objects missing from another object store.
  889. :param object_store: Object store containing at least all objects to be
  890. sent
  891. :param haves: SHA1s of commits not to send (already present in target)
  892. :param wants: SHA1s of commits to send
  893. :param progress: Optional function to report progress to.
  894. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  895. sha for including tags.
  896. :param get_parents: Optional function for getting the parents of a commit.
  897. :param tagged: dict of pointed-to sha -> tag sha for including tags
  898. """
  899. def __init__(self, object_store, haves, wants, progress=None,
  900. get_tagged=None, get_parents=lambda commit: commit.parents):
  901. self.object_store = object_store
  902. self._get_parents = get_parents
  903. # process Commits and Tags differently
  904. # Note, while haves may list commits/tags not available locally,
  905. # and such SHAs would get filtered out by _split_commits_and_tags,
  906. # wants shall list only known SHAs, and otherwise
  907. # _split_commits_and_tags fails with KeyError
  908. have_commits, have_tags, have_others = (
  909. _split_commits_and_tags(object_store, haves, True))
  910. want_commits, want_tags, want_others = (
  911. _split_commits_and_tags(object_store, wants, False))
  912. # all_ancestors is a set of commits that shall not be sent
  913. # (complete repository up to 'haves')
  914. all_ancestors = object_store._collect_ancestors(
  915. have_commits, get_parents=self._get_parents)[0]
  916. # all_missing - complete set of commits between haves and wants
  917. # common - commits from all_ancestors we hit into while
  918. # traversing parent hierarchy of wants
  919. missing_commits, common_commits = object_store._collect_ancestors(
  920. want_commits, all_ancestors, get_parents=self._get_parents)
  921. self.sha_done = set()
  922. # Now, fill sha_done with commits and revisions of
  923. # files and directories known to be both locally
  924. # and on target. Thus these commits and files
  925. # won't get selected for fetch
  926. for h in common_commits:
  927. self.sha_done.add(h)
  928. cmt = object_store[h]
  929. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  930. # record tags we have as visited, too
  931. for t in have_tags:
  932. self.sha_done.add(t)
  933. missing_tags = want_tags.difference(have_tags)
  934. missing_others = want_others.difference(have_others)
  935. # in fact, what we 'want' is commits, tags, and others
  936. # we've found missing
  937. wants = missing_commits.union(missing_tags)
  938. wants = wants.union(missing_others)
  939. self.objects_to_send = set([(w, None, False) for w in wants])
  940. if progress is None:
  941. self.progress = lambda x: None
  942. else:
  943. self.progress = progress
  944. self._tagged = get_tagged and get_tagged() or {}
  945. def add_todo(self, entries):
  946. self.objects_to_send.update([e for e in entries
  947. if not e[0] in self.sha_done])
  948. def next(self):
  949. while True:
  950. if not self.objects_to_send:
  951. return None
  952. (sha, name, leaf) = self.objects_to_send.pop()
  953. if sha not in self.sha_done:
  954. break
  955. if not leaf:
  956. o = self.object_store[sha]
  957. if isinstance(o, Commit):
  958. self.add_todo([(o.tree, "", False)])
  959. elif isinstance(o, Tree):
  960. self.add_todo([(s, n, not stat.S_ISDIR(m))
  961. for n, m, s in o.iteritems()
  962. if not S_ISGITLINK(m)])
  963. elif isinstance(o, Tag):
  964. self.add_todo([(o.object[1], None, False)])
  965. if sha in self._tagged:
  966. self.add_todo([(self._tagged[sha], None, True)])
  967. self.sha_done.add(sha)
  968. self.progress(("counting objects: %d\r" %
  969. len(self.sha_done)).encode('ascii'))
  970. return (sha, name)
  971. __next__ = next
  972. class ObjectStoreGraphWalker(object):
  973. """Graph walker that finds what commits are missing from an object store.
  974. :ivar heads: Revisions without descendants in the local repo
  975. :ivar get_parents: Function to retrieve parents in the local repo
  976. """
  977. def __init__(self, local_heads, get_parents):
  978. """Create a new instance.
  979. :param local_heads: Heads to start search with
  980. :param get_parents: Function for finding the parents of a SHA1.
  981. """
  982. self.heads = set(local_heads)
  983. self.get_parents = get_parents
  984. self.parents = {}
  985. def ack(self, sha):
  986. """Ack that a revision and its ancestors are present in the source."""
  987. if len(sha) != 40:
  988. raise ValueError("unexpected sha %r received" % sha)
  989. ancestors = set([sha])
  990. # stop if we run out of heads to remove
  991. while self.heads:
  992. for a in ancestors:
  993. if a in self.heads:
  994. self.heads.remove(a)
  995. # collect all ancestors
  996. new_ancestors = set()
  997. for a in ancestors:
  998. ps = self.parents.get(a)
  999. if ps is not None:
  1000. new_ancestors.update(ps)
  1001. self.parents[a] = None
  1002. # no more ancestors; stop
  1003. if not new_ancestors:
  1004. break
  1005. ancestors = new_ancestors
  1006. def next(self):
  1007. """Iterate over ancestors of heads in the target."""
  1008. if self.heads:
  1009. ret = self.heads.pop()
  1010. ps = self.get_parents(ret)
  1011. self.parents[ret] = ps
  1012. self.heads.update(
  1013. [p for p in ps if p not in self.parents])
  1014. return ret
  1015. return None
  1016. __next__ = next
  1017. def commit_tree_changes(object_store, tree, changes):
  1018. """Commit a specified set of changes to a tree structure.
  1019. This will apply a set of changes on top of an existing tree, storing new
  1020. objects in object_store.
  1021. changes are a list of tuples with (path, mode, object_sha).
  1022. Paths can be both blobs and trees. See the mode and
  1023. object sha to None deletes the path.
  1024. This method works especially well if there are only a small
  1025. number of changes to a big tree. For a large number of changes
  1026. to a large tree, use e.g. commit_tree.
  1027. :param object_store: Object store to store new objects in
  1028. and retrieve old ones from.
  1029. :param tree: Original tree root
  1030. :param changes: changes to apply
  1031. :return: New tree root object
  1032. """
  1033. # TODO(jelmer): Save up the objects and add them using .add_objects
  1034. # rather than with individual calls to .add_object.
  1035. nested_changes = {}
  1036. for (path, new_mode, new_sha) in changes:
  1037. try:
  1038. (dirname, subpath) = path.split(b'/', 1)
  1039. except ValueError:
  1040. if new_sha is None:
  1041. del tree[path]
  1042. else:
  1043. tree[path] = (new_mode, new_sha)
  1044. else:
  1045. nested_changes.setdefault(dirname, []).append(
  1046. (subpath, new_mode, new_sha))
  1047. for name, subchanges in nested_changes.items():
  1048. try:
  1049. orig_subtree = object_store[tree[name][1]]
  1050. except KeyError:
  1051. orig_subtree = Tree()
  1052. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1053. if len(subtree) == 0:
  1054. del tree[name]
  1055. else:
  1056. tree[name] = (stat.S_IFDIR, subtree.id)
  1057. object_store.add_object(tree)
  1058. return tree
  1059. class OverlayObjectStore(BaseObjectStore):
  1060. """Object store that can overlay multiple object stores."""
  1061. def __init__(self, bases, add_store=None):
  1062. self.bases = bases
  1063. self.add_store = add_store
  1064. def add_object(self, object):
  1065. if self.add_store is None:
  1066. raise NotImplementedError(self.add_object)
  1067. return self.add_store.add_object(object)
  1068. def add_objects(self, objects, progress=None):
  1069. if self.add_store is None:
  1070. raise NotImplementedError(self.add_object)
  1071. return self.add_store.add_objects(objects, progress)
  1072. @property
  1073. def packs(self):
  1074. ret = []
  1075. for b in self.bases:
  1076. ret.extend(b.packs)
  1077. return ret
  1078. def __iter__(self):
  1079. done = set()
  1080. for b in self.bases:
  1081. for o_id in b:
  1082. if o_id not in done:
  1083. yield o_id
  1084. done.add(o_id)
  1085. def get_raw(self, sha_id):
  1086. for b in self.bases:
  1087. try:
  1088. return b.get_raw(sha_id)
  1089. except KeyError:
  1090. pass
  1091. else:
  1092. raise KeyError(sha_id)
  1093. def contains_packed(self, sha):
  1094. for b in self.bases:
  1095. if b.contains_packed(sha):
  1096. return True
  1097. else:
  1098. return False
  1099. def contains_loose(self, sha):
  1100. for b in self.bases:
  1101. if b.contains_loose(sha):
  1102. return True
  1103. else:
  1104. return False