objects.py 51 KB

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