objects.py 36 KB

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