Support progress argument to generate_pack_contents.
[jelmer/dulwich-libgit2.git] / dulwich / objects.py
1 # objects.py -- Access to base git objects
2 # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
3 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; version 2
8 # of the License or (at your option) a later version of the License.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 # MA  02110-1301, USA.
19
20
21 """Access to base git objects."""
22
23
24 import binascii
25 from cStringIO import (
26     StringIO,
27     )
28 import mmap
29 import os
30 import stat
31 import time
32 import zlib
33
34 from dulwich.errors import (
35     NotBlobError,
36     NotCommitError,
37     NotTreeError,
38     )
39 from dulwich.file import GitFile
40 from dulwich.misc import (
41     make_sha,
42     )
43
44
45 # Header fields for commits
46 _TREE_HEADER = "tree"
47 _PARENT_HEADER = "parent"
48 _AUTHOR_HEADER = "author"
49 _COMMITTER_HEADER = "committer"
50 _ENCODING_HEADER = "encoding"
51
52
53 # Header fields for objects
54 _OBJECT_HEADER = "object"
55 _TYPE_HEADER = "type"
56 _TAG_HEADER = "tag"
57 _TAGGER_HEADER = "tagger"
58
59
60 S_IFGITLINK = 0160000
61
62 def S_ISGITLINK(m):
63     return (stat.S_IFMT(m) == S_IFGITLINK)
64
65
66 def _decompress(string):
67     dcomp = zlib.decompressobj()
68     dcomped = dcomp.decompress(string)
69     dcomped += dcomp.flush()
70     return dcomped
71
72
73 def sha_to_hex(sha):
74     """Takes a string and returns the hex of the sha within"""
75     hexsha = binascii.hexlify(sha)
76     assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
77     return hexsha
78
79
80 def hex_to_sha(hex):
81     """Takes a hex sha and returns a binary sha"""
82     assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
83     return binascii.unhexlify(hex)
84
85
86 def serializable_property(name, docstring=None):
87     def set(obj, value):
88         obj._ensure_parsed()
89         setattr(obj, "_"+name, value)
90         obj._needs_serialization = True
91     def get(obj):
92         obj._ensure_parsed()
93         return getattr(obj, "_"+name)
94     return property(get, set, doc=docstring)
95
96
97 def object_class(type):
98     """Get the object class corresponding to the given type.
99
100     :param type: Either a type name string or a numeric type.
101     :return: The ShaFile subclass corresponding to the given type.
102     """
103     return _TYPE_MAP[type]
104
105
106 class ShaFile(object):
107     """A git SHA file."""
108
109     @classmethod
110     def _parse_legacy_object(cls, map):
111         """Parse a legacy object, creating it and setting object._text"""
112         text = _decompress(map)
113         object = None
114         for cls in OBJECT_CLASSES:
115             if text.startswith(cls.type_name):
116                 object = cls()
117                 text = text[len(cls.type_name):]
118                 break
119         assert object is not None, "%s is not a known object type" % text[:9]
120         assert text[0] == ' ', "%s is not a space" % text[0]
121         text = text[1:]
122         size = 0
123         i = 0
124         while text[0] >= '0' and text[0] <= '9':
125             if i > 0 and size == 0:
126                 raise AssertionError("Size is not in canonical format")
127             size = (size * 10) + int(text[0])
128             text = text[1:]
129             i += 1
130         object._size = size
131         assert text[0] == "\0", "Size not followed by null"
132         text = text[1:]
133         object.set_raw_string(text)
134         return object
135
136     def as_legacy_object(self):
137         text = self.as_raw_string()
138         return zlib.compress("%s %d\0%s" % (self.type_name, len(text), text))
139
140     def as_raw_chunks(self):
141         if self._needs_serialization:
142             self._chunked_text = self._serialize()
143             self._needs_serialization = False
144         return self._chunked_text
145
146     def as_raw_string(self):
147         return "".join(self.as_raw_chunks())
148
149     def __str__(self):
150         return self.as_raw_string()
151
152     def __hash__(self):
153         return hash(self.id)
154
155     def as_pretty_string(self):
156         return self.as_raw_string()
157
158     def _ensure_parsed(self):
159         if self._needs_parsing:
160             self._deserialize(self._chunked_text)
161             self._needs_parsing = False
162
163     def set_raw_string(self, text):
164         if type(text) != str:
165             raise TypeError(text)
166         self.set_raw_chunks([text])
167
168     def set_raw_chunks(self, chunks):
169         self._chunked_text = chunks
170         self._sha = None
171         self._needs_parsing = True
172         self._needs_serialization = False
173
174     @classmethod
175     def _parse_object(cls, map):
176         """Parse a new style object , creating it and setting object._text"""
177         used = 0
178         byte = ord(map[used])
179         used += 1
180         type_num = (byte >> 4) & 7
181         try:
182             object = object_class(type_num)()
183         except KeyError:
184             raise AssertionError("Not a known type: %d" % type_num)
185         while (byte & 0x80) != 0:
186             byte = ord(map[used])
187             used += 1
188         raw = map[used:]
189         object.set_raw_string(_decompress(raw))
190         return object
191
192     @classmethod
193     def _parse_file(cls, map):
194         word = (ord(map[0]) << 8) + ord(map[1])
195         if ord(map[0]) == 0x78 and (word % 31) == 0:
196             return cls._parse_legacy_object(map)
197         else:
198             return cls._parse_object(map)
199
200     def __init__(self):
201         """Don't call this directly"""
202         self._sha = None
203
204     def _deserialize(self, chunks):
205         raise NotImplementedError(self._deserialize)
206
207     def _serialize(self):
208         raise NotImplementedError(self._serialize)
209
210     @classmethod
211     def from_file(cls, filename):
212         """Get the contents of a SHA file on disk"""
213         size = os.path.getsize(filename)
214         f = GitFile(filename, 'rb')
215         try:
216             map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
217             shafile = cls._parse_file(map)
218             return shafile
219         finally:
220             f.close()
221
222     @staticmethod
223     def from_raw_string(type_num, string):
224         """Creates an object of the indicated type from the raw string given.
225
226         :param type_num: The numeric type of the object.
227         :param string: The raw uncompressed contents.
228         """
229         obj = object_class(type_num)()
230         obj.set_raw_string(string)
231         return obj
232
233     @staticmethod
234     def from_raw_chunks(type_num, chunks):
235         """Creates an object of the indicated type from the raw chunks given.
236
237         :param type_num: The numeric type of the object.
238         :param chunks: An iterable of the raw uncompressed contents.
239         """
240         obj = object_class(type_num)()
241         obj.set_raw_chunks(chunks)
242         return obj
243
244     @classmethod
245     def from_string(cls, string):
246         """Create a blob from a string."""
247         obj = cls()
248         obj.set_raw_string(string)
249         return obj
250
251     def _header(self):
252         return "%s %lu\0" % (self.type_name, self.raw_length())
253
254     def raw_length(self):
255         """Returns the length of the raw string of this object."""
256         ret = 0
257         for chunk in self.as_raw_chunks():
258             ret += len(chunk)
259         return ret
260
261     def _make_sha(self):
262         ret = make_sha()
263         ret.update(self._header())
264         for chunk in self.as_raw_chunks():
265             ret.update(chunk)
266         return ret
267
268     def sha(self):
269         """The SHA1 object that is the name of this object."""
270         if self._needs_serialization or self._sha is None:
271             self._sha = self._make_sha()
272         return self._sha
273
274     @property
275     def id(self):
276         return self.sha().hexdigest()
277
278     def get_type(self):
279         return self.type_num
280
281     def set_type(self, type):
282         self.type_num = type
283
284     # DEPRECATED: use type_num or type_name as needed.
285     type = property(get_type, set_type)
286
287     def __repr__(self):
288         return "<%s %s>" % (self.__class__.__name__, self.id)
289
290     def __ne__(self, other):
291         return self.id != other.id
292
293     def __eq__(self, other):
294         """Return true if the sha of the two objects match.
295
296         The __le__ etc methods aren't overriden as they make no sense,
297         certainly at this level.
298         """
299         return self.id == other.id
300
301
302 class Blob(ShaFile):
303     """A Git Blob object."""
304
305     type_name = 'blob'
306     type_num = 3
307
308     def __init__(self):
309         super(Blob, self).__init__()
310         self._chunked_text = []
311         self._needs_parsing = False
312         self._needs_serialization = False
313
314     def _get_data(self):
315         return self.as_raw_string()
316
317     def _set_data(self, data):
318         self.set_raw_string(data)
319
320     data = property(_get_data, _set_data,
321             "The text contained within the blob object.")
322
323     def _get_chunked(self):
324         return self._chunked_text
325
326     def _set_chunked(self, chunks):
327         self._chunked_text = chunks
328
329     chunked = property(_get_chunked, _set_chunked,
330         "The text within the blob object, as chunks (not necessarily lines).")
331
332     @classmethod
333     def from_file(cls, filename):
334         blob = ShaFile.from_file(filename)
335         if not isinstance(blob, cls):
336             raise NotBlobError(filename)
337         return blob
338
339
340 class Tag(ShaFile):
341     """A Git Tag object."""
342
343     type_name = 'tag'
344     type_num = 4
345
346     def __init__(self):
347         super(Tag, self).__init__()
348         self._needs_parsing = False
349         self._needs_serialization = True
350
351     @classmethod
352     def from_file(cls, filename):
353         tag = ShaFile.from_file(filename)
354         if not isinstance(tag, cls):
355             raise NotTagError(filename)
356         return tag
357
358     @classmethod
359     def from_string(cls, string):
360         """Create a blob from a string."""
361         shafile = cls()
362         shafile.set_raw_string(string)
363         return shafile
364
365     def _serialize(self):
366         chunks = []
367         chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
368         chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
369         chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
370         if self._tagger:
371             if self._tag_time is None:
372                 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
373             else:
374                 chunks.append("%s %s %d %s\n" % (
375                   _TAGGER_HEADER, self._tagger, self._tag_time,
376                   format_timezone(self._tag_timezone)))
377         chunks.append("\n") # To close headers
378         chunks.append(self._message)
379         return chunks
380
381     def _deserialize(self, chunks):
382         """Grab the metadata attached to the tag"""
383         self._tagger = None
384         f = StringIO("".join(chunks))
385         for l in f:
386             l = l.rstrip("\n")
387             if l == "":
388                 break # empty line indicates end of headers
389             (field, value) = l.split(" ", 1)
390             if field == _OBJECT_HEADER:
391                 self._object_sha = value
392             elif field == _TYPE_HEADER:
393                 self._object_class = object_class(value)
394             elif field == _TAG_HEADER:
395                 self._name = value
396             elif field == _TAGGER_HEADER:
397                 try:
398                     sep = value.index("> ")
399                 except ValueError:
400                     self._tagger = value
401                     self._tag_time = None
402                     self._tag_timezone = None
403                 else:
404                     self._tagger = value[0:sep+1]
405                     (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
406                     try:
407                         self._tag_time = int(timetext)
408                     except ValueError: #Not a unix timestamp
409                         self._tag_time = time.strptime(timetext)
410                     self._tag_timezone = parse_timezone(timezonetext)
411             else:
412                 raise AssertionError("Unknown field %s" % field)
413         self._message = f.read()
414
415     def _get_object(self):
416         """Get the object pointed to by this tag.
417
418         :return: tuple of (object class, sha).
419         """
420         self._ensure_parsed()
421         return (self._object_class, self._object_sha)
422
423     def _set_object(self, value):
424         self._ensure_parsed()
425         (self._object_class, self._object_sha) = value
426         self._needs_serialization = True
427
428     object = property(_get_object, _set_object)
429
430     name = serializable_property("name", "The name of this tag")
431     tagger = serializable_property("tagger",
432         "Returns the name of the person who created this tag")
433     tag_time = serializable_property("tag_time",
434         "The creation timestamp of the tag.  As the number of seconds since the epoch")
435     tag_timezone = serializable_property("tag_timezone",
436         "The timezone that tag_time is in.")
437     message = serializable_property("message", "The message attached to this tag")
438
439
440 def parse_tree(text):
441     """Parse a tree text.
442
443     :param text: Serialized text to parse
444     :return: Dictionary with names as keys, (mode, sha) tuples as values
445     """
446     ret = {}
447     count = 0
448     l = len(text)
449     while count < l:
450         mode_end = text.index(' ', count)
451         mode = int(text[count:mode_end], 8)
452         name_end = text.index('\0', mode_end)
453         name = text[mode_end+1:name_end]
454         count = name_end+21
455         sha = text[name_end+1:count]
456         ret[name] = (mode, sha_to_hex(sha))
457     return ret
458
459
460 def serialize_tree(items):
461     """Serialize the items in a tree to a text.
462
463     :param items: Sorted iterable over (name, mode, sha) tuples
464     :return: Serialized tree text as chunks
465     """
466     for name, mode, hexsha in items:
467         yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
468
469
470 def sorted_tree_items(entries):
471     """Iterate over a tree entries dictionary in the order in which 
472     the items would be serialized.
473
474     :param entries: Dictionary mapping names to (mode, sha) tuples
475     :return: Iterator over (name, mode, sha)
476     """
477     def cmp_entry((name1, value1), (name2, value2)):
478         if stat.S_ISDIR(value1[0]):
479             name1 += "/"
480         if stat.S_ISDIR(value2[0]):
481             name2 += "/"
482         return cmp(name1, name2)
483     for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
484         yield name, entry[0], entry[1]
485
486
487 class Tree(ShaFile):
488     """A Git tree object"""
489
490     type_name = 'tree'
491     type_num = 2
492
493     def __init__(self):
494         super(Tree, self).__init__()
495         self._entries = {}
496         self._needs_parsing = False
497         self._needs_serialization = True
498
499     @classmethod
500     def from_file(cls, filename):
501         tree = ShaFile.from_file(filename)
502         if not isinstance(tree, cls):
503             raise NotTreeError(filename)
504         return tree
505
506     def __contains__(self, name):
507         self._ensure_parsed()
508         return name in self._entries
509
510     def __getitem__(self, name):
511         self._ensure_parsed()
512         return self._entries[name]
513
514     def __setitem__(self, name, value):
515         assert isinstance(value, tuple)
516         assert len(value) == 2
517         self._ensure_parsed()
518         self._entries[name] = value
519         self._needs_serialization = True
520
521     def __delitem__(self, name):
522         self._ensure_parsed()
523         del self._entries[name]
524         self._needs_serialization = True
525
526     def __len__(self):
527         self._ensure_parsed()
528         return len(self._entries)
529
530     def add(self, mode, name, hexsha):
531         assert type(mode) == int
532         assert type(name) == str
533         assert type(hexsha) == str
534         self._ensure_parsed()
535         self._entries[name] = mode, hexsha
536         self._needs_serialization = True
537
538     def entries(self):
539         """Return a list of tuples describing the tree entries"""
540         self._ensure_parsed()
541         # The order of this is different from iteritems() for historical
542         # reasons
543         return [
544             (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
545
546     def iteritems(self):
547         """Iterate over all entries in the order in which they would be
548         serialized.
549
550         :return: Iterator over (name, mode, sha) tuples
551         """
552         self._ensure_parsed()
553         return sorted_tree_items(self._entries)
554
555     def _deserialize(self, chunks):
556         """Grab the entries in the tree"""
557         self._entries = parse_tree("".join(chunks))
558
559     def _serialize(self):
560         return list(serialize_tree(self.iteritems()))
561
562     def as_pretty_string(self):
563         text = []
564         for name, mode, hexsha in self.iteritems():
565             if mode & stat.S_IFDIR:
566                 kind = "tree"
567             else:
568                 kind = "blob"
569             text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
570         return "".join(text)
571
572
573 def parse_timezone(text):
574     offset = int(text)
575     signum = (offset < 0) and -1 or 1
576     offset = abs(offset)
577     hours = int(offset / 100)
578     minutes = (offset % 100)
579     return signum * (hours * 3600 + minutes * 60)
580
581
582 def format_timezone(offset):
583     if offset % 60 != 0:
584         raise ValueError("Unable to handle non-minute offset.")
585     sign = (offset < 0) and '-' or '+'
586     offset = abs(offset)
587     return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
588
589
590 class Commit(ShaFile):
591     """A git commit object"""
592
593     type_name = 'commit'
594     type_num = 1
595
596     def __init__(self):
597         super(Commit, self).__init__()
598         self._parents = []
599         self._encoding = None
600         self._needs_parsing = False
601         self._needs_serialization = True
602         self._extra = {}
603
604     @classmethod
605     def from_file(cls, filename):
606         commit = ShaFile.from_file(filename)
607         if not isinstance(commit, cls):
608             raise NotCommitError(filename)
609         return commit
610
611     def _deserialize(self, chunks):
612         self._parents = []
613         self._extra = []
614         self._author = None
615         f = StringIO("".join(chunks))
616         for l in f:
617             l = l.rstrip("\n")
618             if l == "":
619                 # Empty line indicates end of headers
620                 break
621             (field, value) = l.split(" ", 1)
622             if field == _TREE_HEADER:
623                 self._tree = value
624             elif field == _PARENT_HEADER:
625                 self._parents.append(value)
626             elif field == _AUTHOR_HEADER:
627                 self._author, timetext, timezonetext = value.rsplit(" ", 2)
628                 self._author_time = int(timetext)
629                 self._author_timezone = parse_timezone(timezonetext)
630             elif field == _COMMITTER_HEADER:
631                 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
632                 self._commit_time = int(timetext)
633                 self._commit_timezone = parse_timezone(timezonetext)
634             elif field == _ENCODING_HEADER:
635                 self._encoding = value
636             else:
637                 self._extra.append((field, value))
638         self._message = f.read()
639
640     def _serialize(self):
641         chunks = []
642         chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
643         for p in self._parents:
644             chunks.append("%s %s\n" % (_PARENT_HEADER, p))
645         chunks.append("%s %s %s %s\n" % (
646           _AUTHOR_HEADER, self._author, str(self._author_time),
647           format_timezone(self._author_timezone)))
648         chunks.append("%s %s %s %s\n" % (
649           _COMMITTER_HEADER, self._committer, str(self._commit_time),
650           format_timezone(self._commit_timezone)))
651         if self.encoding:
652             chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
653         for k, v in self.extra:
654             if "\n" in k or "\n" in v:
655                 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
656             chunks.append("%s %s\n" % (k, v))
657         chunks.append("\n") # There must be a new line after the headers
658         chunks.append(self._message)
659         return chunks
660
661     tree = serializable_property("tree", "Tree that is the state of this commit")
662
663     def _get_parents(self):
664         """Return a list of parents of this commit."""
665         self._ensure_parsed()
666         return self._parents
667
668     def _set_parents(self, value):
669         """Set a list of parents of this commit."""
670         self._ensure_parsed()
671         self._needs_serialization = True
672         self._parents = value
673
674     parents = property(_get_parents, _set_parents)
675
676     def _get_extra(self):
677         """Return extra settings of this commit."""
678         self._ensure_parsed()
679         return self._extra
680
681     extra = property(_get_extra)
682
683     author = serializable_property("author",
684         "The name of the author of the commit")
685
686     committer = serializable_property("committer",
687         "The name of the committer of the commit")
688
689     message = serializable_property("message",
690         "The commit message")
691
692     commit_time = serializable_property("commit_time",
693         "The timestamp of the commit. As the number of seconds since the epoch.")
694
695     commit_timezone = serializable_property("commit_timezone",
696         "The zone the commit time is in")
697
698     author_time = serializable_property("author_time",
699         "The timestamp the commit was written. as the number of seconds since the epoch.")
700
701     author_timezone = serializable_property("author_timezone",
702         "Returns the zone the author time is in.")
703
704     encoding = serializable_property("encoding",
705         "Encoding of the commit message.")
706
707
708 OBJECT_CLASSES = (
709     Commit,
710     Tree,
711     Blob,
712     Tag,
713     )
714
715 _TYPE_MAP = {}
716
717 for cls in OBJECT_CLASSES:
718     _TYPE_MAP[cls.type_name] = cls
719     _TYPE_MAP[cls.type_num] = cls
720
721
722 try:
723     # Try to import C versions
724     from dulwich._objects import parse_tree, sorted_tree_items
725 except ImportError:
726     pass