objects.py 39 KB

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