Treat marks as strings internally.
[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 """Access to base git objects."""
21
22
23 import binascii
24 from cStringIO import (
25     StringIO,
26     )
27 import os
28 import stat
29 import zlib
30
31 from dulwich.errors import (
32     ChecksumMismatch,
33     NotBlobError,
34     NotCommitError,
35     NotTagError,
36     NotTreeError,
37     ObjectFormatException,
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 hex_to_filename(path, hex):
87     """Takes a hex sha and returns its filename relative to the given path."""
88     dir = hex[:2]
89     file = hex[2:]
90     # Check from object dir
91     return os.path.join(path, dir, file)
92
93
94 def filename_to_hex(filename):
95     """Takes an object filename and returns its corresponding hex sha."""
96     # grab the last (up to) two path components
97     names = filename.rsplit(os.path.sep, 2)[-2:]
98     errmsg = "Invalid object filename: %s" % filename
99     assert len(names) == 2, errmsg
100     base, rest = names
101     assert len(base) == 2 and len(rest) == 38, errmsg
102     hex = base + rest
103     hex_to_sha(hex)
104     return hex
105
106
107 def object_header(num_type, length):
108     """Return an object header for the given numeric type and text length."""
109     return "%s %d\0" % (object_class(num_type).type_name, length)
110
111
112 def serializable_property(name, docstring=None):
113     def set(obj, value):
114         obj._ensure_parsed()
115         setattr(obj, "_"+name, value)
116         obj._needs_serialization = True
117     def get(obj):
118         obj._ensure_parsed()
119         return getattr(obj, "_"+name)
120     return property(get, set, doc=docstring)
121
122
123 def object_class(type):
124     """Get the object class corresponding to the given type.
125
126     :param type: Either a type name string or a numeric type.
127     :return: The ShaFile subclass corresponding to the given type, or None if
128         type is not a valid type name/number.
129     """
130     return _TYPE_MAP.get(type, None)
131
132
133 def check_hexsha(hex, error_msg):
134     try:
135         hex_to_sha(hex)
136     except (TypeError, AssertionError):
137         raise ObjectFormatException("%s %s" % (error_msg, hex))
138
139
140 def check_identity(identity, error_msg):
141     """Check if the specified identity is valid.
142
143     This will raise an exception if the identity is not valid.
144     
145     :param identity: Identity string
146     :param error_msg: Error message to use in exception
147     """
148     email_start = identity.find("<")
149     email_end = identity.find(">")
150     if (email_start < 0 or email_end < 0 or email_end <= email_start
151         or identity.find("<", email_start + 1) >= 0
152         or identity.find(">", email_end + 1) >= 0
153         or not identity.endswith(">")):
154         raise ObjectFormatException(error_msg)
155
156
157 class FixedSha(object):
158     """SHA object that behaves like hashlib's but is given a fixed value."""
159
160     __slots__ = ('_hexsha', '_sha')
161
162     def __init__(self, hexsha):
163         self._hexsha = hexsha
164         self._sha = hex_to_sha(hexsha)
165
166     def digest(self):
167         return self._sha
168
169     def hexdigest(self):
170         return self._hexsha
171
172
173 class ShaFile(object):
174     """A git SHA file."""
175
176     __slots__ = ('_needs_parsing', '_chunked_text', '_file', '_path', 
177                  '_sha', '_needs_serialization', '_magic')
178
179     @staticmethod
180     def _parse_legacy_object_header(magic, f):
181         """Parse a legacy object, creating it but not reading the file."""
182         bufsize = 1024
183         decomp = zlib.decompressobj()
184         header = decomp.decompress(magic)
185         start = 0
186         end = -1
187         while end < 0:
188             extra = f.read(bufsize)
189             header += decomp.decompress(extra)
190             magic += extra
191             end = header.find("\0", start)
192             start = len(header)
193         header = header[:end]
194         type_name, size = header.split(" ", 1)
195         size = int(size)  # sanity check
196         obj_class = object_class(type_name)
197         if not obj_class:
198             raise ObjectFormatException("Not a known type: %s" % type_name)
199         ret = obj_class()
200         ret._magic = magic
201         return ret
202
203     def _parse_legacy_object(self, map):
204         """Parse a legacy object, setting the raw string."""
205         text = _decompress(map)
206         header_end = text.find('\0')
207         if header_end < 0:
208             raise ObjectFormatException("Invalid object header, no \\0")
209         self.set_raw_string(text[header_end+1:])
210
211     def as_legacy_object_chunks(self):
212         compobj = zlib.compressobj()
213         yield compobj.compress(self._header())
214         for chunk in self.as_raw_chunks():
215             yield compobj.compress(chunk)
216         yield compobj.flush()
217
218     def as_legacy_object(self):
219         return "".join(self.as_legacy_object_chunks())
220
221     def as_raw_chunks(self):
222         if self._needs_parsing:
223             self._ensure_parsed()
224         elif self._needs_serialization:
225             self._chunked_text = self._serialize()
226         return self._chunked_text
227
228     def as_raw_string(self):
229         return "".join(self.as_raw_chunks())
230
231     def __str__(self):
232         return self.as_raw_string()
233
234     def __hash__(self):
235         return hash(self.id)
236
237     def as_pretty_string(self):
238         return self.as_raw_string()
239
240     def _ensure_parsed(self):
241         if self._needs_parsing:
242             if not self._chunked_text:
243                 if self._file is not None:
244                     self._parse_file(self._file)
245                     self._file = None
246                 elif self._path is not None:
247                     self._parse_path()
248                 else:
249                     raise AssertionError(
250                         "ShaFile needs either text or filename")
251             self._deserialize(self._chunked_text)
252             self._needs_parsing = False
253
254     def set_raw_string(self, text):
255         if type(text) != str:
256             raise TypeError(text)
257         self.set_raw_chunks([text])
258
259     def set_raw_chunks(self, chunks):
260         self._chunked_text = chunks
261         self._deserialize(chunks)
262         self._sha = None
263         self._needs_parsing = False
264         self._needs_serialization = False
265
266     @staticmethod
267     def _parse_object_header(magic, f):
268         """Parse a new style object, creating it but not reading the file."""
269         num_type = (ord(magic[0]) >> 4) & 7
270         obj_class = object_class(num_type)
271         if not obj_class:
272             raise ObjectFormatException("Not a known type %d" % num_type)
273         ret = obj_class()
274         ret._magic = magic
275         return ret
276
277     def _parse_object(self, map):
278         """Parse a new style object, setting self._text."""
279         # skip type and size; type must have already been determined, and
280         # we trust zlib to fail if it's otherwise corrupted
281         byte = ord(map[0])
282         used = 1
283         while (byte & 0x80) != 0:
284             byte = ord(map[used])
285             used += 1
286         raw = map[used:]
287         self.set_raw_string(_decompress(raw))
288
289     @classmethod
290     def _is_legacy_object(cls, magic):
291         b0, b1 = map(ord, magic)
292         word = (b0 << 8) + b1
293         return b0 == 0x78 and (word % 31) == 0
294
295     @classmethod
296     def _parse_file_header(cls, f):
297         magic = f.read(2)
298         if cls._is_legacy_object(magic):
299             return cls._parse_legacy_object_header(magic, f)
300         else:
301             return cls._parse_object_header(magic, f)
302
303     def __init__(self):
304         """Don't call this directly"""
305         self._sha = None
306         self._path = None
307         self._file = None
308         self._magic = None
309         self._chunked_text = []
310         self._needs_parsing = False
311         self._needs_serialization = True
312
313     def _deserialize(self, chunks):
314         raise NotImplementedError(self._deserialize)
315
316     def _serialize(self):
317         raise NotImplementedError(self._serialize)
318
319     def _parse_path(self):
320         f = GitFile(self._path, 'rb')
321         try:
322             self._parse_file(f)
323         finally:
324             f.close()
325
326     def _parse_file(self, f):
327         magic = self._magic
328         if magic is None:
329             magic = f.read(2)
330         map = magic + f.read()
331         if self._is_legacy_object(magic[:2]):
332             self._parse_legacy_object(map)
333         else:
334             self._parse_object(map)
335
336     @classmethod
337     def from_path(cls, path):
338         f = GitFile(path, 'rb')
339         try:
340             obj = cls.from_file(f)
341             obj._path = path
342             obj._sha = FixedSha(filename_to_hex(path))
343             obj._file = None
344             obj._magic = None
345             return obj
346         finally:
347             f.close()
348
349     @classmethod
350     def from_file(cls, f):
351         """Get the contents of a SHA file on disk."""
352         try:
353             obj = cls._parse_file_header(f)
354             obj._sha = None
355             obj._needs_parsing = True
356             obj._needs_serialization = True
357             obj._file = f
358             return obj
359         except (IndexError, ValueError), e:
360             raise ObjectFormatException("invalid object header")
361
362     @staticmethod
363     def from_raw_string(type_num, string):
364         """Creates an object of the indicated type from the raw string given.
365
366         :param type_num: The numeric type of the object.
367         :param string: The raw uncompressed contents.
368         """
369         obj = object_class(type_num)()
370         obj.set_raw_string(string)
371         return obj
372
373     @staticmethod
374     def from_raw_chunks(type_num, chunks):
375         """Creates an object of the indicated type from the raw chunks given.
376
377         :param type_num: The numeric type of the object.
378         :param chunks: An iterable of the raw uncompressed contents.
379         """
380         obj = object_class(type_num)()
381         obj.set_raw_chunks(chunks)
382         return obj
383
384     @classmethod
385     def from_string(cls, string):
386         """Create a ShaFile from a string."""
387         obj = cls()
388         obj.set_raw_string(string)
389         return obj
390
391     def _check_has_member(self, member, error_msg):
392         """Check that the object has a given member variable.
393
394         :param member: the member variable to check for
395         :param error_msg: the message for an error if the member is missing
396         :raise ObjectFormatException: with the given error_msg if member is
397             missing or is None
398         """
399         if getattr(self, member, None) is None:
400             raise ObjectFormatException(error_msg)
401
402     def check(self):
403         """Check this object for internal consistency.
404
405         :raise ObjectFormatException: if the object is malformed in some way
406         :raise ChecksumMismatch: if the object was created with a SHA that does
407             not match its contents
408         """
409         # TODO: if we find that error-checking during object parsing is a
410         # performance bottleneck, those checks should be moved to the class's
411         # check() method during optimization so we can still check the object
412         # when necessary.
413         old_sha = self.id
414         try:
415             self._deserialize(self.as_raw_chunks())
416             self._sha = None
417             new_sha = self.id
418         except Exception, e:
419             raise ObjectFormatException(e)
420         if old_sha != new_sha:
421             raise ChecksumMismatch(new_sha, old_sha)
422
423     def _header(self):
424         return object_header(self.type, self.raw_length())
425
426     def raw_length(self):
427         """Returns the length of the raw string of this object."""
428         ret = 0
429         for chunk in self.as_raw_chunks():
430             ret += len(chunk)
431         return ret
432
433     def _make_sha(self):
434         ret = make_sha()
435         ret.update(self._header())
436         for chunk in self.as_raw_chunks():
437             ret.update(chunk)
438         return ret
439
440     def sha(self):
441         """The SHA1 object that is the name of this object."""
442         if self._sha is None or self._needs_serialization:
443             # this is a local because as_raw_chunks() overwrites self._sha
444             new_sha = make_sha()
445             new_sha.update(self._header())
446             for chunk in self.as_raw_chunks():
447                 new_sha.update(chunk)
448             self._sha = new_sha
449         return self._sha
450
451     @property
452     def id(self):
453         return self.sha().hexdigest()
454
455     def get_type(self):
456         return self.type_num
457
458     def set_type(self, type):
459         self.type_num = type
460
461     # DEPRECATED: use type_num or type_name as needed.
462     type = property(get_type, set_type)
463
464     def __repr__(self):
465         return "<%s %s>" % (self.__class__.__name__, self.id)
466
467     def __ne__(self, other):
468         return self.id != other.id
469
470     def __eq__(self, other):
471         """Return true if the sha of the two objects match.
472
473         The __le__ etc methods aren't overriden as they make no sense,
474         certainly at this level.
475         """
476         return self.id == other.id
477
478
479 class Blob(ShaFile):
480     """A Git Blob object."""
481
482     __slots__ = ()
483
484     type_name = 'blob'
485     type_num = 3
486
487     def __init__(self):
488         super(Blob, self).__init__()
489         self._chunked_text = []
490         self._needs_parsing = False
491         self._needs_serialization = False
492
493     def _get_data(self):
494         return self.as_raw_string()
495
496     def _set_data(self, data):
497         self.set_raw_string(data)
498
499     data = property(_get_data, _set_data,
500                     "The text contained within the blob object.")
501
502     def _get_chunked(self):
503         self._ensure_parsed()
504         return self._chunked_text
505
506     def _set_chunked(self, chunks):
507         self._chunked_text = chunks
508
509     def _serialize(self):
510         if not self._chunked_text:
511             self._ensure_parsed()
512         self._needs_serialization = False
513         return self._chunked_text
514
515     def _deserialize(self, chunks):
516         self._chunked_text = chunks
517
518     chunked = property(_get_chunked, _set_chunked,
519         "The text within the blob object, as chunks (not necessarily lines).")
520
521     @classmethod
522     def from_path(cls, path):
523         blob = ShaFile.from_path(path)
524         if not isinstance(blob, cls):
525             raise NotBlobError(path)
526         return blob
527
528     def check(self):
529         """Check this object for internal consistency.
530
531         :raise ObjectFormatException: if the object is malformed in some way
532         """
533         super(Blob, self).check()
534
535
536 def _parse_tag_or_commit(text):
537     """Parse tag or commit text.
538
539     :param text: the raw text of the tag or commit object.
540     :return: iterator of tuples of (field, value), one per header line, in the
541         order read from the text, possibly including duplicates. Includes a
542         field named None for the freeform tag/commit text.
543     """
544     f = StringIO(text)
545     for l in f:
546         l = l.rstrip("\n")
547         if l == "":
548             # Empty line indicates end of headers
549             break
550         yield l.split(" ", 1)
551     yield (None, f.read())
552     f.close()
553
554
555 def parse_tag(text):
556     return _parse_tag_or_commit(text)
557
558
559 class Tag(ShaFile):
560     """A Git Tag object."""
561
562     type_name = 'tag'
563     type_num = 4
564
565     __slots__ = ('_tag_timezone_neg_utc', '_name', '_object_sha', 
566                  '_object_class', '_tag_time', '_tag_timezone',
567                  '_tagger', '_message')
568
569     def __init__(self):
570         super(Tag, self).__init__()
571         self._tag_timezone_neg_utc = False
572
573     @classmethod
574     def from_path(cls, filename):
575         tag = ShaFile.from_path(filename)
576         if not isinstance(tag, cls):
577             raise NotTagError(filename)
578         return tag
579
580     def check(self):
581         """Check this object for internal consistency.
582
583         :raise ObjectFormatException: if the object is malformed in some way
584         """
585         super(Tag, self).check()
586         self._check_has_member("_object_sha", "missing object sha")
587         self._check_has_member("_object_class", "missing object type")
588         self._check_has_member("_name", "missing tag name")
589
590         if not self._name:
591             raise ObjectFormatException("empty tag name")
592
593         check_hexsha(self._object_sha, "invalid object sha")
594
595         if getattr(self, "_tagger", None):
596             check_identity(self._tagger, "invalid tagger")
597
598         last = None
599         for field, _ in parse_tag("".join(self._chunked_text)):
600             if field == _OBJECT_HEADER and last is not None:
601                 raise ObjectFormatException("unexpected object")
602             elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
603                 raise ObjectFormatException("unexpected type")
604             elif field == _TAG_HEADER and last != _TYPE_HEADER:
605                 raise ObjectFormatException("unexpected tag name")
606             elif field == _TAGGER_HEADER and last != _TAG_HEADER:
607                 raise ObjectFormatException("unexpected tagger")
608             last = field
609
610     def _serialize(self):
611         chunks = []
612         chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
613         chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
614         chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
615         if self._tagger:
616             if self._tag_time is None:
617                 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
618             else:
619                 chunks.append("%s %s %d %s\n" % (
620                   _TAGGER_HEADER, self._tagger, self._tag_time,
621                   format_timezone(self._tag_timezone,
622                     self._tag_timezone_neg_utc)))
623         chunks.append("\n") # To close headers
624         chunks.append(self._message)
625         return chunks
626
627     def _deserialize(self, chunks):
628         """Grab the metadata attached to the tag"""
629         self._tagger = None
630         for field, value in parse_tag("".join(chunks)):
631             if field == _OBJECT_HEADER:
632                 self._object_sha = value
633             elif field == _TYPE_HEADER:
634                 obj_class = object_class(value)
635                 if not obj_class:
636                     raise ObjectFormatException("Not a known type: %s" % value)
637                 self._object_class = obj_class
638             elif field == _TAG_HEADER:
639                 self._name = value
640             elif field == _TAGGER_HEADER:
641                 try:
642                     sep = value.index("> ")
643                 except ValueError:
644                     self._tagger = value
645                     self._tag_time = None
646                     self._tag_timezone = None
647                     self._tag_timezone_neg_utc = False
648                 else:
649                     self._tagger = value[0:sep+1]
650                     try:
651                         (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
652                         self._tag_time = int(timetext)
653                         self._tag_timezone, self._tag_timezone_neg_utc = \
654                                 parse_timezone(timezonetext)
655                     except ValueError, e:
656                         raise ObjectFormatException(e)
657             elif field is None:
658                 self._message = value
659             else:
660                 raise ObjectFormatException("Unknown field %s" % field)
661
662     def _get_object(self):
663         """Get the object pointed to by this tag.
664
665         :return: tuple of (object class, sha).
666         """
667         self._ensure_parsed()
668         return (self._object_class, self._object_sha)
669
670     def _set_object(self, value):
671         self._ensure_parsed()
672         (self._object_class, self._object_sha) = value
673         self._needs_serialization = True
674
675     object = property(_get_object, _set_object)
676
677     name = serializable_property("name", "The name of this tag")
678     tagger = serializable_property("tagger",
679         "Returns the name of the person who created this tag")
680     tag_time = serializable_property("tag_time",
681         "The creation timestamp of the tag.  As the number of seconds since the epoch")
682     tag_timezone = serializable_property("tag_timezone",
683         "The timezone that tag_time is in.")
684     message = serializable_property("message", "The message attached to this tag")
685
686
687 def parse_tree(text):
688     """Parse a tree text.
689
690     :param text: Serialized text to parse
691     :return: iterator of tuples of (name, mode, sha)
692     """
693     count = 0
694     l = len(text)
695     while count < l:
696         mode_end = text.index(' ', count)
697         mode_text = text[count:mode_end]
698         assert mode_text[0] != '0'
699         try:
700             mode = int(mode_text, 8)
701         except ValueError:
702             raise ObjectFormatException("Invalid mode '%s'" % mode_text)
703         name_end = text.index('\0', mode_end)
704         name = text[mode_end+1:name_end]
705         count = name_end+21
706         sha = text[name_end+1:count]
707         if len(sha) != 20:
708             raise ObjectFormatException("Sha has invalid length")
709         hexsha = sha_to_hex(sha)
710         yield (name, mode, hexsha)
711
712
713 def serialize_tree(items):
714     """Serialize the items in a tree to a text.
715
716     :param items: Sorted iterable over (name, mode, sha) tuples
717     :return: Serialized tree text as chunks
718     """
719     for name, mode, hexsha in items:
720         yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
721
722
723 def sorted_tree_items(entries):
724     """Iterate over a tree entries dictionary in the order in which 
725     the items would be serialized.
726
727     :param entries: Dictionary mapping names to (mode, sha) tuples
728     :return: Iterator over (name, mode, hexsha)
729     """
730     for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
731         mode, hexsha = entry
732         # Stricter type checks than normal to mirror checks in the C version.
733         mode = int(mode)
734         if not isinstance(hexsha, str):
735             raise TypeError('Expected a string for SHA, got %r' % hexsha)
736         yield name, mode, hexsha
737
738
739 def cmp_entry((name1, value1), (name2, value2)):
740     """Compare two tree entries."""
741     if stat.S_ISDIR(value1[0]):
742         name1 += "/"
743     if stat.S_ISDIR(value2[0]):
744         name2 += "/"
745     return cmp(name1, name2)
746
747
748 class Tree(ShaFile):
749     """A Git tree object"""
750
751     type_name = 'tree'
752     type_num = 2
753
754     __slots__ = ('_entries')
755
756     def __init__(self):
757         super(Tree, self).__init__()
758         self._entries = {}
759
760     @classmethod
761     def from_path(cls, filename):
762         tree = ShaFile.from_path(filename)
763         if not isinstance(tree, cls):
764             raise NotTreeError(filename)
765         return tree
766
767     def __contains__(self, name):
768         self._ensure_parsed()
769         return name in self._entries
770
771     def __getitem__(self, name):
772         self._ensure_parsed()
773         return self._entries[name]
774
775     def __setitem__(self, name, value):
776         """Set a tree entry by name.
777
778         :param name: The name of the entry, as a string.
779         :param value: A tuple of (mode, hexsha), where mode is the mode of the
780             entry as an integral type and hexsha is the hex SHA of the entry as
781             a string.
782         """
783         mode, hexsha = value
784         self._ensure_parsed()
785         self._entries[name] = (mode, hexsha)
786         self._needs_serialization = True
787
788     def __delitem__(self, name):
789         self._ensure_parsed()
790         del self._entries[name]
791         self._needs_serialization = True
792
793     def __len__(self):
794         self._ensure_parsed()
795         return len(self._entries)
796
797     def __iter__(self):
798         self._ensure_parsed()
799         return iter(self._entries)
800
801     def add(self, mode, name, hexsha):
802         """Add an entry to the tree.
803
804         :param mode: The mode of the entry as an integral type. Not all possible
805             modes are supported by git; see check() for details.
806         :param name: The name of the entry, as a string.
807         :param hexsha: The hex SHA of the entry as a string.
808         """
809         self._ensure_parsed()
810         self._entries[name] = mode, hexsha
811         self._needs_serialization = True
812
813     def entries(self):
814         """Return a list of tuples describing the tree entries"""
815         self._ensure_parsed()
816         # The order of this is different from iteritems() for historical
817         # reasons
818         return [
819             (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
820
821     def iteritems(self):
822         """Iterate over entries in the order in which they would be serialized.
823
824         :return: Iterator over (name, mode, sha) tuples
825         """
826         self._ensure_parsed()
827         return sorted_tree_items(self._entries)
828
829     def _deserialize(self, chunks):
830         """Grab the entries in the tree"""
831         try:
832             parsed_entries = parse_tree("".join(chunks))
833         except ValueError, e:
834             raise ObjectFormatException(e)
835         # TODO: list comprehension is for efficiency in the common (small) case;
836         # if memory efficiency in the large case is a concern, use a genexp.
837         self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
838
839     def check(self):
840         """Check this object for internal consistency.
841
842         :raise ObjectFormatException: if the object is malformed in some way
843         """
844         super(Tree, self).check()
845         last = None
846         allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
847                          stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
848                          # TODO: optionally exclude as in git fsck --strict
849                          stat.S_IFREG | 0664)
850         for name, mode, sha in parse_tree("".join(self._chunked_text)):
851             check_hexsha(sha, 'invalid sha %s' % sha)
852             if '/' in name or name in ('', '.', '..'):
853                 raise ObjectFormatException('invalid name %s' % name)
854
855             if mode not in allowed_modes:
856                 raise ObjectFormatException('invalid mode %06o' % mode)
857
858             entry = (name, (mode, sha))
859             if last:
860                 if cmp_entry(last, entry) > 0:
861                     raise ObjectFormatException('entries not sorted')
862                 if name == last[0]:
863                     raise ObjectFormatException('duplicate entry %s' % name)
864             last = entry
865
866     def _serialize(self):
867         return list(serialize_tree(self.iteritems()))
868
869     def as_pretty_string(self):
870         text = []
871         for name, mode, hexsha in self.iteritems():
872             if mode & stat.S_IFDIR:
873                 kind = "tree"
874             else:
875                 kind = "blob"
876             text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
877         return "".join(text)
878
879
880 def parse_timezone(text):
881     """Parse a timezone text fragment (e.g. '+0100').
882
883     :param text: Text to parse.
884     :return: Tuple with timezone as seconds difference to UTC 
885         and a boolean indicating whether this was a UTC timezone
886         prefixed with a negative sign (-0000).
887     """
888     offset = int(text)
889     negative_utc = (offset == 0 and text[0] == '-')
890     signum = (offset < 0) and -1 or 1
891     offset = abs(offset)
892     hours = int(offset / 100)
893     minutes = (offset % 100)
894     return signum * (hours * 3600 + minutes * 60), negative_utc
895
896
897 def format_timezone(offset, negative_utc=False):
898     """Format a timezone for Git serialization.
899
900     :param offset: Timezone offset as seconds difference to UTC
901     :param negative_utc: Whether to use a minus sign for UTC
902         (-0000 rather than +0000).
903     """
904     if offset % 60 != 0:
905         raise ValueError("Unable to handle non-minute offset.")
906     if offset < 0 or (offset == 0 and negative_utc):
907         sign = '-'
908     else:
909         sign = '+'
910     offset = abs(offset)
911     return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
912
913
914 def parse_commit(text):
915     return _parse_tag_or_commit(text)
916
917
918 class Commit(ShaFile):
919     """A git commit object"""
920
921     type_name = 'commit'
922     type_num = 1
923
924     __slots__ = ('_parents', '_encoding', '_extra', '_author_timezone_neg_utc',
925                  '_commit_timezone_neg_utc', '_commit_time',
926                  '_author_time', '_author_timezone', '_commit_timezone',
927                  '_author', '_committer', '_parents', '_extra',
928                  '_encoding', '_tree', '_message')
929
930     def __init__(self):
931         super(Commit, self).__init__()
932         self._parents = []
933         self._encoding = None
934         self._extra = {}
935         self._author_timezone_neg_utc = False
936         self._commit_timezone_neg_utc = False
937
938     @classmethod
939     def from_path(cls, path):
940         commit = ShaFile.from_path(path)
941         if not isinstance(commit, cls):
942             raise NotCommitError(path)
943         return commit
944
945     def _deserialize(self, chunks):
946         self._parents = []
947         self._extra = []
948         self._author = None
949         for field, value in parse_commit("".join(self._chunked_text)):
950             if field == _TREE_HEADER:
951                 self._tree = value
952             elif field == _PARENT_HEADER:
953                 self._parents.append(value)
954             elif field == _AUTHOR_HEADER:
955                 self._author, timetext, timezonetext = value.rsplit(" ", 2)
956                 self._author_time = int(timetext)
957                 self._author_timezone, self._author_timezone_neg_utc =\
958                     parse_timezone(timezonetext)
959             elif field == _COMMITTER_HEADER:
960                 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
961                 self._commit_time = int(timetext)
962                 self._commit_timezone, self._commit_timezone_neg_utc =\
963                     parse_timezone(timezonetext)
964             elif field == _ENCODING_HEADER:
965                 self._encoding = value
966             elif field is None:
967                 self._message = value
968             else:
969                 self._extra.append((field, value))
970
971     def check(self):
972         """Check this object for internal consistency.
973
974         :raise ObjectFormatException: if the object is malformed in some way
975         """
976         super(Commit, self).check()
977         self._check_has_member("_tree", "missing tree")
978         self._check_has_member("_author", "missing author")
979         self._check_has_member("_committer", "missing committer")
980         # times are currently checked when set
981
982         for parent in self._parents:
983             check_hexsha(parent, "invalid parent sha")
984         check_hexsha(self._tree, "invalid tree sha")
985
986         check_identity(self._author, "invalid author")
987         check_identity(self._committer, "invalid committer")
988
989         last = None
990         for field, _ in parse_commit("".join(self._chunked_text)):
991             if field == _TREE_HEADER and last is not None:
992                 raise ObjectFormatException("unexpected tree")
993             elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
994                                                           _TREE_HEADER):
995                 raise ObjectFormatException("unexpected parent")
996             elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
997                                                           _PARENT_HEADER):
998                 raise ObjectFormatException("unexpected author")
999             elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
1000                 raise ObjectFormatException("unexpected committer")
1001             elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
1002                 raise ObjectFormatException("unexpected encoding")
1003             last = field
1004
1005         # TODO: optionally check for duplicate parents
1006
1007     def _serialize(self):
1008         chunks = []
1009         chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
1010         for p in self._parents:
1011             chunks.append("%s %s\n" % (_PARENT_HEADER, p))
1012         chunks.append("%s %s %s %s\n" % (
1013           _AUTHOR_HEADER, self._author, str(self._author_time),
1014           format_timezone(self._author_timezone,
1015                           self._author_timezone_neg_utc)))
1016         chunks.append("%s %s %s %s\n" % (
1017           _COMMITTER_HEADER, self._committer, str(self._commit_time),
1018           format_timezone(self._commit_timezone,
1019                           self._commit_timezone_neg_utc)))
1020         if self.encoding:
1021             chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
1022         for k, v in self.extra:
1023             if "\n" in k or "\n" in v:
1024                 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
1025             chunks.append("%s %s\n" % (k, v))
1026         chunks.append("\n") # There must be a new line after the headers
1027         chunks.append(self._message)
1028         return chunks
1029
1030     tree = serializable_property("tree", "Tree that is the state of this commit")
1031
1032     def _get_parents(self):
1033         """Return a list of parents of this commit."""
1034         self._ensure_parsed()
1035         return self._parents
1036
1037     def _set_parents(self, value):
1038         """Set a list of parents of this commit."""
1039         self._ensure_parsed()
1040         self._needs_serialization = True
1041         self._parents = value
1042
1043     parents = property(_get_parents, _set_parents)
1044
1045     def _get_extra(self):
1046         """Return extra settings of this commit."""
1047         self._ensure_parsed()
1048         return self._extra
1049
1050     extra = property(_get_extra)
1051
1052     author = serializable_property("author",
1053         "The name of the author of the commit")
1054
1055     committer = serializable_property("committer",
1056         "The name of the committer of the commit")
1057
1058     message = serializable_property("message",
1059         "The commit message")
1060
1061     commit_time = serializable_property("commit_time",
1062         "The timestamp of the commit. As the number of seconds since the epoch.")
1063
1064     commit_timezone = serializable_property("commit_timezone",
1065         "The zone the commit time is in")
1066
1067     author_time = serializable_property("author_time",
1068         "The timestamp the commit was written. as the number of seconds since the epoch.")
1069
1070     author_timezone = serializable_property("author_timezone",
1071         "Returns the zone the author time is in.")
1072
1073     encoding = serializable_property("encoding",
1074         "Encoding of the commit message.")
1075
1076
1077 OBJECT_CLASSES = (
1078     Commit,
1079     Tree,
1080     Blob,
1081     Tag,
1082     )
1083
1084 _TYPE_MAP = {}
1085
1086 for cls in OBJECT_CLASSES:
1087     _TYPE_MAP[cls.type_name] = cls
1088     _TYPE_MAP[cls.type_num] = cls
1089
1090
1091
1092 # Hold on to the pure-python implementations for testing
1093 _parse_tree_py = parse_tree
1094 _sorted_tree_items_py = sorted_tree_items
1095 try:
1096     # Try to import C versions
1097     from dulwich._objects import parse_tree, sorted_tree_items
1098 except ImportError:
1099     pass