objects.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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>
  4. #
  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.
  9. #
  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.
  14. #
  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,
  18. # MA 02110-1301, USA.
  19. """Access to base git objects."""
  20. import binascii
  21. from cStringIO import (
  22. StringIO,
  23. )
  24. import mmap
  25. import os
  26. import stat
  27. import zlib
  28. from dulwich.errors import (
  29. ChecksumMismatch,
  30. NotBlobError,
  31. NotCommitError,
  32. NotTagError,
  33. NotTreeError,
  34. ObjectFormatException,
  35. )
  36. from dulwich.file import GitFile
  37. from dulwich.misc import (
  38. make_sha,
  39. )
  40. # Header fields for commits
  41. _TREE_HEADER = "tree"
  42. _PARENT_HEADER = "parent"
  43. _AUTHOR_HEADER = "author"
  44. _COMMITTER_HEADER = "committer"
  45. _ENCODING_HEADER = "encoding"
  46. # Header fields for objects
  47. _OBJECT_HEADER = "object"
  48. _TYPE_HEADER = "type"
  49. _TAG_HEADER = "tag"
  50. _TAGGER_HEADER = "tagger"
  51. S_IFGITLINK = 0160000
  52. def S_ISGITLINK(m):
  53. return (stat.S_IFMT(m) == S_IFGITLINK)
  54. def _decompress(string):
  55. dcomp = zlib.decompressobj()
  56. dcomped = dcomp.decompress(string)
  57. dcomped += dcomp.flush()
  58. return dcomped
  59. def sha_to_hex(sha):
  60. """Takes a string and returns the hex of the sha within"""
  61. hexsha = binascii.hexlify(sha)
  62. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
  63. return hexsha
  64. def hex_to_sha(hex):
  65. """Takes a hex sha and returns a binary sha"""
  66. assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
  67. return binascii.unhexlify(hex)
  68. def hex_to_filename(path, hex):
  69. """Takes a hex sha and returns its filename relative to the given path."""
  70. dir = hex[:2]
  71. file = hex[2:]
  72. # Check from object dir
  73. return os.path.join(path, dir, file)
  74. def filename_to_hex(filename):
  75. """Takes an object filename and returns its corresponding hex sha."""
  76. # grab the last (up to) two path components
  77. names = filename.rsplit(os.path.sep, 2)[-2:]
  78. errmsg = "Invalid object filename: %s" % filename
  79. assert len(names) == 2, errmsg
  80. base, rest = names
  81. assert len(base) == 2 and len(rest) == 38, errmsg
  82. hex = base + rest
  83. hex_to_sha(hex)
  84. return hex
  85. def object_header(num_type, length):
  86. """Return an object header for the given numeric type and text length."""
  87. return "%s %d\0" % (object_class(num_type).type_name, length)
  88. def serializable_property(name, docstring=None):
  89. def set(obj, value):
  90. obj._ensure_parsed()
  91. setattr(obj, "_"+name, value)
  92. obj._needs_serialization = True
  93. def get(obj):
  94. obj._ensure_parsed()
  95. return getattr(obj, "_"+name)
  96. return property(get, set, doc=docstring)
  97. def object_class(type):
  98. """Get the object class corresponding to the given type.
  99. :param type: Either a type name string or a numeric type.
  100. :return: The ShaFile subclass corresponding to the given type, or None if
  101. type is not a valid type name/number.
  102. """
  103. return _TYPE_MAP.get(type, None)
  104. def check_hexsha(hex, error_msg):
  105. try:
  106. hex_to_sha(hex)
  107. except (TypeError, AssertionError):
  108. raise ObjectFormatException("%s %s" % (error_msg, hex))
  109. def check_identity(identity, error_msg):
  110. email_start = identity.find("<")
  111. email_end = identity.find(">")
  112. if (email_start < 0 or email_end < 0 or email_end <= email_start
  113. or identity.find("<", email_start + 1) >= 0
  114. or identity.find(">", email_end + 1) >= 0
  115. or not identity.endswith(">")):
  116. raise ObjectFormatException(error_msg)
  117. class FixedSha(object):
  118. """SHA object that behaves like hashlib's but is given a fixed value."""
  119. def __init__(self, hexsha):
  120. self._hexsha = hexsha
  121. self._sha = hex_to_sha(hexsha)
  122. def digest(self):
  123. return self._sha
  124. def hexdigest(self):
  125. return self._hexsha
  126. class ShaFile(object):
  127. """A git SHA file."""
  128. @staticmethod
  129. def _parse_legacy_object_header(magic, f):
  130. """Parse a legacy object, creating it but not reading the file."""
  131. bufsize = 1024
  132. decomp = zlib.decompressobj()
  133. header = decomp.decompress(magic)
  134. start = 0
  135. end = -1
  136. while end < 0:
  137. header += decomp.decompress(f.read(bufsize))
  138. end = header.find("\0", start)
  139. start = len(header)
  140. header = header[:end]
  141. type_name, size = header.split(" ", 1)
  142. size = int(size) # sanity check
  143. obj_class = object_class(type_name)
  144. if not obj_class:
  145. raise ObjectFormatException("Not a known type: %s" % type_name)
  146. return obj_class()
  147. def _parse_legacy_object(self, f):
  148. """Parse a legacy object, setting the raw string."""
  149. size = os.path.getsize(f.name)
  150. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  151. try:
  152. text = _decompress(map)
  153. finally:
  154. map.close()
  155. header_end = text.find('\0')
  156. if header_end < 0:
  157. raise ObjectFormatException("Invalid object header")
  158. self.set_raw_string(text[header_end+1:])
  159. def as_legacy_object_chunks(self):
  160. compobj = zlib.compressobj()
  161. yield compobj.compress(self._header())
  162. for chunk in self.as_raw_chunks():
  163. yield compobj.compress(chunk)
  164. yield compobj.flush()
  165. def as_legacy_object(self):
  166. return "".join(self.as_legacy_object_chunks())
  167. def as_raw_chunks(self):
  168. if self._needs_parsing:
  169. self._ensure_parsed()
  170. elif self._needs_serialization:
  171. self._chunked_text = self._serialize()
  172. return self._chunked_text
  173. def as_raw_string(self):
  174. return "".join(self.as_raw_chunks())
  175. def __str__(self):
  176. return self.as_raw_string()
  177. def __hash__(self):
  178. return hash(self.id)
  179. def as_pretty_string(self):
  180. return self.as_raw_string()
  181. def _ensure_parsed(self):
  182. if self._needs_parsing:
  183. if not self._chunked_text:
  184. if self._file is not None:
  185. self._parse_file(self._file)
  186. elif self._path is not None:
  187. self._parse_path()
  188. else:
  189. raise AssertionError(
  190. "ShaFile needs either text or filename")
  191. self._deserialize(self._chunked_text)
  192. self._needs_parsing = False
  193. def set_raw_string(self, text):
  194. if type(text) != str:
  195. raise TypeError(text)
  196. self.set_raw_chunks([text])
  197. def set_raw_chunks(self, chunks):
  198. self._chunked_text = chunks
  199. self._deserialize(chunks)
  200. self._sha = None
  201. self._needs_parsing = False
  202. self._needs_serialization = False
  203. @staticmethod
  204. def _parse_object_header(magic, f):
  205. """Parse a new style object, creating it but not reading the file."""
  206. num_type = (ord(magic[0]) >> 4) & 7
  207. obj_class = object_class(num_type)
  208. if not obj_class:
  209. raise ObjectFormatException("Not a known type: %d" % num_type)
  210. return obj_class()
  211. def _parse_object(self, f):
  212. """Parse a new style object, setting self._text."""
  213. size = os.path.getsize(f.name)
  214. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  215. try:
  216. # skip type and size; type must have already been determined, and we
  217. # trust zlib to fail if it's otherwise corrupted
  218. byte = ord(map[0])
  219. used = 1
  220. while (byte & 0x80) != 0:
  221. byte = ord(map[used])
  222. used += 1
  223. raw = map[used:]
  224. self.set_raw_string(_decompress(raw))
  225. finally:
  226. map.close()
  227. @classmethod
  228. def _is_legacy_object(cls, magic):
  229. b0, b1 = map(ord, magic)
  230. word = (b0 << 8) + b1
  231. return b0 == 0x78 and (word % 31) == 0
  232. @classmethod
  233. def _parse_file_header(cls, f):
  234. magic = f.read(2)
  235. if cls._is_legacy_object(magic):
  236. return cls._parse_legacy_object_header(magic, f)
  237. else:
  238. return cls._parse_object_header(magic, f)
  239. def __init__(self):
  240. """Don't call this directly"""
  241. self._sha = None
  242. self._path = None
  243. self._file = None
  244. self._chunked_text = []
  245. self._needs_parsing = False
  246. self._needs_serialization = True
  247. def _deserialize(self, chunks):
  248. raise NotImplementedError(self._deserialize)
  249. def _serialize(self):
  250. raise NotImplementedError(self._serialize)
  251. def _parse_path(self):
  252. f = GitFile(self._path, 'rb')
  253. try:
  254. self._parse_file(f)
  255. finally:
  256. f.close()
  257. def _parse_file(self, f):
  258. magic = f.read(2)
  259. if self._is_legacy_object(magic):
  260. self._parse_legacy_object(f)
  261. else:
  262. self._parse_object(f)
  263. @classmethod
  264. def from_path(cls, path):
  265. f = GitFile(path, 'rb')
  266. try:
  267. obj = cls.from_file(f)
  268. obj._path = path
  269. obj._sha = FixedSha(filename_to_hex(path))
  270. obj._file = None
  271. return obj
  272. finally:
  273. f.close()
  274. @classmethod
  275. def from_file(cls, f):
  276. """Get the contents of a SHA file on disk."""
  277. try:
  278. obj = cls._parse_file_header(f)
  279. obj._sha = None
  280. obj._needs_parsing = True
  281. obj._needs_serialization = True
  282. obj._file = f
  283. return obj
  284. except (IndexError, ValueError), e:
  285. raise ObjectFormatException("invalid object header")
  286. @staticmethod
  287. def from_raw_string(type_num, string):
  288. """Creates an object of the indicated type from the raw string given.
  289. :param type_num: The numeric type of the object.
  290. :param string: The raw uncompressed contents.
  291. """
  292. obj = object_class(type_num)()
  293. obj.set_raw_string(string)
  294. return obj
  295. @staticmethod
  296. def from_raw_chunks(type_num, chunks):
  297. """Creates an object of the indicated type from the raw chunks given.
  298. :param type_num: The numeric type of the object.
  299. :param chunks: An iterable of the raw uncompressed contents.
  300. """
  301. obj = object_class(type_num)()
  302. obj.set_raw_chunks(chunks)
  303. return obj
  304. @classmethod
  305. def from_string(cls, string):
  306. """Create a ShaFile from a string."""
  307. obj = cls()
  308. obj.set_raw_string(string)
  309. return obj
  310. def _check_has_member(self, member, error_msg):
  311. """Check that the object has a given member variable.
  312. :param member: the member variable to check for
  313. :param error_msg: the message for an error if the member is missing
  314. :raise ObjectFormatException: with the given error_msg if member is
  315. missing or is None
  316. """
  317. if getattr(self, member, None) is None:
  318. raise ObjectFormatException(error_msg)
  319. def check(self):
  320. """Check this object for internal consistency.
  321. :raise ObjectFormatException: if the object is malformed in some way
  322. :raise ChecksumMismatch: if the object was created with a SHA that does
  323. not match its contents
  324. """
  325. # TODO: if we find that error-checking during object parsing is a
  326. # performance bottleneck, those checks should be moved to the class's
  327. # check() method during optimization so we can still check the object
  328. # when necessary.
  329. old_sha = self.id
  330. try:
  331. self._deserialize(self.as_raw_chunks())
  332. self._sha = None
  333. new_sha = self.id
  334. except Exception, e:
  335. raise ObjectFormatException(e)
  336. if old_sha != new_sha:
  337. raise ChecksumMismatch(new_sha, old_sha)
  338. def _header(self):
  339. return object_header(self.type, self.raw_length())
  340. def raw_length(self):
  341. """Returns the length of the raw string of this object."""
  342. ret = 0
  343. for chunk in self.as_raw_chunks():
  344. ret += len(chunk)
  345. return ret
  346. def _make_sha(self):
  347. ret = make_sha()
  348. ret.update(self._header())
  349. for chunk in self.as_raw_chunks():
  350. ret.update(chunk)
  351. return ret
  352. def sha(self):
  353. """The SHA1 object that is the name of this object."""
  354. if self._sha is None:
  355. # this is a local because as_raw_chunks() overwrites self._sha
  356. new_sha = make_sha()
  357. new_sha.update(self._header())
  358. for chunk in self.as_raw_chunks():
  359. new_sha.update(chunk)
  360. self._sha = new_sha
  361. return self._sha
  362. @property
  363. def id(self):
  364. return self.sha().hexdigest()
  365. def get_type(self):
  366. return self.type_num
  367. def set_type(self, type):
  368. self.type_num = type
  369. # DEPRECATED: use type_num or type_name as needed.
  370. type = property(get_type, set_type)
  371. def __repr__(self):
  372. return "<%s %s>" % (self.__class__.__name__, self.id)
  373. def __ne__(self, other):
  374. return self.id != other.id
  375. def __eq__(self, other):
  376. """Return true if the sha of the two objects match.
  377. The __le__ etc methods aren't overriden as they make no sense,
  378. certainly at this level.
  379. """
  380. return self.id == other.id
  381. class Blob(ShaFile):
  382. """A Git Blob object."""
  383. type_name = 'blob'
  384. type_num = 3
  385. def __init__(self):
  386. super(Blob, self).__init__()
  387. self._chunked_text = []
  388. self._needs_parsing = False
  389. self._needs_serialization = False
  390. def _get_data(self):
  391. return self.as_raw_string()
  392. def _set_data(self, data):
  393. self.set_raw_string(data)
  394. data = property(_get_data, _set_data,
  395. "The text contained within the blob object.")
  396. def _get_chunked(self):
  397. self._ensure_parsed()
  398. return self._chunked_text
  399. def _set_chunked(self, chunks):
  400. self._chunked_text = chunks
  401. def _serialize(self):
  402. if not self._chunked_text:
  403. self._ensure_parsed()
  404. self._needs_serialization = False
  405. return self._chunked_text
  406. def _deserialize(self, chunks):
  407. self._chunked_text = chunks
  408. chunked = property(_get_chunked, _set_chunked,
  409. "The text within the blob object, as chunks (not necessarily lines).")
  410. @classmethod
  411. def from_path(cls, path):
  412. blob = ShaFile.from_path(path)
  413. if not isinstance(blob, cls):
  414. raise NotBlobError(path)
  415. return blob
  416. def check(self):
  417. """Check this object for internal consistency.
  418. :raise ObjectFormatException: if the object is malformed in some way
  419. """
  420. super(Blob, self).check()
  421. def _parse_tag_or_commit(text):
  422. """Parse tag or commit text.
  423. :param text: the raw text of the tag or commit object.
  424. :yield: tuples of (field, value), one per header line, in the order read
  425. from the text, possibly including duplicates. Includes a field named
  426. None for the freeform tag/commit text.
  427. """
  428. f = StringIO(text)
  429. for l in f:
  430. l = l.rstrip("\n")
  431. if l == "":
  432. # Empty line indicates end of headers
  433. break
  434. yield l.split(" ", 1)
  435. yield (None, f.read())
  436. f.close()
  437. def parse_tag(text):
  438. return _parse_tag_or_commit(text)
  439. class Tag(ShaFile):
  440. """A Git Tag object."""
  441. type_name = 'tag'
  442. type_num = 4
  443. def __init__(self):
  444. super(Tag, self).__init__()
  445. self._tag_timezone_neg_utc = False
  446. @classmethod
  447. def from_path(cls, filename):
  448. tag = ShaFile.from_path(filename)
  449. if not isinstance(tag, cls):
  450. raise NotTagError(filename)
  451. return tag
  452. def check(self):
  453. """Check this object for internal consistency.
  454. :raise ObjectFormatException: if the object is malformed in some way
  455. """
  456. super(Tag, self).check()
  457. self._check_has_member("_object_sha", "missing object sha")
  458. self._check_has_member("_object_class", "missing object type")
  459. self._check_has_member("_name", "missing tag name")
  460. if not self._name:
  461. raise ObjectFormatException("empty tag name")
  462. check_hexsha(self._object_sha, "invalid object sha")
  463. if getattr(self, "_tagger", None):
  464. check_identity(self._tagger, "invalid tagger")
  465. last = None
  466. for field, _ in parse_tag("".join(self._chunked_text)):
  467. if field == _OBJECT_HEADER and last is not None:
  468. raise ObjectFormatException("unexpected object")
  469. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  470. raise ObjectFormatException("unexpected type")
  471. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  472. raise ObjectFormatException("unexpected tag name")
  473. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  474. raise ObjectFormatException("unexpected tagger")
  475. last = field
  476. def _serialize(self):
  477. chunks = []
  478. chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
  479. chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
  480. chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
  481. if self._tagger:
  482. if self._tag_time is None:
  483. chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
  484. else:
  485. chunks.append("%s %s %d %s\n" % (
  486. _TAGGER_HEADER, self._tagger, self._tag_time,
  487. format_timezone(self._tag_timezone,
  488. self._tag_timezone_neg_utc)))
  489. chunks.append("\n") # To close headers
  490. chunks.append(self._message)
  491. return chunks
  492. def _deserialize(self, chunks):
  493. """Grab the metadata attached to the tag"""
  494. self._tagger = None
  495. for field, value in parse_tag("".join(chunks)):
  496. if field == _OBJECT_HEADER:
  497. self._object_sha = value
  498. elif field == _TYPE_HEADER:
  499. obj_class = object_class(value)
  500. if not obj_class:
  501. raise ObjectFormatException("Not a known type: %s" % value)
  502. self._object_class = obj_class
  503. elif field == _TAG_HEADER:
  504. self._name = value
  505. elif field == _TAGGER_HEADER:
  506. try:
  507. sep = value.index("> ")
  508. except ValueError:
  509. self._tagger = value
  510. self._tag_time = None
  511. self._tag_timezone = None
  512. self._tag_timezone_neg_utc = False
  513. else:
  514. self._tagger = value[0:sep+1]
  515. try:
  516. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  517. self._tag_time = int(timetext)
  518. self._tag_timezone, self._tag_timezone_neg_utc = \
  519. parse_timezone(timezonetext)
  520. except ValueError, e:
  521. raise ObjectFormatException(e)
  522. elif field is None:
  523. self._message = value
  524. else:
  525. raise ObjectFormatException("Unknown field %s" % field)
  526. def _get_object(self):
  527. """Get the object pointed to by this tag.
  528. :return: tuple of (object class, sha).
  529. """
  530. self._ensure_parsed()
  531. return (self._object_class, self._object_sha)
  532. def _set_object(self, value):
  533. self._ensure_parsed()
  534. (self._object_class, self._object_sha) = value
  535. self._needs_serialization = True
  536. object = property(_get_object, _set_object)
  537. name = serializable_property("name", "The name of this tag")
  538. tagger = serializable_property("tagger",
  539. "Returns the name of the person who created this tag")
  540. tag_time = serializable_property("tag_time",
  541. "The creation timestamp of the tag. As the number of seconds since the epoch")
  542. tag_timezone = serializable_property("tag_timezone",
  543. "The timezone that tag_time is in.")
  544. message = serializable_property("message", "The message attached to this tag")
  545. def parse_tree(text):
  546. """Parse a tree text.
  547. :param text: Serialized text to parse
  548. :yields: tuples of (name, mode, sha)
  549. """
  550. count = 0
  551. l = len(text)
  552. while count < l:
  553. mode_end = text.index(' ', count)
  554. mode = int(text[count:mode_end], 8)
  555. name_end = text.index('\0', mode_end)
  556. name = text[mode_end+1:name_end]
  557. count = name_end+21
  558. sha = text[name_end+1:count]
  559. yield (name, mode, sha_to_hex(sha))
  560. def serialize_tree(items):
  561. """Serialize the items in a tree to a text.
  562. :param items: Sorted iterable over (name, mode, sha) tuples
  563. :return: Serialized tree text as chunks
  564. """
  565. for name, mode, hexsha in items:
  566. yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  567. def sorted_tree_items(entries):
  568. """Iterate over a tree entries dictionary in the order in which
  569. the items would be serialized.
  570. :param entries: Dictionary mapping names to (mode, sha) tuples
  571. :return: Iterator over (name, mode, sha)
  572. """
  573. for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
  574. yield name, entry[0], entry[1]
  575. def cmp_entry((name1, value1), (name2, value2)):
  576. """Compare two tree entries."""
  577. if stat.S_ISDIR(value1[0]):
  578. name1 += "/"
  579. if stat.S_ISDIR(value2[0]):
  580. name2 += "/"
  581. return cmp(name1, name2)
  582. class Tree(ShaFile):
  583. """A Git tree object"""
  584. type_name = 'tree'
  585. type_num = 2
  586. def __init__(self):
  587. super(Tree, self).__init__()
  588. self._entries = {}
  589. @classmethod
  590. def from_path(cls, filename):
  591. tree = ShaFile.from_path(filename)
  592. if not isinstance(tree, cls):
  593. raise NotTreeError(filename)
  594. return tree
  595. def __contains__(self, name):
  596. self._ensure_parsed()
  597. return name in self._entries
  598. def __getitem__(self, name):
  599. self._ensure_parsed()
  600. return self._entries[name]
  601. def __setitem__(self, name, value):
  602. assert isinstance(value, tuple)
  603. assert len(value) == 2
  604. self._ensure_parsed()
  605. self._entries[name] = value
  606. self._needs_serialization = True
  607. def __delitem__(self, name):
  608. self._ensure_parsed()
  609. del self._entries[name]
  610. self._needs_serialization = True
  611. def __len__(self):
  612. self._ensure_parsed()
  613. return len(self._entries)
  614. def __iter__(self):
  615. self._ensure_parsed()
  616. return iter(self._entries)
  617. def add(self, mode, name, hexsha):
  618. assert type(mode) == int
  619. assert type(name) == str
  620. assert type(hexsha) == str
  621. self._ensure_parsed()
  622. self._entries[name] = mode, hexsha
  623. self._needs_serialization = True
  624. def entries(self):
  625. """Return a list of tuples describing the tree entries"""
  626. self._ensure_parsed()
  627. # The order of this is different from iteritems() for historical
  628. # reasons
  629. return [
  630. (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
  631. def iteritems(self):
  632. """Iterate over entries in the order in which they would be serialized.
  633. :return: Iterator over (name, mode, sha) tuples
  634. """
  635. self._ensure_parsed()
  636. return sorted_tree_items(self._entries)
  637. def _deserialize(self, chunks):
  638. """Grab the entries in the tree"""
  639. try:
  640. parsed_entries = parse_tree("".join(chunks))
  641. except ValueError, e:
  642. raise ObjectFormatException(e)
  643. # TODO: list comprehension is for efficiency in the common (small) case;
  644. # if memory efficiency in the large case is a concern, use a genexp.
  645. self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
  646. def check(self):
  647. """Check this object for internal consistency.
  648. :raise ObjectFormatException: if the object is malformed in some way
  649. """
  650. super(Tree, self).check()
  651. last = None
  652. allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
  653. stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
  654. # TODO: optionally exclude as in git fsck --strict
  655. stat.S_IFREG | 0664)
  656. for name, mode, sha in parse_tree("".join(self._chunked_text)):
  657. check_hexsha(sha, 'invalid sha %s' % sha)
  658. if '/' in name or name in ('', '.', '..'):
  659. raise ObjectFormatException('invalid name %s' % name)
  660. if mode not in allowed_modes:
  661. raise ObjectFormatException('invalid mode %06o' % mode)
  662. entry = (name, (mode, sha))
  663. if last:
  664. if cmp_entry(last, entry) > 0:
  665. raise ObjectFormatException('entries not sorted')
  666. if name == last[0]:
  667. raise ObjectFormatException('duplicate entry %s' % name)
  668. last = entry
  669. def _serialize(self):
  670. return list(serialize_tree(self.iteritems()))
  671. def as_pretty_string(self):
  672. text = []
  673. for name, mode, hexsha in self.iteritems():
  674. if mode & stat.S_IFDIR:
  675. kind = "tree"
  676. else:
  677. kind = "blob"
  678. text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
  679. return "".join(text)
  680. def parse_timezone(text):
  681. offset = int(text)
  682. negative_utc = (offset == 0 and text[0] == '-')
  683. signum = (offset < 0) and -1 or 1
  684. offset = abs(offset)
  685. hours = int(offset / 100)
  686. minutes = (offset % 100)
  687. return signum * (hours * 3600 + minutes * 60), negative_utc
  688. def format_timezone(offset, negative_utc=False):
  689. if offset % 60 != 0:
  690. raise ValueError("Unable to handle non-minute offset.")
  691. if offset < 0 or (offset == 0 and negative_utc):
  692. sign = '-'
  693. else:
  694. sign = '+'
  695. offset = abs(offset)
  696. return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
  697. def parse_commit(text):
  698. return _parse_tag_or_commit(text)
  699. class Commit(ShaFile):
  700. """A git commit object"""
  701. type_name = 'commit'
  702. type_num = 1
  703. def __init__(self):
  704. super(Commit, self).__init__()
  705. self._parents = []
  706. self._encoding = None
  707. self._extra = {}
  708. self._author_timezone_neg_utc = False
  709. self._commit_timezone_neg_utc = False
  710. @classmethod
  711. def from_path(cls, path):
  712. commit = ShaFile.from_path(path)
  713. if not isinstance(commit, cls):
  714. raise NotCommitError(path)
  715. return commit
  716. def _deserialize(self, chunks):
  717. self._parents = []
  718. self._extra = []
  719. self._author = None
  720. for field, value in parse_commit("".join(self._chunked_text)):
  721. if field == _TREE_HEADER:
  722. self._tree = value
  723. elif field == _PARENT_HEADER:
  724. self._parents.append(value)
  725. elif field == _AUTHOR_HEADER:
  726. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  727. self._author_time = int(timetext)
  728. self._author_timezone, self._author_timezone_neg_utc =\
  729. parse_timezone(timezonetext)
  730. elif field == _COMMITTER_HEADER:
  731. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  732. self._commit_time = int(timetext)
  733. self._commit_timezone, self._commit_timezone_neg_utc =\
  734. parse_timezone(timezonetext)
  735. elif field == _ENCODING_HEADER:
  736. self._encoding = value
  737. elif field is None:
  738. self._message = value
  739. else:
  740. self._extra.append((field, value))
  741. def check(self):
  742. """Check this object for internal consistency.
  743. :raise ObjectFormatException: if the object is malformed in some way
  744. """
  745. super(Commit, self).check()
  746. self._check_has_member("_tree", "missing tree")
  747. self._check_has_member("_author", "missing author")
  748. self._check_has_member("_committer", "missing committer")
  749. # times are currently checked when set
  750. for parent in self._parents:
  751. check_hexsha(parent, "invalid parent sha")
  752. check_hexsha(self._tree, "invalid tree sha")
  753. check_identity(self._author, "invalid author")
  754. check_identity(self._committer, "invalid committer")
  755. last = None
  756. for field, _ in parse_commit("".join(self._chunked_text)):
  757. if field == _TREE_HEADER and last is not None:
  758. raise ObjectFormatException("unexpected tree")
  759. elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
  760. _TREE_HEADER):
  761. raise ObjectFormatException("unexpected parent")
  762. elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
  763. _PARENT_HEADER):
  764. raise ObjectFormatException("unexpected author")
  765. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  766. raise ObjectFormatException("unexpected committer")
  767. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  768. raise ObjectFormatException("unexpected encoding")
  769. last = field
  770. # TODO: optionally check for duplicate parents
  771. def _serialize(self):
  772. chunks = []
  773. chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
  774. for p in self._parents:
  775. chunks.append("%s %s\n" % (_PARENT_HEADER, p))
  776. chunks.append("%s %s %s %s\n" % (
  777. _AUTHOR_HEADER, self._author, str(self._author_time),
  778. format_timezone(self._author_timezone,
  779. self._author_timezone_neg_utc)))
  780. chunks.append("%s %s %s %s\n" % (
  781. _COMMITTER_HEADER, self._committer, str(self._commit_time),
  782. format_timezone(self._commit_timezone,
  783. self._commit_timezone_neg_utc)))
  784. if self.encoding:
  785. chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
  786. for k, v in self.extra:
  787. if "\n" in k or "\n" in v:
  788. raise AssertionError("newline in extra data: %r -> %r" % (k, v))
  789. chunks.append("%s %s\n" % (k, v))
  790. chunks.append("\n") # There must be a new line after the headers
  791. chunks.append(self._message)
  792. return chunks
  793. tree = serializable_property("tree", "Tree that is the state of this commit")
  794. def _get_parents(self):
  795. """Return a list of parents of this commit."""
  796. self._ensure_parsed()
  797. return self._parents
  798. def _set_parents(self, value):
  799. """Set a list of parents of this commit."""
  800. self._ensure_parsed()
  801. self._needs_serialization = True
  802. self._parents = value
  803. parents = property(_get_parents, _set_parents)
  804. def _get_extra(self):
  805. """Return extra settings of this commit."""
  806. self._ensure_parsed()
  807. return self._extra
  808. extra = property(_get_extra)
  809. author = serializable_property("author",
  810. "The name of the author of the commit")
  811. committer = serializable_property("committer",
  812. "The name of the committer of the commit")
  813. message = serializable_property("message",
  814. "The commit message")
  815. commit_time = serializable_property("commit_time",
  816. "The timestamp of the commit. As the number of seconds since the epoch.")
  817. commit_timezone = serializable_property("commit_timezone",
  818. "The zone the commit time is in")
  819. author_time = serializable_property("author_time",
  820. "The timestamp the commit was written. as the number of seconds since the epoch.")
  821. author_timezone = serializable_property("author_timezone",
  822. "Returns the zone the author time is in.")
  823. encoding = serializable_property("encoding",
  824. "Encoding of the commit message.")
  825. OBJECT_CLASSES = (
  826. Commit,
  827. Tree,
  828. Blob,
  829. Tag,
  830. )
  831. _TYPE_MAP = {}
  832. for cls in OBJECT_CLASSES:
  833. _TYPE_MAP[cls.type_name] = cls
  834. _TYPE_MAP[cls.type_num] = cls
  835. # Hold on to the pure-python implementations for testing
  836. _parse_tree_py = parse_tree
  837. _sorted_tree_items_py = sorted_tree_items
  838. try:
  839. # Try to import C versions
  840. from dulwich._objects import parse_tree, sorted_tree_items
  841. except ImportError:
  842. pass