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,
20 """Access to base git objects."""
24 from cStringIO import (
31 from dulwich.errors import (
37 ObjectFormatException,
39 from dulwich.file import GitFile
40 from dulwich.misc import (
45 # Header fields for commits
47 _PARENT_HEADER = "parent"
48 _AUTHOR_HEADER = "author"
49 _COMMITTER_HEADER = "committer"
50 _ENCODING_HEADER = "encoding"
53 # Header fields for objects
54 _OBJECT_HEADER = "object"
57 _TAGGER_HEADER = "tagger"
63 return (stat.S_IFMT(m) == S_IFGITLINK)
66 def _decompress(string):
67 dcomp = zlib.decompressobj()
68 dcomped = dcomp.decompress(string)
69 dcomped += dcomp.flush()
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
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)
86 def hex_to_filename(path, hex):
87 """Takes a hex sha and returns its filename relative to the given path."""
90 # Check from object dir
91 return os.path.join(path, dir, file)
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
101 assert len(base) == 2 and len(rest) == 38, errmsg
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)
112 def serializable_property(name, docstring=None):
115 setattr(obj, "_"+name, value)
116 obj._needs_serialization = True
119 return getattr(obj, "_"+name)
120 return property(get, set, doc=docstring)
123 def object_class(type):
124 """Get the object class corresponding to the given type.
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.
130 return _TYPE_MAP.get(type, None)
133 def check_hexsha(hex, error_msg):
136 except (TypeError, AssertionError):
137 raise ObjectFormatException("%s %s" % (error_msg, hex))
140 def check_identity(identity, error_msg):
141 """Check if the specified identity is valid.
143 This will raise an exception if the identity is not valid.
145 :param identity: Identity string
146 :param error_msg: Error message to use in exception
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)
157 class FixedSha(object):
158 """SHA object that behaves like hashlib's but is given a fixed value."""
160 __slots__ = ('_hexsha', '_sha')
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."""
176 __slots__ = ('_needs_parsing', '_chunked_text', '_file', '_path',
177 '_sha', '_needs_serialization', '_magic')
180 def _parse_legacy_object_header(magic, f):
181 """Parse a legacy object, creating it but not reading the file."""
183 decomp = zlib.decompressobj()
184 header = decomp.decompress(magic)
188 extra = f.read(bufsize)
189 header += decomp.decompress(extra)
191 end = header.find("\0", start)
193 header = header[:end]
194 type_name, size = header.split(" ", 1)
195 size = int(size) # sanity check
196 obj_class = object_class(type_name)
198 raise ObjectFormatException("Not a known type: %s" % type_name)
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')
208 raise ObjectFormatException("Invalid object header, no \\0")
209 self.set_raw_string(text[header_end+1:])
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()
218 def as_legacy_object(self):
219 return "".join(self.as_legacy_object_chunks())
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
228 def as_raw_string(self):
229 return "".join(self.as_raw_chunks())
232 return self.as_raw_string()
237 def as_pretty_string(self):
238 return self.as_raw_string()
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)
246 elif self._path is not None:
249 raise AssertionError(
250 "ShaFile needs either text or filename")
251 self._deserialize(self._chunked_text)
252 self._needs_parsing = False
254 def set_raw_string(self, text):
255 if type(text) != str:
256 raise TypeError(text)
257 self.set_raw_chunks([text])
259 def set_raw_chunks(self, chunks):
260 self._chunked_text = chunks
261 self._deserialize(chunks)
263 self._needs_parsing = False
264 self._needs_serialization = False
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)
272 raise ObjectFormatException("Not a known type %d" % num_type)
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
283 while (byte & 0x80) != 0:
284 byte = ord(map[used])
287 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"""
309 self._chunked_text = []
310 self._needs_parsing = False
311 self._needs_serialization = True
313 def _deserialize(self, chunks):
314 raise NotImplementedError(self._deserialize)
316 def _serialize(self):
317 raise NotImplementedError(self._serialize)
319 def _parse_path(self):
320 f = GitFile(self._path, 'rb')
326 def _parse_file(self, f):
330 map = magic + f.read()
331 if self._is_legacy_object(magic[:2]):
332 self._parse_legacy_object(map)
334 self._parse_object(map)
337 def from_path(cls, path):
338 f = GitFile(path, 'rb')
340 obj = cls.from_file(f)
342 obj._sha = FixedSha(filename_to_hex(path))
350 def from_file(cls, f):
351 """Get the contents of a SHA file on disk."""
353 obj = cls._parse_file_header(f)
355 obj._needs_parsing = True
356 obj._needs_serialization = True
359 except (IndexError, ValueError), e:
360 raise ObjectFormatException("invalid object header")
363 def from_raw_string(type_num, string):
364 """Creates an object of the indicated type from the raw string given.
366 :param type_num: The numeric type of the object.
367 :param string: The raw uncompressed contents.
369 obj = object_class(type_num)()
370 obj.set_raw_string(string)
374 def from_raw_chunks(type_num, chunks):
375 """Creates an object of the indicated type from the raw chunks given.
377 :param type_num: The numeric type of the object.
378 :param chunks: An iterable of the raw uncompressed contents.
380 obj = object_class(type_num)()
381 obj.set_raw_chunks(chunks)
385 def from_string(cls, string):
386 """Create a ShaFile from a string."""
388 obj.set_raw_string(string)
391 def _check_has_member(self, member, error_msg):
392 """Check that the object has a given member variable.
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
399 if getattr(self, member, None) is None:
400 raise ObjectFormatException(error_msg)
403 """Check this object for internal consistency.
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
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
415 self._deserialize(self.as_raw_chunks())
419 raise ObjectFormatException(e)
420 if old_sha != new_sha:
421 raise ChecksumMismatch(new_sha, old_sha)
424 return object_header(self.type, self.raw_length())
426 def raw_length(self):
427 """Returns the length of the raw string of this object."""
429 for chunk in self.as_raw_chunks():
435 ret.update(self._header())
436 for chunk in self.as_raw_chunks():
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
445 new_sha.update(self._header())
446 for chunk in self.as_raw_chunks():
447 new_sha.update(chunk)
453 return self.sha().hexdigest()
458 def set_type(self, type):
461 # DEPRECATED: use type_num or type_name as needed.
462 type = property(get_type, set_type)
465 return "<%s %s>" % (self.__class__.__name__, self.id)
467 def __ne__(self, other):
468 return self.id != other.id
470 def __eq__(self, other):
471 """Return true if the sha of the two objects match.
473 The __le__ etc methods aren't overriden as they make no sense,
474 certainly at this level.
476 return self.id == other.id
480 """A Git Blob object."""
488 super(Blob, self).__init__()
489 self._chunked_text = []
490 self._needs_parsing = False
491 self._needs_serialization = False
494 return self.as_raw_string()
496 def _set_data(self, data):
497 self.set_raw_string(data)
499 data = property(_get_data, _set_data,
500 "The text contained within the blob object.")
502 def _get_chunked(self):
503 self._ensure_parsed()
504 return self._chunked_text
506 def _set_chunked(self, chunks):
507 self._chunked_text = chunks
509 def _serialize(self):
510 if not self._chunked_text:
511 self._ensure_parsed()
512 self._needs_serialization = False
513 return self._chunked_text
515 def _deserialize(self, chunks):
516 self._chunked_text = chunks
518 chunked = property(_get_chunked, _set_chunked,
519 "The text within the blob object, as chunks (not necessarily lines).")
522 def from_path(cls, path):
523 blob = ShaFile.from_path(path)
524 if not isinstance(blob, cls):
525 raise NotBlobError(path)
529 """Check this object for internal consistency.
531 :raise ObjectFormatException: if the object is malformed in some way
533 super(Blob, self).check()
536 def _parse_tag_or_commit(text):
537 """Parse tag or commit text.
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.
548 # Empty line indicates end of headers
550 yield l.split(" ", 1)
551 yield (None, f.read())
556 return _parse_tag_or_commit(text)
560 """A Git Tag object."""
565 __slots__ = ('_tag_timezone_neg_utc', '_name', '_object_sha',
566 '_object_class', '_tag_time', '_tag_timezone',
567 '_tagger', '_message')
570 super(Tag, self).__init__()
571 self._tag_timezone_neg_utc = False
574 def from_path(cls, filename):
575 tag = ShaFile.from_path(filename)
576 if not isinstance(tag, cls):
577 raise NotTagError(filename)
581 """Check this object for internal consistency.
583 :raise ObjectFormatException: if the object is malformed in some way
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")
591 raise ObjectFormatException("empty tag name")
593 check_hexsha(self._object_sha, "invalid object sha")
595 if getattr(self, "_tagger", None):
596 check_identity(self._tagger, "invalid tagger")
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")
610 def _serialize(self):
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))
616 if self._tag_time is None:
617 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
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)
627 def _deserialize(self, chunks):
628 """Grab the metadata attached to the tag"""
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)
636 raise ObjectFormatException("Not a known type: %s" % value)
637 self._object_class = obj_class
638 elif field == _TAG_HEADER:
640 elif field == _TAGGER_HEADER:
642 sep = value.index("> ")
645 self._tag_time = None
646 self._tag_timezone = None
647 self._tag_timezone_neg_utc = False
649 self._tagger = value[0:sep+1]
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)
658 self._message = value
660 raise ObjectFormatException("Unknown field %s" % field)
662 def _get_object(self):
663 """Get the object pointed to by this tag.
665 :return: tuple of (object class, sha).
667 self._ensure_parsed()
668 return (self._object_class, self._object_sha)
670 def _set_object(self, value):
671 self._ensure_parsed()
672 (self._object_class, self._object_sha) = value
673 self._needs_serialization = True
675 object = property(_get_object, _set_object)
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")
687 def parse_tree(text):
688 """Parse a tree text.
690 :param text: Serialized text to parse
691 :return: iterator of tuples of (name, mode, sha)
696 mode_end = text.index(' ', count)
697 mode_text = text[count:mode_end]
698 assert mode_text[0] != '0'
700 mode = int(mode_text, 8)
702 raise ObjectFormatException("Invalid mode '%s'" % mode_text)
703 name_end = text.index('\0', mode_end)
704 name = text[mode_end+1:name_end]
706 sha = text[name_end+1:count]
708 raise ObjectFormatException("Sha has invalid length")
709 hexsha = sha_to_hex(sha)
710 yield (name, mode, hexsha)
713 def serialize_tree(items):
714 """Serialize the items in a tree to a text.
716 :param items: Sorted iterable over (name, mode, sha) tuples
717 :return: Serialized tree text as chunks
719 for name, mode, hexsha in items:
720 yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
723 def sorted_tree_items(entries):
724 """Iterate over a tree entries dictionary in the order in which
725 the items would be serialized.
727 :param entries: Dictionary mapping names to (mode, sha) tuples
728 :return: Iterator over (name, mode, hexsha)
730 for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
732 # Stricter type checks than normal to mirror checks in the C version.
734 if not isinstance(hexsha, str):
735 raise TypeError('Expected a string for SHA, got %r' % hexsha)
736 yield name, mode, hexsha
739 def cmp_entry((name1, value1), (name2, value2)):
740 """Compare two tree entries."""
741 if stat.S_ISDIR(value1[0]):
743 if stat.S_ISDIR(value2[0]):
745 return cmp(name1, name2)
749 """A Git tree object"""
754 __slots__ = ('_entries')
757 super(Tree, self).__init__()
761 def from_path(cls, filename):
762 tree = ShaFile.from_path(filename)
763 if not isinstance(tree, cls):
764 raise NotTreeError(filename)
767 def __contains__(self, name):
768 self._ensure_parsed()
769 return name in self._entries
771 def __getitem__(self, name):
772 self._ensure_parsed()
773 return self._entries[name]
775 def __setitem__(self, name, value):
776 """Set a tree entry by name.
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
784 self._ensure_parsed()
785 self._entries[name] = (mode, hexsha)
786 self._needs_serialization = True
788 def __delitem__(self, name):
789 self._ensure_parsed()
790 del self._entries[name]
791 self._needs_serialization = True
794 self._ensure_parsed()
795 return len(self._entries)
798 self._ensure_parsed()
799 return iter(self._entries)
801 def add(self, mode, name, hexsha):
802 """Add an entry to the tree.
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.
809 self._ensure_parsed()
810 self._entries[name] = mode, hexsha
811 self._needs_serialization = True
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
819 (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
822 """Iterate over entries in the order in which they would be serialized.
824 :return: Iterator over (name, mode, sha) tuples
826 self._ensure_parsed()
827 return sorted_tree_items(self._entries)
829 def _deserialize(self, chunks):
830 """Grab the entries in the tree"""
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])
840 """Check this object for internal consistency.
842 :raise ObjectFormatException: if the object is malformed in some way
844 super(Tree, self).check()
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
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)
855 if mode not in allowed_modes:
856 raise ObjectFormatException('invalid mode %06o' % mode)
858 entry = (name, (mode, sha))
860 if cmp_entry(last, entry) > 0:
861 raise ObjectFormatException('entries not sorted')
863 raise ObjectFormatException('duplicate entry %s' % name)
866 def _serialize(self):
867 return list(serialize_tree(self.iteritems()))
869 def as_pretty_string(self):
871 for name, mode, hexsha in self.iteritems():
872 if mode & stat.S_IFDIR:
876 text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
880 def parse_timezone(text):
881 """Parse a timezone text fragment (e.g. '+0100').
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).
889 negative_utc = (offset == 0 and text[0] == '-')
890 signum = (offset < 0) and -1 or 1
892 hours = int(offset / 100)
893 minutes = (offset % 100)
894 return signum * (hours * 3600 + minutes * 60), negative_utc
897 def format_timezone(offset, negative_utc=False):
898 """Format a timezone for Git serialization.
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).
905 raise ValueError("Unable to handle non-minute offset.")
906 if offset < 0 or (offset == 0 and negative_utc):
911 return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
914 def parse_commit(text):
915 return _parse_tag_or_commit(text)
918 class Commit(ShaFile):
919 """A git commit object"""
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')
931 super(Commit, self).__init__()
933 self._encoding = None
935 self._author_timezone_neg_utc = False
936 self._commit_timezone_neg_utc = False
939 def from_path(cls, path):
940 commit = ShaFile.from_path(path)
941 if not isinstance(commit, cls):
942 raise NotCommitError(path)
945 def _deserialize(self, chunks):
949 for field, value in parse_commit("".join(self._chunked_text)):
950 if field == _TREE_HEADER:
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
967 self._message = value
969 self._extra.append((field, value))
972 """Check this object for internal consistency.
974 :raise ObjectFormatException: if the object is malformed in some way
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
982 for parent in self._parents:
983 check_hexsha(parent, "invalid parent sha")
984 check_hexsha(self._tree, "invalid tree sha")
986 check_identity(self._author, "invalid author")
987 check_identity(self._committer, "invalid committer")
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,
995 raise ObjectFormatException("unexpected parent")
996 elif field == _AUTHOR_HEADER and last not in (_TREE_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")
1005 # TODO: optionally check for duplicate parents
1007 def _serialize(self):
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)))
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)
1030 tree = serializable_property("tree", "Tree that is the state of this commit")
1032 def _get_parents(self):
1033 """Return a list of parents of this commit."""
1034 self._ensure_parsed()
1035 return self._parents
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
1043 parents = property(_get_parents, _set_parents)
1045 def _get_extra(self):
1046 """Return extra settings of this commit."""
1047 self._ensure_parsed()
1050 extra = property(_get_extra)
1052 author = serializable_property("author",
1053 "The name of the author of the commit")
1055 committer = serializable_property("committer",
1056 "The name of the committer of the commit")
1058 message = serializable_property("message",
1059 "The commit message")
1061 commit_time = serializable_property("commit_time",
1062 "The timestamp of the commit. As the number of seconds since the epoch.")
1064 commit_timezone = serializable_property("commit_timezone",
1065 "The zone the commit time is in")
1067 author_time = serializable_property("author_time",
1068 "The timestamp the commit was written. as the number of seconds since the epoch.")
1070 author_timezone = serializable_property("author_timezone",
1071 "Returns the zone the author time is in.")
1073 encoding = serializable_property("encoding",
1074 "Encoding of the commit message.")
1086 for cls in OBJECT_CLASSES:
1087 _TYPE_MAP[cls.type_name] = cls
1088 _TYPE_MAP[cls.type_num] = cls
1092 # Hold on to the pure-python implementations for testing
1093 _parse_tree_py = parse_tree
1094 _sorted_tree_items_py = sorted_tree_items
1096 # Try to import C versions
1097 from dulwich._objects import parse_tree, sorted_tree_items