Raise sha error if necessary, always return refs, fix docs.
[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 class ObjectStore(object):
54     """Object store."""
55
56     def __init__(self, path):
57         """Open an object store.
58
59         :param path: Path of the object store.
60         """
61         self.path = path
62         self._pack_cache = None
63         self.pack_dir = os.path.join(self.path, PACKDIR)
64
65     def determine_wants_all(self, refs):
66             return [sha for (ref, sha) in refs.iteritems() if not sha in self and not ref.endswith("^{}")]
67
68     def iter_shas(self, shas):
69         """Iterate over the objects for the specified shas.
70
71         :param shas: Iterable object with SHAs
72         """
73         return ObjectStoreIterator(self, shas)
74
75     def __contains__(self, sha):
76         """Check if a particular object is present by SHA1."""
77         for pack in self.packs:
78             if sha in pack:
79                 return True
80         ret = self._get_shafile(sha)
81         if ret is not None:
82             return True
83         return False
84
85     def __iter__(self):
86         """Iterate over the SHAs that are present in this store."""
87         iterables = self.packs + [self._iter_shafile_shas()]
88         return itertools.chain(*iterables)
89
90     @property
91     def packs(self):
92         """List with pack objects."""
93         if self._pack_cache is None:
94             self._pack_cache = list(load_packs(self.pack_dir))
95         return self._pack_cache
96
97     def _add_known_pack(self, path):
98         """Add a newly appeared pack to the cache by path.
99
100         """
101         if self._pack_cache is not None:
102             self._pack_cache.append(Pack(path))
103
104     def _get_shafile_path(self, sha):
105         dir = sha[:2]
106         file = sha[2:]
107         # Check from object dir
108         return os.path.join(self.path, dir, file)
109
110     def _iter_shafile_shas(self):
111         for base in os.listdir(self.path):
112             if len(base) != 2:
113                 continue
114             for rest in os.listdir(os.path.join(self.path, base)):
115                 yield base+rest
116
117     def _get_shafile(self, sha):
118         path = self._get_shafile_path(sha)
119         if os.path.exists(path):
120           return ShaFile.from_file(path)
121         return None
122
123     def _add_shafile(self, sha, o):
124         dir = os.path.join(self.path, sha[:2])
125         if not os.path.isdir(dir):
126             os.mkdir(dir)
127         path = os.path.join(dir, sha[2:])
128         f = open(path, 'w+')
129         try:
130             f.write(o.as_legacy_object())
131         finally:
132             f.close()
133
134     def get_raw(self, name):
135         """Obtain the raw text for an object.
136         
137         :param name: sha for the object.
138         :return: tuple with object type and object contents.
139         """
140         if len(name) == 40:
141             sha = hex_to_sha(name)
142             hexsha = name
143         elif len(name) == 20:
144             sha = name
145             hexsha = None
146         else:
147             raise AssertionError
148         for pack in self.packs:
149             try:
150                 return pack.get_raw(sha)
151             except KeyError:
152                 pass
153         if hexsha is None: 
154             hexsha = sha_to_hex(name)
155         ret = self._get_shafile(hexsha)
156         if ret is not None:
157             return ret.type, ret.as_raw_string()
158         raise KeyError(hexsha)
159
160     def __getitem__(self, sha):
161         type, uncomp = self.get_raw(sha)
162         return ShaFile.from_raw_string(type, uncomp)
163
164     def move_in_thin_pack(self, path):
165         """Move a specific file containing a pack into the pack directory.
166
167         :note: The file should be on the same file system as the 
168             packs directory.
169
170         :param path: Path to the pack file.
171         """
172         data = PackData(path)
173
174         # Write index for the thin pack (do we really need this?)
175         temppath = os.path.join(self.pack_dir, 
176             sha_to_hex(urllib2.randombytes(20))+".tempidx")
177         data.create_index_v2(temppath, self.get_raw)
178         p = Pack.from_objects(data, load_pack_index(temppath))
179
180         # Write a full pack version
181         temppath = os.path.join(self.pack_dir, 
182             sha_to_hex(urllib2.randombytes(20))+".temppack")
183         write_pack(temppath, ((o, None) for o in p.iterobjects(self.get_raw)), 
184                 len(p))
185         pack_sha = load_pack_index(temppath+".idx").objects_sha1()
186         newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
187         os.rename(temppath+".pack", newbasename+".pack")
188         os.rename(temppath+".idx", newbasename+".idx")
189         self._add_known_pack(newbasename)
190
191     def move_in_pack(self, path):
192         """Move a specific file containing a pack into the pack directory.
193
194         :note: The file should be on the same file system as the 
195             packs directory.
196
197         :param path: Path to the pack file.
198         """
199         p = PackData(path)
200         entries = p.sorted_entries()
201         basename = os.path.join(self.pack_dir, 
202             "pack-%s" % iter_sha1(entry[0] for entry in entries))
203         write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
204         os.rename(path, basename + ".pack")
205         self._add_known_pack(basename)
206
207     def add_thin_pack(self):
208         """Add a new thin pack to this object store.
209
210         Thin packs are packs that contain deltas with parents that exist 
211         in a different pack.
212         """
213         fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
214         f = os.fdopen(fd, 'w')
215         def commit():
216             os.fsync(fd)
217             f.close()
218             if os.path.getsize(path) > 0:
219                 self.move_in_thin_pack(path)
220         return f, commit
221
222     def add_pack(self):
223         """Add a new pack to this object store. 
224
225         :return: Fileobject to write to and a commit function to 
226             call when the pack is finished.
227         """
228         fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
229         f = os.fdopen(fd, 'w')
230         def commit():
231             os.fsync(fd)
232             f.close()
233             if os.path.getsize(path) > 0:
234                 self.move_in_pack(path)
235         return f, commit
236
237     def add_object(self, obj):
238         """Add a single object to this object store.
239
240         """
241         self._add_shafile(obj.id, obj)
242
243     def add_objects(self, objects):
244         """Add a set of objects to this object store.
245
246         :param objects: Iterable over a list of objects.
247         """
248         if len(objects) == 0:
249             return
250         f, commit = self.add_pack()
251         write_pack_data(f, objects, len(objects))
252         commit()
253
254     def find_missing_objects(self, wants, graph_walker, progress=None):
255         """Find the missing objects required for a set of revisions.
256
257         :param wants: Iterable over SHAs of objects to fetch.
258         :param graph_walker: Object that can iterate over the list of revisions 
259             to fetch and has an "ack" method that will be called to acknowledge 
260             that a revision is present.
261         :param progress: Simple progress function that will be called with 
262             updated progress strings.
263         :return: Iterator over (sha, path) pairs.
264         """
265         return iter(MissingObjectFinder(self, wants, graph_walker, progress).next, None)
266
267
268 class ObjectImporter(object):
269     """Interface for importing objects."""
270
271     def __init__(self, count):
272         """Create a new ObjectImporter.
273
274         :param count: Number of objects that's going to be imported.
275         """
276         self.count = count
277
278     def add_object(self, object):
279         """Add an object."""
280         raise NotImplementedError(self.add_object)
281
282     def finish(self, object):
283         """Finish the imoprt and write objects to disk."""
284         raise NotImplementedError(self.finish)
285
286
287 class ObjectIterator(object):
288     """Interface for iterating over objects."""
289
290     def iterobjects(self):
291         raise NotImplementedError(self.iterobjects)
292
293
294 class ObjectStoreIterator(ObjectIterator):
295     """ObjectIterator that works on top of an ObjectStore."""
296
297     def __init__(self, store, sha_iter):
298         self.store = store
299         self.sha_iter = sha_iter
300         self._shas = []
301
302     def __iter__(self):
303         for sha, path in self.itershas():
304             yield self.store[sha], path
305
306     def iterobjects(self):
307         for o, path in self:
308             yield o
309
310     def itershas(self):
311         for sha in self._shas:
312             yield sha
313         for sha in self.sha_iter:
314             self._shas.append(sha)
315             yield sha
316
317     def __contains__(self, needle):
318         """Check if an object is present.
319
320         :param needle: SHA1 of the object to check for
321         """
322         return needle in self.store
323
324     def __getitem__(self, key):
325         """Find an object by SHA1."""
326         return self.store[key]
327
328     def __len__(self):
329         """Return the number of objects."""
330         return len(list(self.itershas()))
331
332
333 def tree_lookup_path(lookup_obj, root_sha, path):
334     """Lookup an object in a Git tree.
335
336     :param lookup_obj: Callback for retrieving object by SHA1
337     :param root_sha: SHA1 of the root tree
338     :param path: Path to lookup
339     """
340     parts = path.split("/")
341     sha = root_sha
342     for p in parts:
343         obj = lookup_obj(sha)
344         if type(obj) is not Tree:
345             raise NotTreeError(sha)
346         if p == '':
347             continue
348         mode, sha = obj[p]
349     return lookup_obj(sha)
350
351
352 class MissingObjectFinder(object):
353     """Find the objects missing from another object store.
354
355     :param object_store: Object store containing at least all objects to be 
356         sent
357     :param wants: SHA1s of commits to send
358     :param graph_walker: graph walker object used to see what the remote 
359         repo has and misses
360     :param progress: Optional function to report progress to.
361     """
362
363     def __init__(self, object_store, wants, graph_walker, progress=None):
364         self.sha_done = set()
365         self.objects_to_send = set([(w, None, False) for w in wants])
366         self.object_store = object_store
367         if progress is None:
368             self.progress = lambda x: None
369         else:
370             self.progress = progress
371         ref = graph_walker.next()
372         while ref:
373             if ref in self.object_store:
374                 graph_walker.ack(ref)
375             ref = graph_walker.next()
376
377     def add_todo(self, entries):
378         self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
379
380     def parse_tree(self, tree):
381         self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries()])
382
383     def parse_commit(self, commit):
384         self.add_todo([(commit.tree, "", False)])
385         self.add_todo([(p, None, False) for p in commit.parents])
386
387     def parse_tag(self, tag):
388         self.add_todo([(tag.object[1], None, False)])
389
390     def next(self):
391         if not self.objects_to_send:
392             return None
393         (sha, name, leaf) = self.objects_to_send.pop()
394         if not leaf:
395             o = self.object_store[sha]
396             if isinstance(o, Commit):
397                 self.parse_commit(o)
398             elif isinstance(o, Tree):
399                 self.parse_tree(o)
400             elif isinstance(o, Tag):
401                 self.parse_tag(o)
402         self.sha_done.add(sha)
403         self.progress("counting objects: %d\r" % len(self.sha_done))
404         return (sha, name)