Add ObjectStore.generate_pack_contents.
[jelmer/dulwich-libgit2.git] / dulwich / object_store.py
1 # object_store.py -- Object store for git objects 
2 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
3
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.
8
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.
13
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,
17 # MA  02110-1301, USA.
18
19
20 """Git object store interfaces and implementation."""
21
22
23 import itertools
24 import os
25 import stat
26 import tempfile
27 import urllib2
28
29 from dulwich.errors import (
30     NotTreeError,
31     )
32 from dulwich.objects import (
33     Commit,
34     ShaFile,
35     Tag,
36     Tree,
37     hex_to_sha,
38     sha_to_hex,
39     )
40 from dulwich.pack import (
41     Pack,
42     PackData, 
43     iter_sha1, 
44     load_packs, 
45     load_pack_index,
46     write_pack,
47     write_pack_data,
48     write_pack_index_v2,
49     )
50
51 PACKDIR = 'pack'
52
53
54 class BaseObjectStore(object):
55     """Object store interface."""
56
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("^{}")]
59
60     def iter_shas(self, shas):
61         """Iterate over the objects for the specified shas.
62
63         :param shas: Iterable object with SHAs
64         :return: Object iterator
65         """
66         return ObjectStoreIterator(self, shas)
67
68     def __contains__(self, sha):
69         """Check if a particular object is present by SHA1."""
70         raise NotImplementedError(self.__contains__)
71
72     def get_raw(self, name):
73         """Obtain the raw text for an object.
74         
75         :param name: sha for the object.
76         :return: tuple with object type and object contents.
77         """
78         raise NotImplementedError(self.get_raw)
79
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)
84
85     def __iter__(self):
86         """Iterate over the SHAs that are present in this store."""
87         raise NotImplementedError(self.__iter__)
88
89     def add_object(self, obj):
90         """Add a single object to this object store.
91
92         """
93         raise NotImplementedError(self.add_object)
94
95     def add_objects(self, objects):
96         """Add a set of objects to this object store.
97
98         :param objects: Iterable over a list of objects.
99         """
100         raise NotImplementedError(self.add_objects)
101
102     def find_missing_objects(self, haves, wants, progress=None):
103         """Find the missing objects required for a set of revisions.
104
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.
110         """
111         return iter(MissingObjectFinder(self, haves, wants, progress).next, None)
112
113     def find_common_revisions(self, graphwalker):
114         """Find which revisions this store has in common using graphwalker.
115
116         :param graphwalker: A graphwalker object.
117         :return: List of SHAs that are in common
118         """
119         haves = []
120         sha = graphwalker.next()
121         while sha:
122             if sha in self:
123                 haves.append(sha)
124                 graphwalker.ack(sha)
125             sha = graphwalker.next()
126         return haves
127
128     def get_graph_walker(self, heads):
129         """Obtain a graph walker for this object store.
130         
131         :param heads: Local heads to start search with
132         :return: GraphWalker object
133         """
134         return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents)
135
136
137     def generate_pack_contents(self, have, want):
138         return self.iter_shas(self.find_missing_objects(have, want))
139
140
141 class DiskObjectStore(BaseObjectStore):
142     """Git-style object store that exists on disk."""
143
144     def __init__(self, path):
145         """Open an object store.
146
147         :param path: Path of the object store.
148         """
149         self.path = path
150         self._pack_cache = None
151         self.pack_dir = os.path.join(self.path, PACKDIR)
152
153     def __contains__(self, sha):
154         """Check if a particular object is present by SHA1."""
155         for pack in self.packs:
156             if sha in pack:
157                 return True
158         ret = self._get_shafile(sha)
159         if ret is not None:
160             return True
161         return False
162
163     def __iter__(self):
164         """Iterate over the SHAs that are present in this store."""
165         iterables = self.packs + [self._iter_shafile_shas()]
166         return itertools.chain(*iterables)
167
168     @property
169     def packs(self):
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
174
175     def _add_known_pack(self, path):
176         """Add a newly appeared pack to the cache by path.
177
178         """
179         if self._pack_cache is not None:
180             self._pack_cache.append(Pack(path))
181
182     def _get_shafile_path(self, sha):
183         dir = sha[:2]
184         file = sha[2:]
185         # Check from object dir
186         return os.path.join(self.path, dir, file)
187
188     def _iter_shafile_shas(self):
189         for base in os.listdir(self.path):
190             if len(base) != 2:
191                 continue
192             for rest in os.listdir(os.path.join(self.path, base)):
193                 yield base+rest
194
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)
199         return None
200
201     def _add_shafile(self, sha, o):
202         dir = os.path.join(self.path, sha[:2])
203         if not os.path.isdir(dir):
204             os.mkdir(dir)
205         path = os.path.join(dir, sha[2:])
206         if os.path.exists(path):
207             return # Already there, no need to write again
208         f = open(path, 'w+')
209         try:
210             f.write(o.as_legacy_object())
211         finally:
212             f.close()
213
214     def get_raw(self, name):
215         """Obtain the raw text for an object.
216         
217         :param name: sha for the object.
218         :return: tuple with object type and object contents.
219         """
220         if len(name) == 40:
221             sha = hex_to_sha(name)
222             hexsha = name
223         elif len(name) == 20:
224             sha = name
225             hexsha = None
226         else:
227             raise AssertionError
228         for pack in self.packs:
229             try:
230                 return pack.get_raw(sha)
231             except KeyError:
232                 pass
233         if hexsha is None: 
234             hexsha = sha_to_hex(name)
235         ret = self._get_shafile(hexsha)
236         if ret is not None:
237             return ret.type, ret.as_raw_string()
238         raise KeyError(hexsha)
239
240     def move_in_thin_pack(self, path):
241         """Move a specific file containing a pack into the pack directory.
242
243         :note: The file should be on the same file system as the 
244             packs directory.
245
246         :param path: Path to the pack file.
247         """
248         data = PackData(path)
249
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))
255
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)), 
260                 len(p))
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)
266
267     def move_in_pack(self, path):
268         """Move a specific file containing a pack into the pack directory.
269
270         :note: The file should be on the same file system as the 
271             packs directory.
272
273         :param path: Path to the pack file.
274         """
275         p = PackData(path)
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)
282
283     def add_thin_pack(self):
284         """Add a new thin pack to this object store.
285
286         Thin packs are packs that contain deltas with parents that exist 
287         in a different pack.
288         """
289         fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
290         f = os.fdopen(fd, 'w')
291         def commit():
292             os.fsync(fd)
293             f.close()
294             if os.path.getsize(path) > 0:
295                 self.move_in_thin_pack(path)
296         return f, commit
297
298     def add_pack(self):
299         """Add a new pack to this object store. 
300
301         :return: Fileobject to write to and a commit function to 
302             call when the pack is finished.
303         """
304         fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
305         f = os.fdopen(fd, 'w')
306         def commit():
307             os.fsync(fd)
308             f.close()
309             if os.path.getsize(path) > 0:
310                 self.move_in_pack(path)
311         return f, commit
312
313     def add_object(self, obj):
314         """Add a single object to this object store.
315
316         """
317         self._add_shafile(obj.id, obj)
318
319     def add_objects(self, objects):
320         """Add a set of objects to this object store.
321
322         :param objects: Iterable over a list of objects.
323         """
324         if len(objects) == 0:
325             return
326         f, commit = self.add_pack()
327         write_pack_data(f, objects, len(objects))
328         commit()
329
330
331 class MemoryObjectStore(BaseObjectStore):
332
333     def __init__(self):
334         super(MemoryObjectStore, self).__init__()
335         self._data = {}
336
337     def __contains__(self, sha):
338         return sha in self._data
339
340     def __iter__(self):
341         """Iterate over the SHAs that are present in this store."""
342         return self._data.iterkeys()
343
344     def get_raw(self, name):
345         """Obtain the raw text for an object.
346         
347         :param name: sha for the object.
348         :return: tuple with object type and object contents.
349         """
350         return self[name].as_raw_string()
351
352     def __getitem__(self, name):
353         return self._data[name]
354
355     def add_object(self, obj):
356         """Add a single object to this object store.
357
358         """
359         self._data[obj.id] = obj
360
361     def add_objects(self, objects):
362         """Add a set of objects to this object store.
363
364         :param objects: Iterable over a list of objects.
365         """
366         for obj in objects:
367             self._data[obj.id] = obj
368
369
370 class ObjectImporter(object):
371     """Interface for importing objects."""
372
373     def __init__(self, count):
374         """Create a new ObjectImporter.
375
376         :param count: Number of objects that's going to be imported.
377         """
378         self.count = count
379
380     def add_object(self, object):
381         """Add an object."""
382         raise NotImplementedError(self.add_object)
383
384     def finish(self, object):
385         """Finish the imoprt and write objects to disk."""
386         raise NotImplementedError(self.finish)
387
388
389 class ObjectIterator(object):
390     """Interface for iterating over objects."""
391
392     def iterobjects(self):
393         raise NotImplementedError(self.iterobjects)
394
395
396 class ObjectStoreIterator(ObjectIterator):
397     """ObjectIterator that works on top of an ObjectStore."""
398
399     def __init__(self, store, sha_iter):
400         self.store = store
401         self.sha_iter = sha_iter
402         self._shas = []
403
404     def __iter__(self):
405         for sha, path in self.itershas():
406             yield self.store[sha], path
407
408     def iterobjects(self):
409         for o, path in self:
410             yield o
411
412     def itershas(self):
413         for sha in self._shas:
414             yield sha
415         for sha in self.sha_iter:
416             self._shas.append(sha)
417             yield sha
418
419     def __contains__(self, needle):
420         """Check if an object is present.
421
422         :param needle: SHA1 of the object to check for
423         """
424         return needle in self.store
425
426     def __getitem__(self, key):
427         """Find an object by SHA1."""
428         return self.store[key]
429
430     def __len__(self):
431         """Return the number of objects."""
432         return len(list(self.itershas()))
433
434
435 def tree_lookup_path(lookup_obj, root_sha, path):
436     """Lookup an object in a Git tree.
437
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
441     """
442     parts = path.split("/")
443     sha = root_sha
444     for p in parts:
445         obj = lookup_obj(sha)
446         if type(obj) is not Tree:
447             raise NotTreeError(sha)
448         if p == '':
449             continue
450         mode, sha = obj[p]
451     return lookup_obj(sha)
452
453
454 class MissingObjectFinder(object):
455     """Find the objects missing from another object store.
456
457     :param object_store: Object store containing at least all objects to be 
458         sent
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.
462     """
463
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
468         if progress is None:
469             self.progress = lambda x: None
470         else:
471             self.progress = progress
472
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])
475
476     def parse_tree(self, tree):
477         self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries()])
478
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])
482
483     def parse_tag(self, tag):
484         self.add_todo([(tag.object[1], None, False)])
485
486     def next(self):
487         if not self.objects_to_send:
488             return None
489         (sha, name, leaf) = self.objects_to_send.pop()
490         if not leaf:
491             o = self.object_store[sha]
492             if isinstance(o, Commit):
493                 self.parse_commit(o)
494             elif isinstance(o, Tree):
495                 self.parse_tree(o)
496             elif isinstance(o, Tag):
497                 self.parse_tag(o)
498         self.sha_done.add(sha)
499         self.progress("counting objects: %d\r" % len(self.sha_done))
500         return (sha, name)
501
502
503 class ObjectStoreGraphWalker(object):
504     """Graph walker that finds out what commits are missing from an object store."""
505
506     def __init__(self, local_heads, get_parents):
507         """Create a new instance.
508
509         :param local_heads: Heads to start search with
510         :param get_parents: Function for finding the parents of a SHA1.
511         """
512         self.heads = set(local_heads)
513         self.get_parents = get_parents
514         self.parents = {}
515
516     def ack(self, sha):
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]:
522                 self.ack(p)
523
524     def next(self):
525         """Iterate over ancestors of heads in the target."""
526         if self.heads:
527             ret = self.heads.pop()
528             ps = self.get_parents(ret)
529             self.parents[ret] = ps
530             self.heads.update(ps)
531             return ret
532         return None