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(self):
137 text = self.as_raw_string()
138 return zlib.compress("%s %d\0%s" % (self.type_name, len(text), text))
140 def as_raw_chunks(self):
141 if self._needs_serialization:
142 self._chunked_text = self._serialize()
143 self._needs_serialization = False
144 return self._chunked_text
146 def as_raw_string(self):
147 return "".join(self.as_raw_chunks())
150 return self.as_raw_string()
155 def as_pretty_string(self):
156 return self.as_raw_string()
158 def _ensure_parsed(self):
159 if self._needs_parsing:
160 self._deserialize(self._chunked_text)
161 self._needs_parsing = False
163 def set_raw_string(self, text):
164 if type(text) != str:
165 raise TypeError(text)
166 self.set_raw_chunks([text])
168 def set_raw_chunks(self, chunks):
169 self._chunked_text = chunks
171 self._needs_parsing = True
172 self._needs_serialization = False
175 def _parse_object(cls, map):
176 """Parse a new style object , creating it and setting object._text"""
178 byte = ord(map[used])
180 type_num = (byte >> 4) & 7
182 object = object_class(type_num)()
184 raise AssertionError("Not a known type: %d" % type_num)
185 while (byte & 0x80) != 0:
186 byte = ord(map[used])
189 object.set_raw_string(_decompress(raw))
193 def _parse_file(cls, map):
194 word = (ord(map[0]) << 8) + ord(map[1])
195 if ord(map[0]) == 0x78 and (word % 31) == 0:
196 return cls._parse_legacy_object(map)
198 return cls._parse_object(map)
201 """Don't call this directly"""
204 def _deserialize(self, chunks):
205 raise NotImplementedError(self._deserialize)
207 def _serialize(self):
208 raise NotImplementedError(self._serialize)
211 def from_file(cls, filename):
212 """Get the contents of a SHA file on disk"""
213 size = os.path.getsize(filename)
214 f = GitFile(filename, 'rb')
216 map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
217 shafile = cls._parse_file(map)
223 def from_raw_string(type_num, string):
224 """Creates an object of the indicated type from the raw string given.
226 :param type_num: The numeric type of the object.
227 :param string: The raw uncompressed contents.
229 obj = object_class(type_num)()
230 obj.set_raw_string(string)
234 def from_raw_chunks(type_num, chunks):
235 """Creates an object of the indicated type from the raw chunks given.
237 :param type_num: The numeric type of the object.
238 :param chunks: An iterable of the raw uncompressed contents.
240 obj = object_class(type_num)()
241 obj.set_raw_chunks(chunks)
245 def from_string(cls, string):
246 """Create a blob from a string."""
248 obj.set_raw_string(string)
252 return "%s %lu\0" % (self.type_name, self.raw_length())
254 def raw_length(self):
255 """Returns the length of the raw string of this object."""
257 for chunk in self.as_raw_chunks():
263 ret.update(self._header())
264 for chunk in self.as_raw_chunks():
269 """The SHA1 object that is the name of this object."""
270 if self._needs_serialization or self._sha is None:
271 self._sha = self._make_sha()
276 return self.sha().hexdigest()
281 def set_type(self, type):
284 # DEPRECATED: use type_num or type_name as needed.
285 type = property(get_type, set_type)
288 return "<%s %s>" % (self.__class__.__name__, self.id)
290 def __ne__(self, other):
291 return self.id != other.id
293 def __eq__(self, other):
294 """Return true if the sha of the two objects match.
296 The __le__ etc methods aren't overriden as they make no sense,
297 certainly at this level.
299 return self.id == other.id
303 """A Git Blob object."""
309 super(Blob, self).__init__()
310 self._chunked_text = []
311 self._needs_parsing = False
312 self._needs_serialization = False
315 return self.as_raw_string()
317 def _set_data(self, data):
318 self.set_raw_string(data)
320 data = property(_get_data, _set_data,
321 "The text contained within the blob object.")
323 def _get_chunked(self):
324 return self._chunked_text
326 def _set_chunked(self, chunks):
327 self._chunked_text = chunks
329 chunked = property(_get_chunked, _set_chunked,
330 "The text within the blob object, as chunks (not necessarily lines).")
333 def from_file(cls, filename):
334 blob = ShaFile.from_file(filename)
335 if not isinstance(blob, cls):
336 raise NotBlobError(filename)
341 """A Git Tag object."""
347 super(Tag, self).__init__()
348 self._needs_parsing = False
349 self._needs_serialization = True
352 def from_file(cls, filename):
353 tag = ShaFile.from_file(filename)
354 if not isinstance(tag, cls):
355 raise NotTagError(filename)
359 def from_string(cls, string):
360 """Create a blob from a string."""
362 shafile.set_raw_string(string)
365 def _serialize(self):
367 chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
368 chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
369 chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
371 if self._tag_time is None:
372 chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
374 chunks.append("%s %s %d %s\n" % (
375 _TAGGER_HEADER, self._tagger, self._tag_time,
376 format_timezone(self._tag_timezone)))
377 chunks.append("\n") # To close headers
378 chunks.append(self._message)
381 def _deserialize(self, chunks):
382 """Grab the metadata attached to the tag"""
384 f = StringIO("".join(chunks))
388 break # empty line indicates end of headers
389 (field, value) = l.split(" ", 1)
390 if field == _OBJECT_HEADER:
391 self._object_sha = value
392 elif field == _TYPE_HEADER:
393 self._object_class = object_class(value)
394 elif field == _TAG_HEADER:
396 elif field == _TAGGER_HEADER:
398 sep = value.index("> ")
401 self._tag_time = None
402 self._tag_timezone = None
404 self._tagger = value[0:sep+1]
405 (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
407 self._tag_time = int(timetext)
408 except ValueError: #Not a unix timestamp
409 self._tag_time = time.strptime(timetext)
410 self._tag_timezone = parse_timezone(timezonetext)
412 raise AssertionError("Unknown field %s" % field)
413 self._message = f.read()
415 def _get_object(self):
416 """Get the object pointed to by this tag.
418 :return: tuple of (object class, sha).
420 self._ensure_parsed()
421 return (self._object_class, self._object_sha)
423 def _set_object(self, value):
424 self._ensure_parsed()
425 (self._object_class, self._object_sha) = value
426 self._needs_serialization = True
428 object = property(_get_object, _set_object)
430 name = serializable_property("name", "The name of this tag")
431 tagger = serializable_property("tagger",
432 "Returns the name of the person who created this tag")
433 tag_time = serializable_property("tag_time",
434 "The creation timestamp of the tag. As the number of seconds since the epoch")
435 tag_timezone = serializable_property("tag_timezone",
436 "The timezone that tag_time is in.")
437 message = serializable_property("message", "The message attached to this tag")
440 def parse_tree(text):
441 """Parse a tree text.
443 :param text: Serialized text to parse
444 :return: Dictionary with names as keys, (mode, sha) tuples as values
450 mode_end = text.index(' ', count)
451 mode = int(text[count:mode_end], 8)
452 name_end = text.index('\0', mode_end)
453 name = text[mode_end+1:name_end]
455 sha = text[name_end+1:count]
456 ret[name] = (mode, sha_to_hex(sha))
460 def serialize_tree(items):
461 """Serialize the items in a tree to a text.
463 :param items: Sorted iterable over (name, mode, sha) tuples
464 :return: Serialized tree text as chunks
466 for name, mode, hexsha in items:
467 yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
470 def sorted_tree_items(entries):
471 """Iterate over a tree entries dictionary in the order in which
472 the items would be serialized.
474 :param entries: Dictionary mapping names to (mode, sha) tuples
475 :return: Iterator over (name, mode, sha)
477 def cmp_entry((name1, value1), (name2, value2)):
478 if stat.S_ISDIR(value1[0]):
480 if stat.S_ISDIR(value2[0]):
482 return cmp(name1, name2)
483 for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
484 yield name, entry[0], entry[1]
488 """A Git tree object"""
494 super(Tree, self).__init__()
496 self._needs_parsing = False
497 self._needs_serialization = True
500 def from_file(cls, filename):
501 tree = ShaFile.from_file(filename)
502 if not isinstance(tree, cls):
503 raise NotTreeError(filename)
506 def __contains__(self, name):
507 self._ensure_parsed()
508 return name in self._entries
510 def __getitem__(self, name):
511 self._ensure_parsed()
512 return self._entries[name]
514 def __setitem__(self, name, value):
515 assert isinstance(value, tuple)
516 assert len(value) == 2
517 self._ensure_parsed()
518 self._entries[name] = value
519 self._needs_serialization = True
521 def __delitem__(self, name):
522 self._ensure_parsed()
523 del self._entries[name]
524 self._needs_serialization = True
527 self._ensure_parsed()
528 return len(self._entries)
530 def add(self, mode, name, hexsha):
531 assert type(mode) == int
532 assert type(name) == str
533 assert type(hexsha) == str
534 self._ensure_parsed()
535 self._entries[name] = mode, hexsha
536 self._needs_serialization = True
539 """Return a list of tuples describing the tree entries"""
540 self._ensure_parsed()
541 # The order of this is different from iteritems() for historical
544 (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
547 """Iterate over all entries in the order in which they would be
550 :return: Iterator over (name, mode, sha) tuples
552 self._ensure_parsed()
553 return sorted_tree_items(self._entries)
555 def _deserialize(self, chunks):
556 """Grab the entries in the tree"""
557 self._entries = parse_tree("".join(chunks))
559 def _serialize(self):
560 return list(serialize_tree(self.iteritems()))
562 def as_pretty_string(self):
564 for name, mode, hexsha in self.iteritems():
565 if mode & stat.S_IFDIR:
569 text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
573 def parse_timezone(text):
575 signum = (offset < 0) and -1 or 1
577 hours = int(offset / 100)
578 minutes = (offset % 100)
579 return signum * (hours * 3600 + minutes * 60)
582 def format_timezone(offset):
584 raise ValueError("Unable to handle non-minute offset.")
585 sign = (offset < 0) and '-' or '+'
587 return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
590 class Commit(ShaFile):
591 """A git commit object"""
597 super(Commit, self).__init__()
599 self._encoding = None
600 self._needs_parsing = False
601 self._needs_serialization = True
605 def from_file(cls, filename):
606 commit = ShaFile.from_file(filename)
607 if not isinstance(commit, cls):
608 raise NotCommitError(filename)
611 def _deserialize(self, chunks):
615 f = StringIO("".join(chunks))
619 # Empty line indicates end of headers
621 (field, value) = l.split(" ", 1)
622 if field == _TREE_HEADER:
624 elif field == _PARENT_HEADER:
625 self._parents.append(value)
626 elif field == _AUTHOR_HEADER:
627 self._author, timetext, timezonetext = value.rsplit(" ", 2)
628 self._author_time = int(timetext)
629 self._author_timezone = parse_timezone(timezonetext)
630 elif field == _COMMITTER_HEADER:
631 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
632 self._commit_time = int(timetext)
633 self._commit_timezone = parse_timezone(timezonetext)
634 elif field == _ENCODING_HEADER:
635 self._encoding = value
637 self._extra.append((field, value))
638 self._message = f.read()
640 def _serialize(self):
642 chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
643 for p in self._parents:
644 chunks.append("%s %s\n" % (_PARENT_HEADER, p))
645 chunks.append("%s %s %s %s\n" % (
646 _AUTHOR_HEADER, self._author, str(self._author_time),
647 format_timezone(self._author_timezone)))
648 chunks.append("%s %s %s %s\n" % (
649 _COMMITTER_HEADER, self._committer, str(self._commit_time),
650 format_timezone(self._commit_timezone)))
652 chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
653 for k, v in self.extra:
654 if "\n" in k or "\n" in v:
655 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
656 chunks.append("%s %s\n" % (k, v))
657 chunks.append("\n") # There must be a new line after the headers
658 chunks.append(self._message)
661 tree = serializable_property("tree", "Tree that is the state of this commit")
663 def _get_parents(self):
664 """Return a list of parents of this commit."""
665 self._ensure_parsed()
668 def _set_parents(self, value):
669 """Set a list of parents of this commit."""
670 self._ensure_parsed()
671 self._needs_serialization = True
672 self._parents = value
674 parents = property(_get_parents, _set_parents)
676 def _get_extra(self):
677 """Return extra settings of this commit."""
678 self._ensure_parsed()
681 extra = property(_get_extra)
683 author = serializable_property("author",
684 "The name of the author of the commit")
686 committer = serializable_property("committer",
687 "The name of the committer of the commit")
689 message = serializable_property("message",
690 "The commit message")
692 commit_time = serializable_property("commit_time",
693 "The timestamp of the commit. As the number of seconds since the epoch.")
695 commit_timezone = serializable_property("commit_timezone",
696 "The zone the commit time is in")
698 author_time = serializable_property("author_time",
699 "The timestamp the commit was written. as the number of seconds since the epoch.")
701 author_timezone = serializable_property("author_timezone",
702 "Returns the zone the author time is in.")
704 encoding = serializable_property("encoding",
705 "Encoding of the commit message.")
717 for cls in OBJECT_CLASSES:
718 _TYPE_MAP[cls.type_name] = cls
719 _TYPE_MAP[cls.type_num] = cls
723 # Try to import C versions
724 from dulwich._objects import parse_tree, sorted_tree_items