2
0

objects.py 41 KB

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