Some trivial formatting fixes.
[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_chunks(self):
137         compobj = zlib.compressobj()
138         yield compobj.compress(self._header())
139         for chunk in self.as_raw_chunks():
140             yield compobj.compress(chunk)
141         yield compobj.flush()
142
143     def as_legacy_object(self):
144         return "".join(self.as_legacy_object_chunks())
145
146     def as_raw_chunks(self):
147         if self._needs_serialization:
148             self._chunked_text = self._serialize()
149             self._needs_serialization = False
150         return self._chunked_text
151
152     def as_raw_string(self):
153         return "".join(self.as_raw_chunks())
154
155     def __str__(self):
156         return self.as_raw_string()
157
158     def __hash__(self):
159         return hash(self.id)
160
161     def as_pretty_string(self):
162         return self.as_raw_string()
163
164     def _ensure_parsed(self):
165         if self._needs_parsing:
166             self._deserialize(self._chunked_text)
167             self._needs_parsing = False
168
169     def set_raw_string(self, text):
170         if type(text) != str:
171             raise TypeError(text)
172         self.set_raw_chunks([text])
173
174     def set_raw_chunks(self, chunks):
175         self._chunked_text = chunks
176         self._sha = None
177         self._needs_parsing = True
178         self._needs_serialization = False
179
180     @classmethod
181     def _parse_object(cls, map):
182         """Parse a new style object , creating it and setting object._text"""
183         used = 0
184         byte = ord(map[used])
185         used += 1
186         type_num = (byte >> 4) & 7
187         try:
188             object = object_class(type_num)()
189         except KeyError:
190             raise AssertionError("Not a known type: %d" % type_num)
191         while (byte & 0x80) != 0:
192             byte = ord(map[used])
193             used += 1
194         raw = map[used:]
195         object.set_raw_string(_decompress(raw))
196         return object
197
198     @classmethod
199     def _parse_file(cls, map):
200         word = (ord(map[0]) << 8) + ord(map[1])
201         if ord(map[0]) == 0x78 and (word % 31) == 0:
202             return cls._parse_legacy_object(map)
203         else:
204             return cls._parse_object(map)
205
206     def __init__(self):
207         """Don't call this directly"""
208         self._sha = None
209
210     def _deserialize(self, chunks):
211         raise NotImplementedError(self._deserialize)
212
213     def _serialize(self):
214         raise NotImplementedError(self._serialize)
215
216     @classmethod
217     def from_file(cls, filename):
218         """Get the contents of a SHA file on disk"""
219         size = os.path.getsize(filename)
220         f = GitFile(filename, 'rb')
221         try:
222             map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
223             shafile = cls._parse_file(map)
224             return shafile
225         finally:
226             f.close()
227
228     @staticmethod
229     def from_raw_string(type_num, string):
230         """Creates an object of the indicated type from the raw string given.
231
232         :param type_num: The numeric type of the object.
233         :param string: The raw uncompressed contents.
234         """
235         obj = object_class(type_num)()
236         obj.set_raw_string(string)
237         return obj
238
239     @staticmethod
240     def from_raw_chunks(type_num, chunks):
241         """Creates an object of the indicated type from the raw chunks given.
242
243         :param type_num: The numeric type of the object.
244         :param chunks: An iterable of the raw uncompressed contents.
245         """
246         obj = object_class(type_num)()
247         obj.set_raw_chunks(chunks)
248         return obj
249
250     @classmethod
251     def from_string(cls, string):
252         """Create a blob from a string."""
253         obj = cls()
254         obj.set_raw_string(string)
255         return obj
256
257     def _header(self):
258         return "%s %lu\0" % (self.type_name, self.raw_length())
259
260     def raw_length(self):
261         """Returns the length of the raw string of this object."""
262         ret = 0
263         for chunk in self.as_raw_chunks():
264             ret += len(chunk)
265         return ret
266
267     def _make_sha(self):
268         ret = make_sha()
269         ret.update(self._header())
270         for chunk in self.as_raw_chunks():
271             ret.update(chunk)
272         return ret
273
274     def sha(self):
275         """The SHA1 object that is the name of this object."""
276         if self._needs_serialization or self._sha is None:
277             self._sha = self._make_sha()
278         return self._sha
279
280     @property
281     def id(self):
282         return self.sha().hexdigest()
283
284     def get_type(self):
285         return self.type_num
286
287     def set_type(self, type):
288         self.type_num = type
289
290     # DEPRECATED: use type_num or type_name as needed.
291     type = property(get_type, set_type)
292
293     def __repr__(self):
294         return "<%s %s>" % (self.__class__.__name__, self.id)
295
296     def __ne__(self, other):
297         return self.id != other.id
298
299     def __eq__(self, other):
300         """Return true if the sha of the two objects match.
301
302         The __le__ etc methods aren't overriden as they make no sense,
303         certainly at this level.
304         """
305         return self.id == other.id
306
307
308 class Blob(ShaFile):
309     """A Git Blob object."""
310
311     type_name = 'blob'
312     type_num = 3
313
314     def __init__(self):
315         super(Blob, self).__init__()
316         self._chunked_text = []
317         self._needs_parsing = False
318         self._needs_serialization = False
319
320     def _get_data(self):
321         return self.as_raw_string()
322
323     def _set_data(self, data):
324         self.set_raw_string(data)
325
326     data = property(_get_data, _set_data,
327             "The text contained within the blob object.")
328
329     def _get_chunked(self):
330         return self._chunked_text
331
332     def _set_chunked(self, chunks):
333         self._chunked_text = chunks
334
335     chunked = property(_get_chunked, _set_chunked,
336         "The text within the blob object, as chunks (not necessarily lines).")
337
338     @classmethod
339     def from_file(cls, filename):
340         blob = ShaFile.from_file(filename)
341         if not isinstance(blob, cls):
342             raise NotBlobError(filename)
343         return blob
344
345
346 class Tag(ShaFile):
347     """A Git Tag object."""
348
349     type_name = 'tag'
350     type_num = 4
351
352     def __init__(self):
353         super(Tag, self).__init__()
354         self._needs_parsing = False
355         self._needs_serialization = True
356
357     @classmethod
358     def from_file(cls, filename):
359         tag = ShaFile.from_file(filename)
360         if not isinstance(tag, cls):
361             raise NotTagError(filename)
362         return tag
363
364     @classmethod
365     def from_string(cls, string):
366         """Create a blob from a string."""
367         shafile = cls()
368         shafile.set_raw_string(string)
369         return shafile
370
371     def _serialize(self):
372         chunks = []
373         chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
374         chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
375         chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
376         if self._tagger:
377             if self._tag_time is None:
378                 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
379             else:
380                 chunks.append("%s %s %d %s\n" % (
381                   _TAGGER_HEADER, self._tagger, self._tag_time,
382                   format_timezone(self._tag_timezone)))
383         chunks.append("\n") # To close headers
384         chunks.append(self._message)
385         return chunks
386
387     def _deserialize(self, chunks):
388         """Grab the metadata attached to the tag"""
389         self._tagger = None
390         f = StringIO("".join(chunks))
391         for l in f:
392             l = l.rstrip("\n")
393             if l == "":
394                 break # empty line indicates end of headers
395             (field, value) = l.split(" ", 1)
396             if field == _OBJECT_HEADER:
397                 self._object_sha = value
398             elif field == _TYPE_HEADER:
399                 self._object_class = object_class(value)
400             elif field == _TAG_HEADER:
401                 self._name = value
402             elif field == _TAGGER_HEADER:
403                 try:
404                     sep = value.index("> ")
405                 except ValueError:
406                     self._tagger = value
407                     self._tag_time = None
408                     self._tag_timezone = None
409                 else:
410                     self._tagger = value[0:sep+1]
411                     (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
412                     try:
413                         self._tag_time = int(timetext)
414                     except ValueError: #Not a unix timestamp
415                         self._tag_time = time.strptime(timetext)
416                     self._tag_timezone = parse_timezone(timezonetext)
417             else:
418                 raise AssertionError("Unknown field %s" % field)
419         self._message = f.read()
420
421     def _get_object(self):
422         """Get the object pointed to by this tag.
423
424         :return: tuple of (object class, sha).
425         """
426         self._ensure_parsed()
427         return (self._object_class, self._object_sha)
428
429     def _set_object(self, value):
430         self._ensure_parsed()
431         (self._object_class, self._object_sha) = value
432         self._needs_serialization = True
433
434     object = property(_get_object, _set_object)
435
436     name = serializable_property("name", "The name of this tag")
437     tagger = serializable_property("tagger",
438         "Returns the name of the person who created this tag")
439     tag_time = serializable_property("tag_time",
440         "The creation timestamp of the tag.  As the number of seconds since the epoch")
441     tag_timezone = serializable_property("tag_timezone",
442         "The timezone that tag_time is in.")
443     message = serializable_property("message", "The message attached to this tag")
444
445
446 def parse_tree(text):
447     """Parse a tree text.
448
449     :param text: Serialized text to parse
450     :return: Dictionary with names as keys, (mode, sha) tuples as values
451     """
452     ret = {}
453     count = 0
454     l = len(text)
455     while count < l:
456         mode_end = text.index(' ', count)
457         mode = int(text[count:mode_end], 8)
458         name_end = text.index('\0', mode_end)
459         name = text[mode_end+1:name_end]
460         count = name_end+21
461         sha = text[name_end+1:count]
462         ret[name] = (mode, sha_to_hex(sha))
463     return ret
464
465
466 def serialize_tree(items):
467     """Serialize the items in a tree to a text.
468
469     :param items: Sorted iterable over (name, mode, sha) tuples
470     :return: Serialized tree text as chunks
471     """
472     for name, mode, hexsha in items:
473         yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
474
475
476 def sorted_tree_items(entries):
477     """Iterate over a tree entries dictionary in the order in which 
478     the items would be serialized.
479
480     :param entries: Dictionary mapping names to (mode, sha) tuples
481     :return: Iterator over (name, mode, sha)
482     """
483     def cmp_entry((name1, value1), (name2, value2)):
484         if stat.S_ISDIR(value1[0]):
485             name1 += "/"
486         if stat.S_ISDIR(value2[0]):
487             name2 += "/"
488         return cmp(name1, name2)
489     for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
490         yield name, entry[0], entry[1]
491
492
493 class Tree(ShaFile):
494     """A Git tree object"""
495
496     type_name = 'tree'
497     type_num = 2
498
499     def __init__(self):
500         super(Tree, self).__init__()
501         self._entries = {}
502         self._needs_parsing = False
503         self._needs_serialization = True
504
505     @classmethod
506     def from_file(cls, filename):
507         tree = ShaFile.from_file(filename)
508         if not isinstance(tree, cls):
509             raise NotTreeError(filename)
510         return tree
511
512     def __contains__(self, name):
513         self._ensure_parsed()
514         return name in self._entries
515
516     def __getitem__(self, name):
517         self._ensure_parsed()
518         return self._entries[name]
519
520     def __setitem__(self, name, value):
521         assert isinstance(value, tuple)
522         assert len(value) == 2
523         self._ensure_parsed()
524         self._entries[name] = value
525         self._needs_serialization = True
526
527     def __delitem__(self, name):
528         self._ensure_parsed()
529         del self._entries[name]
530         self._needs_serialization = True
531
532     def __len__(self):
533         self._ensure_parsed()
534         return len(self._entries)
535
536     def add(self, mode, name, hexsha):
537         assert type(mode) == int
538         assert type(name) == str
539         assert type(hexsha) == str
540         self._ensure_parsed()
541         self._entries[name] = mode, hexsha
542         self._needs_serialization = True
543
544     def entries(self):
545         """Return a list of tuples describing the tree entries"""
546         self._ensure_parsed()
547         # The order of this is different from iteritems() for historical
548         # reasons
549         return [
550             (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
551
552     def iteritems(self):
553         """Iterate over all entries in the order in which they would be
554         serialized.
555
556         :return: Iterator over (name, mode, sha) tuples
557         """
558         self._ensure_parsed()
559         return sorted_tree_items(self._entries)
560
561     def _deserialize(self, chunks):
562         """Grab the entries in the tree"""
563         self._entries = parse_tree("".join(chunks))
564
565     def _serialize(self):
566         return list(serialize_tree(self.iteritems()))
567
568     def as_pretty_string(self):
569         text = []
570         for name, mode, hexsha in self.iteritems():
571             if mode & stat.S_IFDIR:
572                 kind = "tree"
573             else:
574                 kind = "blob"
575             text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
576         return "".join(text)
577
578
579 def parse_timezone(text):
580     offset = int(text)
581     signum = (offset < 0) and -1 or 1
582     offset = abs(offset)
583     hours = int(offset / 100)
584     minutes = (offset % 100)
585     return signum * (hours * 3600 + minutes * 60)
586
587
588 def format_timezone(offset):
589     if offset % 60 != 0:
590         raise ValueError("Unable to handle non-minute offset.")
591     sign = (offset < 0) and '-' or '+'
592     offset = abs(offset)
593     return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
594
595
596 class Commit(ShaFile):
597     """A git commit object"""
598
599     type_name = 'commit'
600     type_num = 1
601
602     def __init__(self):
603         super(Commit, self).__init__()
604         self._parents = []
605         self._encoding = None
606         self._needs_parsing = False
607         self._needs_serialization = True
608         self._extra = {}
609
610     @classmethod
611     def from_file(cls, filename):
612         commit = ShaFile.from_file(filename)
613         if not isinstance(commit, cls):
614             raise NotCommitError(filename)
615         return commit
616
617     def _deserialize(self, chunks):
618         self._parents = []
619         self._extra = []
620         self._author = None
621         f = StringIO("".join(chunks))
622         for l in f:
623             l = l.rstrip("\n")
624             if l == "":
625                 # Empty line indicates end of headers
626                 break
627             (field, value) = l.split(" ", 1)
628             if field == _TREE_HEADER:
629                 self._tree = value
630             elif field == _PARENT_HEADER:
631                 self._parents.append(value)
632             elif field == _AUTHOR_HEADER:
633                 self._author, timetext, timezonetext = value.rsplit(" ", 2)
634                 self._author_time = int(timetext)
635                 self._author_timezone = parse_timezone(timezonetext)
636             elif field == _COMMITTER_HEADER:
637                 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
638                 self._commit_time = int(timetext)
639                 self._commit_timezone = parse_timezone(timezonetext)
640             elif field == _ENCODING_HEADER:
641                 self._encoding = value
642             else:
643                 self._extra.append((field, value))
644         self._message = f.read()
645
646     def _serialize(self):
647         chunks = []
648         chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
649         for p in self._parents:
650             chunks.append("%s %s\n" % (_PARENT_HEADER, p))
651         chunks.append("%s %s %s %s\n" % (
652           _AUTHOR_HEADER, self._author, str(self._author_time),
653           format_timezone(self._author_timezone)))
654         chunks.append("%s %s %s %s\n" % (
655           _COMMITTER_HEADER, self._committer, str(self._commit_time),
656           format_timezone(self._commit_timezone)))
657         if self.encoding:
658             chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
659         for k, v in self.extra:
660             if "\n" in k or "\n" in v:
661                 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
662             chunks.append("%s %s\n" % (k, v))
663         chunks.append("\n") # There must be a new line after the headers
664         chunks.append(self._message)
665         return chunks
666
667     tree = serializable_property("tree", "Tree that is the state of this commit")
668
669     def _get_parents(self):
670         """Return a list of parents of this commit."""
671         self._ensure_parsed()
672         return self._parents
673
674     def _set_parents(self, value):
675         """Set a list of parents of this commit."""
676         self._ensure_parsed()
677         self._needs_serialization = True
678         self._parents = value
679
680     parents = property(_get_parents, _set_parents)
681
682     def _get_extra(self):
683         """Return extra settings of this commit."""
684         self._ensure_parsed()
685         return self._extra
686
687     extra = property(_get_extra)
688
689     author = serializable_property("author",
690         "The name of the author of the commit")
691
692     committer = serializable_property("committer",
693         "The name of the committer of the commit")
694
695     message = serializable_property("message",
696         "The commit message")
697
698     commit_time = serializable_property("commit_time",
699         "The timestamp of the commit. As the number of seconds since the epoch.")
700
701     commit_timezone = serializable_property("commit_timezone",
702         "The zone the commit time is in")
703
704     author_time = serializable_property("author_time",
705         "The timestamp the commit was written. as the number of seconds since the epoch.")
706
707     author_timezone = serializable_property("author_timezone",
708         "Returns the zone the author time is in.")
709
710     encoding = serializable_property("encoding",
711         "Encoding of the commit message.")
712
713
714 OBJECT_CLASSES = (
715     Commit,
716     Tree,
717     Blob,
718     Tag,
719     )
720
721 _TYPE_MAP = {}
722
723 for cls in OBJECT_CLASSES:
724     _TYPE_MAP[cls.type_name] = cls
725     _TYPE_MAP[cls.type_num] = cls
726
727
728 try:
729     # Try to import C versions
730     from dulwich._objects import parse_tree, sorted_tree_items
731 except ImportError:
732     pass