objects.py 34 KB

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