objects.py 46 KB

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