objects.py 45 KB

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