objects.py 47 KB

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