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>
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.
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.
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,
21 """Access to base git objects."""
25 from cStringIO import (
33 from dulwich.errors import (
39 ObjectFormatException,
41 from dulwich.file import GitFile
42 from dulwich.misc import (
47 # Header fields for commits
49 _PARENT_HEADER = "parent"
50 _AUTHOR_HEADER = "author"
51 _COMMITTER_HEADER = "committer"
52 _ENCODING_HEADER = "encoding"
55 # Header fields for objects
56 _OBJECT_HEADER = "object"
59 _TAGGER_HEADER = "tagger"
65 return (stat.S_IFMT(m) == S_IFGITLINK)
68 def _decompress(string):
69 dcomp = zlib.decompressobj()
70 dcomped = dcomp.decompress(string)
71 dcomped += dcomp.flush()
76 """Takes a string and returns the hex of the sha within"""
77 hexsha = binascii.hexlify(sha)
78 assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
83 """Takes a hex sha and returns a binary sha"""
84 assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
85 return binascii.unhexlify(hex)
88 def hex_to_filename(path, hex):
89 """Takes a hex sha and returns its filename relative to the given path."""
92 # Check from object dir
93 return os.path.join(path, dir, file)
96 def filename_to_hex(filename):
97 """Takes an object filename and returns its corresponding hex sha."""
98 # grab the last (up to) two path components
99 names = filename.rsplit(os.path.sep, 2)[-2:]
100 errmsg = "Invalid object filename: %s" % filename
101 assert len(names) == 2, errmsg
103 assert len(base) == 2 and len(rest) == 38, errmsg
109 def object_header(num_type, length):
110 """Return an object header for the given numeric type and text length."""
111 return "%s %d\0" % (object_class(num_type).type_name, length)
114 def serializable_property(name, docstring=None):
117 setattr(obj, "_"+name, value)
118 obj._needs_serialization = True
121 return getattr(obj, "_"+name)
122 return property(get, set, doc=docstring)
125 def object_class(type):
126 """Get the object class corresponding to the given type.
128 :param type: Either a type name string or a numeric type.
129 :return: The ShaFile subclass corresponding to the given type, or None if
130 type is not a valid type name/number.
132 return _TYPE_MAP.get(type, None)
135 def check_hexsha(hex, error_msg):
138 except (TypeError, AssertionError):
139 raise ObjectFormatException("%s %s" % (error_msg, hex))
142 def check_identity(identity, error_msg):
143 """Check if the specified identity is valid.
145 This will raise an exception if the identity is not valid.
147 :param identity: Identity string
148 :param error_msg: Error message to use in exception
150 email_start = identity.find("<")
151 email_end = identity.find(">")
152 if (email_start < 0 or email_end < 0 or email_end <= email_start
153 or identity.find("<", email_start + 1) >= 0
154 or identity.find(">", email_end + 1) >= 0
155 or not identity.endswith(">")):
156 raise ObjectFormatException(error_msg)
159 class FixedSha(object):
160 """SHA object that behaves like hashlib's but is given a fixed value."""
162 def __init__(self, hexsha):
163 self._hexsha = hexsha
164 self._sha = hex_to_sha(hexsha)
173 class ShaFile(object):
174 """A git SHA file."""
177 def _parse_legacy_object_header(magic, f):
178 """Parse a legacy object, creating it but not reading the file."""
180 decomp = zlib.decompressobj()
181 header = decomp.decompress(magic)
185 header += decomp.decompress(f.read(bufsize))
186 end = header.find("\0", start)
188 header = header[:end]
189 type_name, size = header.split(" ", 1)
190 size = int(size) # sanity check
191 obj_class = object_class(type_name)
193 raise ObjectFormatException("Not a known type: %s" % type_name)
196 def _parse_legacy_object(self, f):
197 """Parse a legacy object, setting the raw string."""
198 size = os.path.getsize(f.name)
199 map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
201 text = _decompress(map)
204 header_end = text.find('\0')
206 raise ObjectFormatException("Invalid object header")
207 self.set_raw_string(text[header_end+1:])
209 def as_legacy_object_chunks(self):
210 compobj = zlib.compressobj()
211 yield compobj.compress(self._header())
212 for chunk in self.as_raw_chunks():
213 yield compobj.compress(chunk)
214 yield compobj.flush()
216 def as_legacy_object(self):
217 return "".join(self.as_legacy_object_chunks())
219 def as_raw_chunks(self):
220 if self._needs_parsing:
221 self._ensure_parsed()
222 elif self._needs_serialization:
223 self._chunked_text = self._serialize()
224 return self._chunked_text
226 def as_raw_string(self):
227 return "".join(self.as_raw_chunks())
230 return self.as_raw_string()
235 def as_pretty_string(self):
236 return self.as_raw_string()
238 def _ensure_parsed(self):
239 if self._needs_parsing:
240 if not self._chunked_text:
241 if self._file is not None:
242 self._parse_file(self._file)
243 elif self._path is not None:
246 raise AssertionError(
247 "ShaFile needs either text or filename")
248 self._deserialize(self._chunked_text)
249 self._needs_parsing = False
251 def set_raw_string(self, text):
252 if type(text) != str:
253 raise TypeError(text)
254 self.set_raw_chunks([text])
256 def set_raw_chunks(self, chunks):
257 self._chunked_text = chunks
258 self._deserialize(chunks)
260 self._needs_parsing = False
261 self._needs_serialization = False
264 def _parse_object_header(magic, f):
265 """Parse a new style object, creating it but not reading the file."""
266 num_type = (ord(magic[0]) >> 4) & 7
267 obj_class = object_class(num_type)
269 raise ObjectFormatException("Not a known type: %d" % num_type)
272 def _parse_object(self, f):
273 """Parse a new style object, setting self._text."""
274 size = os.path.getsize(f.name)
275 map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
277 # skip type and size; type must have already been determined, and
278 # we trust zlib to fail if it's otherwise corrupted
281 while (byte & 0x80) != 0:
282 byte = ord(map[used])
285 self.set_raw_string(_decompress(raw))
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
296 def _parse_file_header(cls, f):
298 if cls._is_legacy_object(magic):
299 return cls._parse_legacy_object_header(magic, f)
301 return cls._parse_object_header(magic, f)
304 """Don't call this directly"""
308 self._chunked_text = []
309 self._needs_parsing = False
310 self._needs_serialization = True
312 def _deserialize(self, chunks):
313 raise NotImplementedError(self._deserialize)
315 def _serialize(self):
316 raise NotImplementedError(self._serialize)
318 def _parse_path(self):
319 f = GitFile(self._path, 'rb')
325 def _parse_file(self, f):
327 if self._is_legacy_object(magic):
328 self._parse_legacy_object(f)
330 self._parse_object(f)
333 def from_path(cls, path):
334 f = GitFile(path, 'rb')
336 obj = cls.from_file(f)
338 obj._sha = FixedSha(filename_to_hex(path))
345 def from_file(cls, f):
346 """Get the contents of a SHA file on disk."""
348 obj = cls._parse_file_header(f)
350 obj._needs_parsing = True
351 obj._needs_serialization = True
354 except (IndexError, ValueError), e:
355 raise ObjectFormatException("invalid object header")
358 def from_raw_string(type_num, string):
359 """Creates an object of the indicated type from the raw string given.
361 :param type_num: The numeric type of the object.
362 :param string: The raw uncompressed contents.
364 obj = object_class(type_num)()
365 obj.set_raw_string(string)
369 def from_raw_chunks(type_num, chunks):
370 """Creates an object of the indicated type from the raw chunks given.
372 :param type_num: The numeric type of the object.
373 :param chunks: An iterable of the raw uncompressed contents.
375 obj = object_class(type_num)()
376 obj.set_raw_chunks(chunks)
380 def from_string(cls, string):
381 """Create a ShaFile from a string."""
383 obj.set_raw_string(string)
386 def _check_has_member(self, member, error_msg):
387 """Check that the object has a given member variable.
389 :param member: the member variable to check for
390 :param error_msg: the message for an error if the member is missing
391 :raise ObjectFormatException: with the given error_msg if member is
394 if getattr(self, member, None) is None:
395 raise ObjectFormatException(error_msg)
398 """Check this object for internal consistency.
400 :raise ObjectFormatException: if the object is malformed in some way
401 :raise ChecksumMismatch: if the object was created with a SHA that does
402 not match its contents
404 # TODO: if we find that error-checking during object parsing is a
405 # performance bottleneck, those checks should be moved to the class's
406 # check() method during optimization so we can still check the object
410 self._deserialize(self.as_raw_chunks())
414 raise ObjectFormatException(e)
415 if old_sha != new_sha:
416 raise ChecksumMismatch(new_sha, old_sha)
419 return object_header(self.type, self.raw_length())
421 def raw_length(self):
422 """Returns the length of the raw string of this object."""
424 for chunk in self.as_raw_chunks():
430 ret.update(self._header())
431 for chunk in self.as_raw_chunks():
436 """The SHA1 object that is the name of this object."""
437 if self._sha is None or self._needs_serialization:
438 # this is a local because as_raw_chunks() overwrites self._sha
440 new_sha.update(self._header())
441 for chunk in self.as_raw_chunks():
442 new_sha.update(chunk)
448 return self.sha().hexdigest()
453 def set_type(self, type):
456 # DEPRECATED: use type_num or type_name as needed.
457 type = property(get_type, set_type)
460 return "<%s %s>" % (self.__class__.__name__, self.id)
462 def __ne__(self, other):
463 return self.id != other.id
465 def __eq__(self, other):
466 """Return true if the sha of the two objects match.
468 The __le__ etc methods aren't overriden as they make no sense,
469 certainly at this level.
471 return self.id == other.id
475 """A Git Blob object."""
481 super(Blob, self).__init__()
482 self._chunked_text = []
483 self._needs_parsing = False
484 self._needs_serialization = False
487 return self.as_raw_string()
489 def _set_data(self, data):
490 self.set_raw_string(data)
492 data = property(_get_data, _set_data,
493 "The text contained within the blob object.")
495 def _get_chunked(self):
496 self._ensure_parsed()
497 return self._chunked_text
499 def _set_chunked(self, chunks):
500 self._chunked_text = chunks
502 def _serialize(self):
503 if not self._chunked_text:
504 self._ensure_parsed()
505 self._needs_serialization = False
506 return self._chunked_text
508 def _deserialize(self, chunks):
509 self._chunked_text = chunks
511 chunked = property(_get_chunked, _set_chunked,
512 "The text within the blob object, as chunks (not necessarily lines).")
515 def from_path(cls, path):
516 blob = ShaFile.from_path(path)
517 if not isinstance(blob, cls):
518 raise NotBlobError(path)
522 """Check this object for internal consistency.
524 :raise ObjectFormatException: if the object is malformed in some way
526 super(Blob, self).check()
529 def _parse_tag_or_commit(text):
530 """Parse tag or commit text.
532 :param text: the raw text of the tag or commit object.
533 :yield: tuples of (field, value), one per header line, in the order read
534 from the text, possibly including duplicates. Includes a field named
535 None for the freeform tag/commit text.
541 # Empty line indicates end of headers
543 yield l.split(" ", 1)
544 yield (None, f.read())
549 return _parse_tag_or_commit(text)
553 """A Git Tag object."""
559 super(Tag, self).__init__()
560 self._tag_timezone_neg_utc = False
563 def from_path(cls, filename):
564 tag = ShaFile.from_path(filename)
565 if not isinstance(tag, cls):
566 raise NotTagError(filename)
570 """Check this object for internal consistency.
572 :raise ObjectFormatException: if the object is malformed in some way
574 super(Tag, self).check()
575 self._check_has_member("_object_sha", "missing object sha")
576 self._check_has_member("_object_class", "missing object type")
577 self._check_has_member("_name", "missing tag name")
580 raise ObjectFormatException("empty tag name")
582 check_hexsha(self._object_sha, "invalid object sha")
584 if getattr(self, "_tagger", None):
585 check_identity(self._tagger, "invalid tagger")
588 for field, _ in parse_tag("".join(self._chunked_text)):
589 if field == _OBJECT_HEADER and last is not None:
590 raise ObjectFormatException("unexpected object")
591 elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
592 raise ObjectFormatException("unexpected type")
593 elif field == _TAG_HEADER and last != _TYPE_HEADER:
594 raise ObjectFormatException("unexpected tag name")
595 elif field == _TAGGER_HEADER and last != _TAG_HEADER:
596 raise ObjectFormatException("unexpected tagger")
599 def _serialize(self):
601 chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
602 chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
603 chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
605 if self._tag_time is None:
606 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
608 chunks.append("%s %s %d %s\n" % (
609 _TAGGER_HEADER, self._tagger, self._tag_time,
610 format_timezone(self._tag_timezone,
611 self._tag_timezone_neg_utc)))
612 chunks.append("\n") # To close headers
613 chunks.append(self._message)
616 def _deserialize(self, chunks):
617 """Grab the metadata attached to the tag"""
619 for field, value in parse_tag("".join(chunks)):
620 if field == _OBJECT_HEADER:
621 self._object_sha = value
622 elif field == _TYPE_HEADER:
623 obj_class = object_class(value)
625 raise ObjectFormatException("Not a known type: %s" % value)
626 self._object_class = obj_class
627 elif field == _TAG_HEADER:
629 elif field == _TAGGER_HEADER:
631 sep = value.index("> ")
634 self._tag_time = None
635 self._tag_timezone = None
636 self._tag_timezone_neg_utc = False
638 self._tagger = value[0:sep+1]
640 (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
641 self._tag_time = int(timetext)
642 self._tag_timezone, self._tag_timezone_neg_utc = \
643 parse_timezone(timezonetext)
644 except ValueError, e:
645 raise ObjectFormatException(e)
647 self._message = value
649 raise ObjectFormatException("Unknown field %s" % field)
651 def _get_object(self):
652 """Get the object pointed to by this tag.
654 :return: tuple of (object class, sha).
656 self._ensure_parsed()
657 return (self._object_class, self._object_sha)
659 def _set_object(self, value):
660 self._ensure_parsed()
661 (self._object_class, self._object_sha) = value
662 self._needs_serialization = True
664 object = property(_get_object, _set_object)
666 name = serializable_property("name", "The name of this tag")
667 tagger = serializable_property("tagger",
668 "Returns the name of the person who created this tag")
669 tag_time = serializable_property("tag_time",
670 "The creation timestamp of the tag. As the number of seconds since the epoch")
671 tag_timezone = serializable_property("tag_timezone",
672 "The timezone that tag_time is in.")
673 message = serializable_property("message", "The message attached to this tag")
676 def parse_tree(text):
677 """Parse a tree text.
679 :param text: Serialized text to parse
680 :yields: tuples of (name, mode, sha)
685 mode_end = text.index(' ', count)
686 mode = int(text[count:mode_end], 8)
687 name_end = text.index('\0', mode_end)
688 name = text[mode_end+1:name_end]
690 sha = text[name_end+1:count]
691 yield (name, mode, sha_to_hex(sha))
694 def serialize_tree(items):
695 """Serialize the items in a tree to a text.
697 :param items: Sorted iterable over (name, mode, sha) tuples
698 :return: Serialized tree text as chunks
700 for name, mode, hexsha in items:
701 yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
704 def sorted_tree_items(entries):
705 """Iterate over a tree entries dictionary in the order in which
706 the items would be serialized.
708 :param entries: Dictionary mapping names to (mode, sha) tuples
709 :return: Iterator over (name, mode, sha)
711 for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
712 yield name, entry[0], entry[1]
715 def cmp_entry((name1, value1), (name2, value2)):
716 """Compare two tree entries."""
717 if stat.S_ISDIR(value1[0]):
719 if stat.S_ISDIR(value2[0]):
721 return cmp(name1, name2)
725 """A Git tree object"""
731 super(Tree, self).__init__()
735 def from_path(cls, filename):
736 tree = ShaFile.from_path(filename)
737 if not isinstance(tree, cls):
738 raise NotTreeError(filename)
741 def __contains__(self, name):
742 self._ensure_parsed()
743 return name in self._entries
745 def __getitem__(self, name):
746 self._ensure_parsed()
747 return self._entries[name]
749 def __setitem__(self, name, value):
750 """Set a tree entry by name.
752 :param name: The name of the entry, as a string.
753 :param value: A tuple of (mode, hexsha), where mode is the mode of the
754 entry as an integral type and hexsha is the hex SHA of the entry as
758 self._ensure_parsed()
759 self._entries[name] = (mode, hexsha)
760 self._needs_serialization = True
762 def __delitem__(self, name):
763 self._ensure_parsed()
764 del self._entries[name]
765 self._needs_serialization = True
768 self._ensure_parsed()
769 return len(self._entries)
772 self._ensure_parsed()
773 return iter(self._entries)
775 def add(self, mode, name, hexsha):
776 """Add an entry to the tree.
778 :param mode: The mode of the entry as an integral type. Not all possible
779 modes are supported by git; see check() for details.
780 :param name: The name of the entry, as a string.
781 :param hexsha: The hex SHA of the entry as a string.
783 self._ensure_parsed()
784 self._entries[name] = mode, hexsha
785 self._needs_serialization = True
788 """Return a list of tuples describing the tree entries"""
789 self._ensure_parsed()
790 # The order of this is different from iteritems() for historical
793 (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
796 """Iterate over entries in the order in which they would be serialized.
798 :return: Iterator over (name, mode, sha) tuples
800 self._ensure_parsed()
801 return sorted_tree_items(self._entries)
803 def _deserialize(self, chunks):
804 """Grab the entries in the tree"""
806 parsed_entries = parse_tree("".join(chunks))
807 except ValueError, e:
808 raise ObjectFormatException(e)
809 # TODO: list comprehension is for efficiency in the common (small) case;
810 # if memory efficiency in the large case is a concern, use a genexp.
811 self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
814 """Check this object for internal consistency.
816 :raise ObjectFormatException: if the object is malformed in some way
818 super(Tree, self).check()
820 allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
821 stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
822 # TODO: optionally exclude as in git fsck --strict
824 for name, mode, sha in parse_tree("".join(self._chunked_text)):
825 check_hexsha(sha, 'invalid sha %s' % sha)
826 if '/' in name or name in ('', '.', '..'):
827 raise ObjectFormatException('invalid name %s' % name)
829 if mode not in allowed_modes:
830 raise ObjectFormatException('invalid mode %06o' % mode)
832 entry = (name, (mode, sha))
834 if cmp_entry(last, entry) > 0:
835 raise ObjectFormatException('entries not sorted')
837 raise ObjectFormatException('duplicate entry %s' % name)
840 def _serialize(self):
841 return list(serialize_tree(self.iteritems()))
843 def as_pretty_string(self):
845 for name, mode, hexsha in self.iteritems():
846 if mode & stat.S_IFDIR:
850 text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
854 def parse_timezone(text):
856 negative_utc = (offset == 0 and text[0] == '-')
857 signum = (offset < 0) and -1 or 1
859 hours = int(offset / 100)
860 minutes = (offset % 100)
861 return signum * (hours * 3600 + minutes * 60), negative_utc
864 def format_timezone(offset, negative_utc=False):
866 raise ValueError("Unable to handle non-minute offset.")
867 if offset < 0 or (offset == 0 and negative_utc):
872 return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
875 def parse_commit(text):
876 return _parse_tag_or_commit(text)
879 class Commit(ShaFile):
880 """A git commit object"""
886 super(Commit, self).__init__()
888 self._encoding = None
890 self._author_timezone_neg_utc = False
891 self._commit_timezone_neg_utc = False
894 def from_path(cls, path):
895 commit = ShaFile.from_path(path)
896 if not isinstance(commit, cls):
897 raise NotCommitError(path)
900 def _deserialize(self, chunks):
904 for field, value in parse_commit("".join(self._chunked_text)):
905 if field == _TREE_HEADER:
907 elif field == _PARENT_HEADER:
908 self._parents.append(value)
909 elif field == _AUTHOR_HEADER:
910 self._author, timetext, timezonetext = value.rsplit(" ", 2)
911 self._author_time = int(timetext)
912 self._author_timezone, self._author_timezone_neg_utc =\
913 parse_timezone(timezonetext)
914 elif field == _COMMITTER_HEADER:
915 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
916 self._commit_time = int(timetext)
917 self._commit_timezone, self._commit_timezone_neg_utc =\
918 parse_timezone(timezonetext)
919 elif field == _ENCODING_HEADER:
920 self._encoding = value
922 self._message = value
924 self._extra.append((field, value))
927 """Check this object for internal consistency.
929 :raise ObjectFormatException: if the object is malformed in some way
931 super(Commit, self).check()
932 self._check_has_member("_tree", "missing tree")
933 self._check_has_member("_author", "missing author")
934 self._check_has_member("_committer", "missing committer")
935 # times are currently checked when set
937 for parent in self._parents:
938 check_hexsha(parent, "invalid parent sha")
939 check_hexsha(self._tree, "invalid tree sha")
941 check_identity(self._author, "invalid author")
942 check_identity(self._committer, "invalid committer")
945 for field, _ in parse_commit("".join(self._chunked_text)):
946 if field == _TREE_HEADER and last is not None:
947 raise ObjectFormatException("unexpected tree")
948 elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
950 raise ObjectFormatException("unexpected parent")
951 elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
953 raise ObjectFormatException("unexpected author")
954 elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
955 raise ObjectFormatException("unexpected committer")
956 elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
957 raise ObjectFormatException("unexpected encoding")
960 # TODO: optionally check for duplicate parents
962 def _serialize(self):
964 chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
965 for p in self._parents:
966 chunks.append("%s %s\n" % (_PARENT_HEADER, p))
967 chunks.append("%s %s %s %s\n" % (
968 _AUTHOR_HEADER, self._author, str(self._author_time),
969 format_timezone(self._author_timezone,
970 self._author_timezone_neg_utc)))
971 chunks.append("%s %s %s %s\n" % (
972 _COMMITTER_HEADER, self._committer, str(self._commit_time),
973 format_timezone(self._commit_timezone,
974 self._commit_timezone_neg_utc)))
976 chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
977 for k, v in self.extra:
978 if "\n" in k or "\n" in v:
979 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
980 chunks.append("%s %s\n" % (k, v))
981 chunks.append("\n") # There must be a new line after the headers
982 chunks.append(self._message)
985 tree = serializable_property("tree", "Tree that is the state of this commit")
987 def _get_parents(self):
988 """Return a list of parents of this commit."""
989 self._ensure_parsed()
992 def _set_parents(self, value):
993 """Set a list of parents of this commit."""
994 self._ensure_parsed()
995 self._needs_serialization = True
996 self._parents = value
998 parents = property(_get_parents, _set_parents)
1000 def _get_extra(self):
1001 """Return extra settings of this commit."""
1002 self._ensure_parsed()
1005 extra = property(_get_extra)
1007 author = serializable_property("author",
1008 "The name of the author of the commit")
1010 committer = serializable_property("committer",
1011 "The name of the committer of the commit")
1013 message = serializable_property("message",
1014 "The commit message")
1016 commit_time = serializable_property("commit_time",
1017 "The timestamp of the commit. As the number of seconds since the epoch.")
1019 commit_timezone = serializable_property("commit_timezone",
1020 "The zone the commit time is in")
1022 author_time = serializable_property("author_time",
1023 "The timestamp the commit was written. as the number of seconds since the epoch.")
1025 author_timezone = serializable_property("author_timezone",
1026 "Returns the zone the author time is in.")
1028 encoding = serializable_property("encoding",
1029 "Encoding of the commit message.")
1041 for cls in OBJECT_CLASSES:
1042 _TYPE_MAP[cls.type_name] = cls
1043 _TYPE_MAP[cls.type_num] = cls
1047 # Hold on to the pure-python implementations for testing
1048 _parse_tree_py = parse_tree
1049 _sorted_tree_items_py = sorted_tree_items
1051 # Try to import C versions
1052 from dulwich._objects import parse_tree, sorted_tree_items