objects.py 33 KB

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