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 (
34 from dulwich.errors import (
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 serializable_property(name, docstring=None):
89 setattr(obj, "_"+name, value)
90 obj._needs_serialization = True
93 return getattr(obj, "_"+name)
94 return property(get, set, doc=docstring)
97 def object_class(type):
98 """Get the object class corresponding to the given type.
100 :param type: Either a type name string or a numeric type.
101 :return: The ShaFile subclass corresponding to the given type.
103 return _TYPE_MAP[type]
106 class ShaFile(object):
107 """A git SHA file."""
110 def _parse_legacy_object(cls, map):
111 """Parse a legacy object, creating it and setting object._text"""
112 text = _decompress(map)
114 for cls in OBJECT_CLASSES:
115 if text.startswith(cls.type_name):
117 text = text[len(cls.type_name):]
119 assert object is not None, "%s is not a known object type" % text[:9]
120 assert text[0] == ' ', "%s is not a space" % text[0]
124 while text[0] >= '0' and text[0] <= '9':
125 if i > 0 and size == 0:
126 raise AssertionError("Size is not in canonical format")
127 size = (size * 10) + int(text[0])
131 assert text[0] == "\0", "Size not followed by null"
133 object.set_raw_string(text)
136 def as_legacy_object_chunks(self):
137 compobj = zlib.compressobj()
138 yield compobj.compress(self._header())
139 for chunk in self.as_raw_chunks():
140 yield compobj.compress(chunk)
141 yield compobj.flush()
143 def as_legacy_object(self):
144 return "".join(self.as_legacy_object_chunks())
146 def as_raw_chunks(self):
147 if self._needs_serialization:
148 self._chunked_text = self._serialize()
149 self._needs_serialization = False
150 return self._chunked_text
152 def as_raw_string(self):
153 return "".join(self.as_raw_chunks())
156 return self.as_raw_string()
161 def as_pretty_string(self):
162 return self.as_raw_string()
164 def _ensure_parsed(self):
165 if self._needs_parsing:
166 self._deserialize(self._chunked_text)
167 self._needs_parsing = False
169 def set_raw_string(self, text):
170 if type(text) != str:
171 raise TypeError(text)
172 self.set_raw_chunks([text])
174 def set_raw_chunks(self, chunks):
175 self._chunked_text = chunks
177 self._needs_parsing = True
178 self._needs_serialization = False
181 def _parse_object(cls, map):
182 """Parse a new style object , creating it and setting object._text"""
184 byte = ord(map[used])
186 type_num = (byte >> 4) & 7
188 object = object_class(type_num)()
190 raise AssertionError("Not a known type: %d" % type_num)
191 while (byte & 0x80) != 0:
192 byte = ord(map[used])
195 object.set_raw_string(_decompress(raw))
199 def _parse_file(cls, map):
200 word = (ord(map[0]) << 8) + ord(map[1])
201 if ord(map[0]) == 0x78 and (word % 31) == 0:
202 return cls._parse_legacy_object(map)
204 return cls._parse_object(map)
207 """Don't call this directly"""
210 def _deserialize(self, chunks):
211 raise NotImplementedError(self._deserialize)
213 def _serialize(self):
214 raise NotImplementedError(self._serialize)
217 def from_file(cls, filename):
218 """Get the contents of a SHA file on disk"""
219 size = os.path.getsize(filename)
220 f = GitFile(filename, 'rb')
222 map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
223 shafile = cls._parse_file(map)
229 def from_raw_string(type_num, string):
230 """Creates an object of the indicated type from the raw string given.
232 :param type_num: The numeric type of the object.
233 :param string: The raw uncompressed contents.
235 obj = object_class(type_num)()
236 obj.set_raw_string(string)
240 def from_raw_chunks(type_num, chunks):
241 """Creates an object of the indicated type from the raw chunks given.
243 :param type_num: The numeric type of the object.
244 :param chunks: An iterable of the raw uncompressed contents.
246 obj = object_class(type_num)()
247 obj.set_raw_chunks(chunks)
251 def from_string(cls, string):
252 """Create a blob from a string."""
254 obj.set_raw_string(string)
258 return "%s %lu\0" % (self.type_name, self.raw_length())
260 def raw_length(self):
261 """Returns the length of the raw string of this object."""
263 for chunk in self.as_raw_chunks():
269 ret.update(self._header())
270 for chunk in self.as_raw_chunks():
275 """The SHA1 object that is the name of this object."""
276 if self._needs_serialization or self._sha is None:
277 self._sha = self._make_sha()
282 return self.sha().hexdigest()
287 def set_type(self, type):
290 # DEPRECATED: use type_num or type_name as needed.
291 type = property(get_type, set_type)
294 return "<%s %s>" % (self.__class__.__name__, self.id)
296 def __ne__(self, other):
297 return self.id != other.id
299 def __eq__(self, other):
300 """Return true if the sha of the two objects match.
302 The __le__ etc methods aren't overriden as they make no sense,
303 certainly at this level.
305 return self.id == other.id
309 """A Git Blob object."""
315 super(Blob, self).__init__()
316 self._chunked_text = []
317 self._needs_parsing = False
318 self._needs_serialization = False
321 return self.as_raw_string()
323 def _set_data(self, data):
324 self.set_raw_string(data)
326 data = property(_get_data, _set_data,
327 "The text contained within the blob object.")
329 def _get_chunked(self):
330 return self._chunked_text
332 def _set_chunked(self, chunks):
333 self._chunked_text = chunks
335 chunked = property(_get_chunked, _set_chunked,
336 "The text within the blob object, as chunks (not necessarily lines).")
339 def from_file(cls, filename):
340 blob = ShaFile.from_file(filename)
341 if not isinstance(blob, cls):
342 raise NotBlobError(filename)
347 """A Git Tag object."""
353 super(Tag, self).__init__()
354 self._needs_parsing = False
355 self._needs_serialization = True
358 def from_file(cls, filename):
359 tag = ShaFile.from_file(filename)
360 if not isinstance(tag, cls):
361 raise NotTagError(filename)
365 def from_string(cls, string):
366 """Create a blob from a string."""
368 shafile.set_raw_string(string)
371 def _serialize(self):
373 chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
374 chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
375 chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
377 if self._tag_time is None:
378 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
380 chunks.append("%s %s %d %s\n" % (
381 _TAGGER_HEADER, self._tagger, self._tag_time,
382 format_timezone(self._tag_timezone)))
383 chunks.append("\n") # To close headers
384 chunks.append(self._message)
387 def _deserialize(self, chunks):
388 """Grab the metadata attached to the tag"""
390 f = StringIO("".join(chunks))
394 break # empty line indicates end of headers
395 (field, value) = l.split(" ", 1)
396 if field == _OBJECT_HEADER:
397 self._object_sha = value
398 elif field == _TYPE_HEADER:
399 self._object_class = object_class(value)
400 elif field == _TAG_HEADER:
402 elif field == _TAGGER_HEADER:
404 sep = value.index("> ")
407 self._tag_time = None
408 self._tag_timezone = None
410 self._tagger = value[0:sep+1]
411 (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
413 self._tag_time = int(timetext)
414 except ValueError: #Not a unix timestamp
415 self._tag_time = time.strptime(timetext)
416 self._tag_timezone = parse_timezone(timezonetext)
418 raise AssertionError("Unknown field %s" % field)
419 self._message = f.read()
421 def _get_object(self):
422 """Get the object pointed to by this tag.
424 :return: tuple of (object class, sha).
426 self._ensure_parsed()
427 return (self._object_class, self._object_sha)
429 def _set_object(self, value):
430 self._ensure_parsed()
431 (self._object_class, self._object_sha) = value
432 self._needs_serialization = True
434 object = property(_get_object, _set_object)
436 name = serializable_property("name", "The name of this tag")
437 tagger = serializable_property("tagger",
438 "Returns the name of the person who created this tag")
439 tag_time = serializable_property("tag_time",
440 "The creation timestamp of the tag. As the number of seconds since the epoch")
441 tag_timezone = serializable_property("tag_timezone",
442 "The timezone that tag_time is in.")
443 message = serializable_property("message", "The message attached to this tag")
446 def parse_tree(text):
447 """Parse a tree text.
449 :param text: Serialized text to parse
450 :return: Dictionary with names as keys, (mode, sha) tuples as values
456 mode_end = text.index(' ', count)
457 mode = int(text[count:mode_end], 8)
458 name_end = text.index('\0', mode_end)
459 name = text[mode_end+1:name_end]
461 sha = text[name_end+1:count]
462 ret[name] = (mode, sha_to_hex(sha))
466 def serialize_tree(items):
467 """Serialize the items in a tree to a text.
469 :param items: Sorted iterable over (name, mode, sha) tuples
470 :return: Serialized tree text as chunks
472 for name, mode, hexsha in items:
473 yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
476 def sorted_tree_items(entries):
477 """Iterate over a tree entries dictionary in the order in which
478 the items would be serialized.
480 :param entries: Dictionary mapping names to (mode, sha) tuples
481 :return: Iterator over (name, mode, sha)
483 def cmp_entry((name1, value1), (name2, value2)):
484 if stat.S_ISDIR(value1[0]):
486 if stat.S_ISDIR(value2[0]):
488 return cmp(name1, name2)
489 for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
490 yield name, entry[0], entry[1]
494 """A Git tree object"""
500 super(Tree, self).__init__()
502 self._needs_parsing = False
503 self._needs_serialization = True
506 def from_file(cls, filename):
507 tree = ShaFile.from_file(filename)
508 if not isinstance(tree, cls):
509 raise NotTreeError(filename)
512 def __contains__(self, name):
513 self._ensure_parsed()
514 return name in self._entries
516 def __getitem__(self, name):
517 self._ensure_parsed()
518 return self._entries[name]
520 def __setitem__(self, name, value):
521 assert isinstance(value, tuple)
522 assert len(value) == 2
523 self._ensure_parsed()
524 self._entries[name] = value
525 self._needs_serialization = True
527 def __delitem__(self, name):
528 self._ensure_parsed()
529 del self._entries[name]
530 self._needs_serialization = True
533 self._ensure_parsed()
534 return len(self._entries)
536 def add(self, mode, name, hexsha):
537 assert type(mode) == int
538 assert type(name) == str
539 assert type(hexsha) == str
540 self._ensure_parsed()
541 self._entries[name] = mode, hexsha
542 self._needs_serialization = True
545 """Return a list of tuples describing the tree entries"""
546 self._ensure_parsed()
547 # The order of this is different from iteritems() for historical
550 (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
553 """Iterate over all entries in the order in which they would be
556 :return: Iterator over (name, mode, sha) tuples
558 self._ensure_parsed()
559 return sorted_tree_items(self._entries)
561 def _deserialize(self, chunks):
562 """Grab the entries in the tree"""
563 self._entries = parse_tree("".join(chunks))
565 def _serialize(self):
566 return list(serialize_tree(self.iteritems()))
568 def as_pretty_string(self):
570 for name, mode, hexsha in self.iteritems():
571 if mode & stat.S_IFDIR:
575 text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
579 def parse_timezone(text):
581 signum = (offset < 0) and -1 or 1
583 hours = int(offset / 100)
584 minutes = (offset % 100)
585 return signum * (hours * 3600 + minutes * 60)
588 def format_timezone(offset):
590 raise ValueError("Unable to handle non-minute offset.")
591 sign = (offset < 0) and '-' or '+'
593 return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
596 class Commit(ShaFile):
597 """A git commit object"""
603 super(Commit, self).__init__()
605 self._encoding = None
606 self._needs_parsing = False
607 self._needs_serialization = True
611 def from_file(cls, filename):
612 commit = ShaFile.from_file(filename)
613 if not isinstance(commit, cls):
614 raise NotCommitError(filename)
617 def _deserialize(self, chunks):
621 f = StringIO("".join(chunks))
625 # Empty line indicates end of headers
627 (field, value) = l.split(" ", 1)
628 if field == _TREE_HEADER:
630 elif field == _PARENT_HEADER:
631 self._parents.append(value)
632 elif field == _AUTHOR_HEADER:
633 self._author, timetext, timezonetext = value.rsplit(" ", 2)
634 self._author_time = int(timetext)
635 self._author_timezone = parse_timezone(timezonetext)
636 elif field == _COMMITTER_HEADER:
637 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
638 self._commit_time = int(timetext)
639 self._commit_timezone = parse_timezone(timezonetext)
640 elif field == _ENCODING_HEADER:
641 self._encoding = value
643 self._extra.append((field, value))
644 self._message = f.read()
646 def _serialize(self):
648 chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
649 for p in self._parents:
650 chunks.append("%s %s\n" % (_PARENT_HEADER, p))
651 chunks.append("%s %s %s %s\n" % (
652 _AUTHOR_HEADER, self._author, str(self._author_time),
653 format_timezone(self._author_timezone)))
654 chunks.append("%s %s %s %s\n" % (
655 _COMMITTER_HEADER, self._committer, str(self._commit_time),
656 format_timezone(self._commit_timezone)))
658 chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
659 for k, v in self.extra:
660 if "\n" in k or "\n" in v:
661 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
662 chunks.append("%s %s\n" % (k, v))
663 chunks.append("\n") # There must be a new line after the headers
664 chunks.append(self._message)
667 tree = serializable_property("tree", "Tree that is the state of this commit")
669 def _get_parents(self):
670 """Return a list of parents of this commit."""
671 self._ensure_parsed()
674 def _set_parents(self, value):
675 """Set a list of parents of this commit."""
676 self._ensure_parsed()
677 self._needs_serialization = True
678 self._parents = value
680 parents = property(_get_parents, _set_parents)
682 def _get_extra(self):
683 """Return extra settings of this commit."""
684 self._ensure_parsed()
687 extra = property(_get_extra)
689 author = serializable_property("author",
690 "The name of the author of the commit")
692 committer = serializable_property("committer",
693 "The name of the committer of the commit")
695 message = serializable_property("message",
696 "The commit message")
698 commit_time = serializable_property("commit_time",
699 "The timestamp of the commit. As the number of seconds since the epoch.")
701 commit_timezone = serializable_property("commit_timezone",
702 "The zone the commit time is in")
704 author_time = serializable_property("author_time",
705 "The timestamp the commit was written. as the number of seconds since the epoch.")
707 author_timezone = serializable_property("author_timezone",
708 "Returns the zone the author time is in.")
710 encoding = serializable_property("encoding",
711 "Encoding of the commit message.")
723 for cls in OBJECT_CLASSES:
724 _TYPE_MAP[cls.type_name] = cls
725 _TYPE_MAP[cls.type_num] = cls
729 # Try to import C versions
730 from dulwich._objects import parse_tree, sorted_tree_items