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 (
50 COMMITTER_ID = "committer"
54 ENCODING_ID = "encoding"
58 return (stat.S_IFMT(m) == S_IFGITLINK)
60 def _decompress(string):
61 dcomp = zlib.decompressobj()
62 dcomped = dcomp.decompress(string)
63 dcomped += dcomp.flush()
68 """Takes a string and returns the hex of the sha within"""
69 hexsha = binascii.hexlify(sha)
70 assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
75 """Takes a hex sha and returns a binary sha"""
76 assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
77 return binascii.unhexlify(hex)
80 def serializable_property(name, docstring=None):
83 setattr(obj, "_"+name, value)
84 obj._needs_serialization = True
87 return getattr(obj, "_"+name)
88 return property(get, set, doc=docstring)
91 class ShaFile(object):
95 def _parse_legacy_object(cls, map):
96 """Parse a legacy object, creating it and setting object._text"""
97 text = _decompress(map)
99 for posstype in type_map.keys():
100 if text.startswith(posstype):
101 object = type_map[posstype]()
102 text = text[len(posstype):]
104 assert object is not None, "%s is not a known object type" % text[:9]
105 assert text[0] == ' ', "%s is not a space" % text[0]
109 while text[0] >= '0' and text[0] <= '9':
110 if i > 0 and size == 0:
111 raise AssertionError("Size is not in canonical format")
112 size = (size * 10) + int(text[0])
116 assert text[0] == "\0", "Size not followed by null"
118 object.set_raw_string(text)
121 def as_legacy_object(self):
122 text = self.as_raw_string()
123 return zlib.compress("%s %d\0%s" % (self._type, len(text), text))
125 def as_raw_string(self):
126 if self._needs_serialization:
131 return self.as_raw_string()
136 def as_pretty_string(self):
137 return self.as_raw_string()
139 def _ensure_parsed(self):
140 if self._needs_parsing:
143 def set_raw_string(self, text):
144 if type(text) != str:
145 raise TypeError(text)
148 self._needs_parsing = True
149 self._needs_serialization = False
152 def _parse_object(cls, map):
153 """Parse a new style object , creating it and setting object._text"""
155 byte = ord(map[used])
157 num_type = (byte >> 4) & 7
159 object = num_type_map[num_type]()
161 raise AssertionError("Not a known type: %d" % num_type)
162 while (byte & 0x80) != 0:
163 byte = ord(map[used])
166 object.set_raw_string(_decompress(raw))
170 def _parse_file(cls, map):
171 word = (ord(map[0]) << 8) + ord(map[1])
172 if ord(map[0]) == 0x78 and (word % 31) == 0:
173 return cls._parse_legacy_object(map)
175 return cls._parse_object(map)
178 """Don't call this directly"""
181 def _parse_text(self):
182 """For subclasses to do initialisation time parsing"""
185 def from_file(cls, filename):
186 """Get the contents of a SHA file on disk"""
187 size = os.path.getsize(filename)
188 f = GitFile(filename, 'rb')
190 map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
191 shafile = cls._parse_file(map)
197 def from_raw_string(cls, type, string):
198 """Creates an object of the indicated type from the raw string given.
200 Type is the numeric type of an object. String is the raw uncompressed
203 real_class = num_type_map[type]
206 obj.set_raw_string(string)
210 def from_string(cls, string):
211 """Create a blob from a string."""
213 shafile.set_raw_string(string)
217 return "%s %lu\0" % (self._type, len(self.as_raw_string()))
220 """The SHA1 object that is the name of this object."""
221 if self._needs_serialization or self._sha is None:
222 self._sha = make_sha()
223 self._sha.update(self._header())
224 self._sha.update(self.as_raw_string())
229 return self.sha().hexdigest()
232 return self._num_type
234 def set_type(self, type):
235 self._num_type = type
237 type = property(get_type, set_type)
240 return "<%s %s>" % (self.__class__.__name__, self.id)
242 def __ne__(self, other):
243 return self.id != other.id
245 def __eq__(self, other):
246 """Return true id the sha of the two objects match.
248 The __le__ etc methods aren't overriden as they make no sense,
249 certainly at this level.
251 return self.id == other.id
255 """A Git Blob object."""
259 _needs_serialization = False
260 _needs_parsing = False
265 def set_data(self, data):
268 data = property(get_data, set_data,
269 "The text contained within the blob object.")
272 def from_file(cls, filename):
273 blob = ShaFile.from_file(filename)
274 if blob._type != cls._type:
275 raise NotBlobError(filename)
280 """A Git Tag object."""
286 super(Tag, self).__init__()
287 self._needs_parsing = False
288 self._needs_serialization = True
291 def from_file(cls, filename):
292 blob = ShaFile.from_file(filename)
293 if blob._type != cls._type:
294 raise NotBlobError(filename)
298 def from_string(cls, string):
299 """Create a blob from a string."""
301 shafile.set_raw_string(string)
306 f.write("%s %s\n" % (OBJECT_ID, self._object_sha))
307 f.write("%s %s\n" % (TYPE_ID, num_type_map[self._object_type]._type))
308 f.write("%s %s\n" % (TAG_ID, self._name))
310 if self._tag_time is None:
311 f.write("%s %s\n" % (TAGGER_ID, self._tagger))
313 f.write("%s %s %d %s\n" % (TAGGER_ID, self._tagger, self._tag_time, format_timezone(self._tag_timezone)))
314 f.write("\n") # To close headers
315 f.write(self._message)
316 self._text = f.getvalue()
317 self._needs_serialization = False
319 def _parse_text(self):
320 """Grab the metadata attached to the tag"""
322 f = StringIO(self._text)
326 break # empty line indicates end of headers
327 (field, value) = l.split(" ", 1)
328 if field == OBJECT_ID:
329 self._object_sha = value
330 elif field == TYPE_ID:
331 self._object_type = type_map[value]
332 elif field == TAG_ID:
334 elif field == TAGGER_ID:
336 sep = value.index("> ")
339 self._tag_time = None
340 self._tag_timezone = None
342 self._tagger = value[0:sep+1]
343 (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
345 self._tag_time = int(timetext)
346 except ValueError: #Not a unix timestamp
347 self._tag_time = time.strptime(timetext)
348 self._tag_timezone = parse_timezone(timezonetext)
350 raise AssertionError("Unknown field %s" % field)
351 self._message = f.read()
352 self._needs_parsing = False
354 def get_object(self):
355 """Returns the object pointed by this tag, represented as a tuple(type, sha)"""
356 self._ensure_parsed()
357 return (self._object_type, self._object_sha)
359 def set_object(self, value):
360 self._ensure_parsed()
361 (self._object_type, self._object_sha) = value
362 self._needs_serialization = True
364 object = property(get_object, set_object)
366 name = serializable_property("name", "The name of this tag")
367 tagger = serializable_property("tagger",
368 "Returns the name of the person who created this tag")
369 tag_time = serializable_property("tag_time",
370 "The creation timestamp of the tag. As the number of seconds since the epoch")
371 tag_timezone = serializable_property("tag_timezone",
372 "The timezone that tag_time is in.")
373 message = serializable_property("message", "The message attached to this tag")
376 def parse_tree(text):
381 mode_end = text.index(' ', count)
382 mode = int(text[count:mode_end], 8)
384 name_end = text.index('\0', mode_end)
385 name = text[mode_end+1:name_end]
389 sha = text[name_end+1:count]
391 ret[name] = (mode, sha_to_hex(sha))
397 """A Git tree object"""
403 super(Tree, self).__init__()
405 self._needs_parsing = False
406 self._needs_serialization = True
409 def from_file(cls, filename):
410 tree = ShaFile.from_file(filename)
411 if tree._type != cls._type:
412 raise NotTreeError(filename)
415 def __contains__(self, name):
416 self._ensure_parsed()
417 return name in self._entries
419 def __getitem__(self, name):
420 self._ensure_parsed()
421 return self._entries[name]
423 def __setitem__(self, name, value):
424 assert isinstance(value, tuple)
425 assert len(value) == 2
426 self._ensure_parsed()
427 self._entries[name] = value
428 self._needs_serialization = True
430 def __delitem__(self, name):
431 self._ensure_parsed()
432 del self._entries[name]
433 self._needs_serialization = True
436 self._ensure_parsed()
437 return len(self._entries)
439 def add(self, mode, name, hexsha):
440 assert type(mode) == int
441 assert type(name) == str
442 assert type(hexsha) == str
443 self._ensure_parsed()
444 self._entries[name] = mode, hexsha
445 self._needs_serialization = True
448 """Return a list of tuples describing the tree entries"""
449 self._ensure_parsed()
450 # The order of this is different from iteritems() for historical reasons
451 return [(mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
454 def cmp_entry((name1, value1), (name2, value2)):
455 if stat.S_ISDIR(value1[0]):
457 if stat.S_ISDIR(value2[0]):
459 return cmp(name1, name2)
460 self._ensure_parsed()
461 for name, entry in sorted(self._entries.iteritems(), cmp=cmp_entry):
462 yield name, entry[0], entry[1]
464 def _parse_text(self):
465 """Grab the entries in the tree"""
466 self._entries = parse_tree(self._text)
467 self._needs_parsing = False
471 for name, mode, hexsha in self.iteritems():
472 f.write("%04o %s\0%s" % (mode, name, hex_to_sha(hexsha)))
473 self._text = f.getvalue()
474 self._needs_serialization = False
476 def as_pretty_string(self):
478 for name, mode, hexsha in self.iteritems():
479 if mode & stat.S_IFDIR:
483 text += "%04o %s %s\t%s\n" % (mode, kind, hexsha, name)
487 def parse_timezone(text):
489 signum = (offset < 0) and -1 or 1
491 hours = int(offset / 100)
492 minutes = (offset % 100)
493 return signum * (hours * 3600 + minutes * 60)
496 def format_timezone(offset):
498 raise ValueError("Unable to handle non-minute offset.")
499 sign = (offset < 0) and '-' or '+'
501 return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
504 class Commit(ShaFile):
505 """A git commit object"""
511 super(Commit, self).__init__()
513 self._encoding = None
514 self._needs_parsing = False
515 self._needs_serialization = True
519 def from_file(cls, filename):
520 commit = ShaFile.from_file(filename)
521 if commit._type != cls._type:
522 raise NotCommitError(filename)
525 def _parse_text(self):
529 f = StringIO(self._text)
533 # Empty line indicates end of headers
535 (field, value) = l.split(" ", 1)
538 elif field == PARENT_ID:
539 self._parents.append(value)
540 elif field == AUTHOR_ID:
541 self._author, timetext, timezonetext = value.rsplit(" ", 2)
542 self._author_time = int(timetext)
543 self._author_timezone = parse_timezone(timezonetext)
544 elif field == COMMITTER_ID:
545 self._committer, timetext, timezonetext = value.rsplit(" ", 2)
546 self._commit_time = int(timetext)
547 self._commit_timezone = parse_timezone(timezonetext)
548 elif field == ENCODING_ID:
549 self._encoding = value
551 self._extra.append((field, value))
552 self._message = f.read()
553 self._needs_parsing = False
557 f.write("%s %s\n" % (TREE_ID, self._tree))
558 for p in self._parents:
559 f.write("%s %s\n" % (PARENT_ID, p))
560 f.write("%s %s %s %s\n" % (AUTHOR_ID, self._author, str(self._author_time), format_timezone(self._author_timezone)))
561 f.write("%s %s %s %s\n" % (COMMITTER_ID, self._committer, str(self._commit_time), format_timezone(self._commit_timezone)))
563 f.write("%s %s\n" % (ENCODING_ID, self.encoding))
564 for k, v in self.extra:
565 if "\n" in k or "\n" in v:
566 raise AssertionError("newline in extra data: %r -> %r" % (k, v))
567 f.write("%s %s\n" % (k, v))
568 f.write("\n") # There must be a new line after the headers
569 f.write(self._message)
570 self._text = f.getvalue()
571 self._needs_serialization = False
573 tree = serializable_property("tree", "Tree that is the state of this commit")
575 def get_parents(self):
576 """Return a list of parents of this commit."""
577 self._ensure_parsed()
580 def set_parents(self, value):
581 """Return a list of parents of this commit."""
582 self._ensure_parsed()
583 self._needs_serialization = True
584 self._parents = value
586 parents = property(get_parents, set_parents)
589 """Return extra settings of this commit."""
590 self._ensure_parsed()
593 extra = property(get_extra)
595 author = serializable_property("author",
596 "The name of the author of the commit")
598 committer = serializable_property("committer",
599 "The name of the committer of the commit")
601 message = serializable_property("message",
602 "The commit message")
604 commit_time = serializable_property("commit_time",
605 "The timestamp of the commit. As the number of seconds since the epoch.")
607 commit_timezone = serializable_property("commit_timezone",
608 "The zone the commit time is in")
610 author_time = serializable_property("author_time",
611 "The timestamp the commit was written. as the number of seconds since the epoch.")
613 author_timezone = serializable_property("author_timezone",
614 "Returns the zone the author time is in.")
616 encoding = serializable_property("encoding",
617 "Encoding of the commit message.")
633 # 5 Is reserved for further expansion
637 # Try to import C versions
638 from dulwich._objects import parse_tree