1 # object_store.py -- Object store for git objects
2 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # or (at your option) a later version of the License.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 """Git object store interfaces and implementation."""
29 from dulwich.errors import (
32 from dulwich.objects import (
40 from dulwich.pack import (
54 class BaseObjectStore(object):
55 """Object store interface."""
57 def determine_wants_all(self, refs):
58 return [sha for (ref, sha) in refs.iteritems() if not sha in self and not ref.endswith("^{}")]
60 def iter_shas(self, shas):
61 """Iterate over the objects for the specified shas.
63 :param shas: Iterable object with SHAs
64 :return: Object iterator
66 return ObjectStoreIterator(self, shas)
68 def __contains__(self, sha):
69 """Check if a particular object is present by SHA1."""
70 raise NotImplementedError(self.__contains__)
72 def get_raw(self, name):
73 """Obtain the raw text for an object.
75 :param name: sha for the object.
76 :return: tuple with object type and object contents.
78 raise NotImplementedError(self.get_raw)
80 def __getitem__(self, sha):
81 """Obtain an object by SHA1."""
82 type, uncomp = self.get_raw(sha)
83 return ShaFile.from_raw_string(type, uncomp)
86 """Iterate over the SHAs that are present in this store."""
87 raise NotImplementedError(self.__iter__)
89 def add_object(self, obj):
90 """Add a single object to this object store.
93 raise NotImplementedError(self.add_object)
95 def add_objects(self, objects):
96 """Add a set of objects to this object store.
98 :param objects: Iterable over a list of objects.
100 raise NotImplementedError(self.add_objects)
102 def find_missing_objects(self, haves, wants, progress=None):
103 """Find the missing objects required for a set of revisions.
105 :param haves: Iterable over SHAs already in common.
106 :param wants: Iterable over SHAs of objects to fetch.
107 :param progress: Simple progress function that will be called with
108 updated progress strings.
109 :return: Iterator over (sha, path) pairs.
111 return iter(MissingObjectFinder(self, haves, wants, progress).next, None)
113 def find_common_revisions(self, graphwalker):
114 """Find which revisions this store has in common using graphwalker.
116 :param graphwalker: A graphwalker object.
117 :return: List of SHAs that are in common
120 sha = graphwalker.next()
125 sha = graphwalker.next()
128 def get_graph_walker(self, heads):
129 """Obtain a graph walker for this object store.
131 :param heads: Local heads to start search with
132 :return: GraphWalker object
134 return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents)
137 def generate_pack_contents(self, have, want):
138 return self.iter_shas(self.find_missing_objects(have, want))
141 class DiskObjectStore(BaseObjectStore):
142 """Git-style object store that exists on disk."""
144 def __init__(self, path):
145 """Open an object store.
147 :param path: Path of the object store.
150 self._pack_cache = None
151 self.pack_dir = os.path.join(self.path, PACKDIR)
153 def __contains__(self, sha):
154 """Check if a particular object is present by SHA1."""
155 for pack in self.packs:
158 ret = self._get_shafile(sha)
164 """Iterate over the SHAs that are present in this store."""
165 iterables = self.packs + [self._iter_shafile_shas()]
166 return itertools.chain(*iterables)
170 """List with pack objects."""
171 if self._pack_cache is None:
172 self._pack_cache = list(load_packs(self.pack_dir))
173 return self._pack_cache
175 def _add_known_pack(self, path):
176 """Add a newly appeared pack to the cache by path.
179 if self._pack_cache is not None:
180 self._pack_cache.append(Pack(path))
182 def _get_shafile_path(self, sha):
185 # Check from object dir
186 return os.path.join(self.path, dir, file)
188 def _iter_shafile_shas(self):
189 for base in os.listdir(self.path):
192 for rest in os.listdir(os.path.join(self.path, base)):
195 def _get_shafile(self, sha):
196 path = self._get_shafile_path(sha)
197 if os.path.exists(path):
198 return ShaFile.from_file(path)
201 def _add_shafile(self, sha, o):
202 dir = os.path.join(self.path, sha[:2])
203 if not os.path.isdir(dir):
205 path = os.path.join(dir, sha[2:])
206 if os.path.exists(path):
207 return # Already there, no need to write again
210 f.write(o.as_legacy_object())
214 def get_raw(self, name):
215 """Obtain the raw text for an object.
217 :param name: sha for the object.
218 :return: tuple with object type and object contents.
221 sha = hex_to_sha(name)
223 elif len(name) == 20:
228 for pack in self.packs:
230 return pack.get_raw(sha)
234 hexsha = sha_to_hex(name)
235 ret = self._get_shafile(hexsha)
237 return ret.type, ret.as_raw_string()
238 raise KeyError(hexsha)
240 def move_in_thin_pack(self, path):
241 """Move a specific file containing a pack into the pack directory.
243 :note: The file should be on the same file system as the
246 :param path: Path to the pack file.
248 data = PackData(path)
250 # Write index for the thin pack (do we really need this?)
251 temppath = os.path.join(self.pack_dir,
252 sha_to_hex(urllib2.randombytes(20))+".tempidx")
253 data.create_index_v2(temppath, self.get_raw)
254 p = Pack.from_objects(data, load_pack_index(temppath))
256 # Write a full pack version
257 temppath = os.path.join(self.pack_dir,
258 sha_to_hex(urllib2.randombytes(20))+".temppack")
259 write_pack(temppath, ((o, None) for o in p.iterobjects(self.get_raw)),
261 pack_sha = load_pack_index(temppath+".idx").objects_sha1()
262 newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
263 os.rename(temppath+".pack", newbasename+".pack")
264 os.rename(temppath+".idx", newbasename+".idx")
265 self._add_known_pack(newbasename)
267 def move_in_pack(self, path):
268 """Move a specific file containing a pack into the pack directory.
270 :note: The file should be on the same file system as the
273 :param path: Path to the pack file.
276 entries = p.sorted_entries()
277 basename = os.path.join(self.pack_dir,
278 "pack-%s" % iter_sha1(entry[0] for entry in entries))
279 write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
280 os.rename(path, basename + ".pack")
281 self._add_known_pack(basename)
283 def add_thin_pack(self):
284 """Add a new thin pack to this object store.
286 Thin packs are packs that contain deltas with parents that exist
289 fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
290 f = os.fdopen(fd, 'w')
294 if os.path.getsize(path) > 0:
295 self.move_in_thin_pack(path)
299 """Add a new pack to this object store.
301 :return: Fileobject to write to and a commit function to
302 call when the pack is finished.
304 fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
305 f = os.fdopen(fd, 'w')
309 if os.path.getsize(path) > 0:
310 self.move_in_pack(path)
313 def add_object(self, obj):
314 """Add a single object to this object store.
317 self._add_shafile(obj.id, obj)
319 def add_objects(self, objects):
320 """Add a set of objects to this object store.
322 :param objects: Iterable over a list of objects.
324 if len(objects) == 0:
326 f, commit = self.add_pack()
327 write_pack_data(f, objects, len(objects))
331 class MemoryObjectStore(BaseObjectStore):
334 super(MemoryObjectStore, self).__init__()
337 def __contains__(self, sha):
338 return sha in self._data
341 """Iterate over the SHAs that are present in this store."""
342 return self._data.iterkeys()
344 def get_raw(self, name):
345 """Obtain the raw text for an object.
347 :param name: sha for the object.
348 :return: tuple with object type and object contents.
350 return self[name].as_raw_string()
352 def __getitem__(self, name):
353 return self._data[name]
355 def add_object(self, obj):
356 """Add a single object to this object store.
359 self._data[obj.id] = obj
361 def add_objects(self, objects):
362 """Add a set of objects to this object store.
364 :param objects: Iterable over a list of objects.
367 self._data[obj.id] = obj
370 class ObjectImporter(object):
371 """Interface for importing objects."""
373 def __init__(self, count):
374 """Create a new ObjectImporter.
376 :param count: Number of objects that's going to be imported.
380 def add_object(self, object):
382 raise NotImplementedError(self.add_object)
384 def finish(self, object):
385 """Finish the imoprt and write objects to disk."""
386 raise NotImplementedError(self.finish)
389 class ObjectIterator(object):
390 """Interface for iterating over objects."""
392 def iterobjects(self):
393 raise NotImplementedError(self.iterobjects)
396 class ObjectStoreIterator(ObjectIterator):
397 """ObjectIterator that works on top of an ObjectStore."""
399 def __init__(self, store, sha_iter):
401 self.sha_iter = sha_iter
405 for sha, path in self.itershas():
406 yield self.store[sha], path
408 def iterobjects(self):
413 for sha in self._shas:
415 for sha in self.sha_iter:
416 self._shas.append(sha)
419 def __contains__(self, needle):
420 """Check if an object is present.
422 :param needle: SHA1 of the object to check for
424 return needle in self.store
426 def __getitem__(self, key):
427 """Find an object by SHA1."""
428 return self.store[key]
431 """Return the number of objects."""
432 return len(list(self.itershas()))
435 def tree_lookup_path(lookup_obj, root_sha, path):
436 """Lookup an object in a Git tree.
438 :param lookup_obj: Callback for retrieving object by SHA1
439 :param root_sha: SHA1 of the root tree
440 :param path: Path to lookup
442 parts = path.split("/")
445 obj = lookup_obj(sha)
446 if type(obj) is not Tree:
447 raise NotTreeError(sha)
451 return lookup_obj(sha)
454 class MissingObjectFinder(object):
455 """Find the objects missing from another object store.
457 :param object_store: Object store containing at least all objects to be
459 :param haves: SHA1s of commits not to send (already present in target)
460 :param wants: SHA1s of commits to send
461 :param progress: Optional function to report progress to.
464 def __init__(self, object_store, haves, wants, progress=None):
465 self.sha_done = set(haves)
466 self.objects_to_send = set([(w, None, False) for w in wants if w not in haves])
467 self.object_store = object_store
469 self.progress = lambda x: None
471 self.progress = progress
473 def add_todo(self, entries):
474 self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
476 def parse_tree(self, tree):
477 self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries()])
479 def parse_commit(self, commit):
480 self.add_todo([(commit.tree, "", False)])
481 self.add_todo([(p, None, False) for p in commit.parents])
483 def parse_tag(self, tag):
484 self.add_todo([(tag.object[1], None, False)])
487 if not self.objects_to_send:
489 (sha, name, leaf) = self.objects_to_send.pop()
491 o = self.object_store[sha]
492 if isinstance(o, Commit):
494 elif isinstance(o, Tree):
496 elif isinstance(o, Tag):
498 self.sha_done.add(sha)
499 self.progress("counting objects: %d\r" % len(self.sha_done))
503 class ObjectStoreGraphWalker(object):
504 """Graph walker that finds out what commits are missing from an object store."""
506 def __init__(self, local_heads, get_parents):
507 """Create a new instance.
509 :param local_heads: Heads to start search with
510 :param get_parents: Function for finding the parents of a SHA1.
512 self.heads = set(local_heads)
513 self.get_parents = get_parents
517 """Ack that a particular revision and its ancestors are present in the source."""
518 if sha in self.heads:
519 self.heads.remove(sha)
520 if sha in self.parents:
521 for p in self.parents[sha]:
525 """Iterate over ancestors of heads in the target."""
527 ret = self.heads.pop()
528 ps = self.get_parents(ret)
529 self.parents[ret] = ps
530 self.heads.update(ps)