objects.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265
  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. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as published by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Access to base git objects."""
  23. __all__ = [
  24. "BEGIN_PGP_SIGNATURE",
  25. "BEGIN_SSH_SIGNATURE",
  26. "MAX_TIME",
  27. "OBJECT_CLASSES",
  28. "SIGNATURE_PGP",
  29. "SIGNATURE_SSH",
  30. "S_IFGITLINK",
  31. "S_ISGITLINK",
  32. "ZERO_SHA",
  33. "Blob",
  34. "Commit",
  35. "EmptyFileException",
  36. "FixedSha",
  37. "ObjectID",
  38. "RawObjectID",
  39. "ShaFile",
  40. "SubmoduleEncountered",
  41. "Tag",
  42. "Tree",
  43. "TreeEntry",
  44. "check_hexsha",
  45. "check_identity",
  46. "check_time",
  47. "filename_to_hex",
  48. "format_time_entry",
  49. "format_timezone",
  50. "git_line",
  51. "hex_to_filename",
  52. "hex_to_sha",
  53. "is_blob",
  54. "is_commit",
  55. "is_tag",
  56. "is_tree",
  57. "key_entry",
  58. "key_entry_name_order",
  59. "object_class",
  60. "object_header",
  61. "parse_commit",
  62. "parse_time_entry",
  63. "parse_timezone",
  64. "parse_tree",
  65. "pretty_format_tree_entry",
  66. "serializable_property",
  67. "serialize_tree",
  68. "sha_to_hex",
  69. "sorted_tree_items",
  70. "valid_hexsha",
  71. ]
  72. import binascii
  73. import os
  74. import posixpath
  75. import stat
  76. import sys
  77. import zlib
  78. from collections.abc import Callable, Iterable, Iterator, Sequence
  79. from hashlib import sha1
  80. from io import BufferedIOBase, BytesIO
  81. from typing import (
  82. IO,
  83. TYPE_CHECKING,
  84. NamedTuple,
  85. TypeVar,
  86. )
  87. if sys.version_info >= (3, 11):
  88. from typing import Self
  89. else:
  90. from typing_extensions import Self
  91. from typing import NewType, TypeGuard
  92. from . import replace_me
  93. from .errors import (
  94. ChecksumMismatch,
  95. FileFormatException,
  96. NotBlobError,
  97. NotCommitError,
  98. NotTagError,
  99. NotTreeError,
  100. ObjectFormatException,
  101. )
  102. from .file import GitFile
  103. if TYPE_CHECKING:
  104. from _hashlib import HASH
  105. from .file import _GitFile
  106. # Zero SHA constants for backward compatibility
  107. ZERO_SHA = b"0" * 40 # SHA1 - kept for backward compatibility
  108. def zero_sha_for(object_format=None) -> bytes:
  109. """Get the zero SHA for a given hash algorithm.
  110. Args:
  111. object_format: HashAlgorithm instance. If None, returns SHA1 zero.
  112. Returns:
  113. Zero SHA as hex bytes (40 chars for SHA1, 64 for SHA256)
  114. """
  115. if object_format is None:
  116. return ZERO_SHA
  117. return object_format.zero_oid
  118. # Header fields for commits
  119. _TREE_HEADER = b"tree"
  120. _PARENT_HEADER = b"parent"
  121. _AUTHOR_HEADER = b"author"
  122. _COMMITTER_HEADER = b"committer"
  123. _ENCODING_HEADER = b"encoding"
  124. _MERGETAG_HEADER = b"mergetag"
  125. _GPGSIG_HEADER = b"gpgsig"
  126. # Header fields for objects
  127. _OBJECT_HEADER = b"object"
  128. _TYPE_HEADER = b"type"
  129. _TAG_HEADER = b"tag"
  130. _TAGGER_HEADER = b"tagger"
  131. S_IFGITLINK = 0o160000
  132. MAX_TIME = 9223372036854775807 # (2**63) - 1 - signed long int max
  133. BEGIN_PGP_SIGNATURE = b"-----BEGIN PGP SIGNATURE-----"
  134. BEGIN_SSH_SIGNATURE = b"-----BEGIN SSH SIGNATURE-----"
  135. # Signature type constants
  136. SIGNATURE_PGP = b"pgp"
  137. SIGNATURE_SSH = b"ssh"
  138. # Hex SHA type
  139. ObjectID = NewType("ObjectID", bytes)
  140. # Raw SHA type
  141. RawObjectID = NewType("RawObjectID", bytes)
  142. # Zero SHA constant
  143. ZERO_SHA: ObjectID = ObjectID(b"0" * 40)
  144. class EmptyFileException(FileFormatException):
  145. """An unexpectedly empty file was encountered."""
  146. def S_ISGITLINK(m: int) -> bool:
  147. """Check if a mode indicates a submodule.
  148. Args:
  149. m: Mode to check
  150. Returns: a ``boolean``
  151. """
  152. return stat.S_IFMT(m) == S_IFGITLINK
  153. def _decompress(string: bytes) -> bytes:
  154. dcomp = zlib.decompressobj()
  155. dcomped = dcomp.decompress(string)
  156. dcomped += dcomp.flush()
  157. return dcomped
  158. def sha_to_hex(sha: RawObjectID) -> ObjectID:
  159. """Takes a string and returns the hex of the sha within."""
  160. hexsha = binascii.hexlify(sha)
  161. # Support both SHA1 (40 chars) and SHA256 (64 chars)
  162. if len(hexsha) not in (40, 64):
  163. raise ValueError(f"Incorrect length of sha string: {hexsha!r}")
  164. return ObjectID(hexsha)
  165. def hex_to_sha(hex: ObjectID | str) -> RawObjectID:
  166. """Takes a hex sha and returns a binary sha."""
  167. # Support both SHA1 (40 chars) and SHA256 (64 chars)
  168. if len(hex) not in (40, 64):
  169. raise ValueError(f"Incorrect length of hexsha: {hex!r}")
  170. try:
  171. return RawObjectID(binascii.unhexlify(hex))
  172. except TypeError as exc:
  173. if not isinstance(hex, bytes):
  174. raise
  175. raise ValueError(exc.args[0]) from exc
  176. def valid_hexsha(hex: bytes | str) -> bool:
  177. """Check if a hex string is a valid SHA1 or SHA256.
  178. Args:
  179. hex: Hex string to validate
  180. Returns:
  181. True if valid SHA1 (40 chars) or SHA256 (64 chars), False otherwise
  182. """
  183. if len(hex) not in (40, 64):
  184. return False
  185. try:
  186. binascii.unhexlify(hex)
  187. except (TypeError, binascii.Error):
  188. return False
  189. else:
  190. return True
  191. PathT = TypeVar("PathT", str, bytes)
  192. def hex_to_filename(path: PathT, hex: str | bytes) -> PathT:
  193. """Takes a hex sha and returns its filename relative to the given path."""
  194. # os.path.join accepts bytes or unicode, but all args must be of the same
  195. # type. Make sure that hex which is expected to be bytes, is the same type
  196. # as path.
  197. if isinstance(path, str):
  198. if isinstance(hex, bytes):
  199. hex_str = hex.decode("ascii")
  200. else:
  201. hex_str = hex
  202. dir_name = hex_str[:2]
  203. file_name = hex_str[2:]
  204. result = os.path.join(path, dir_name, file_name)
  205. assert isinstance(result, str)
  206. return result
  207. else:
  208. # path is bytes
  209. if isinstance(hex, str):
  210. hex_bytes = hex.encode("ascii")
  211. else:
  212. hex_bytes = hex
  213. dir_name_b = hex_bytes[:2]
  214. file_name_b = hex_bytes[2:]
  215. result_b = os.path.join(path, dir_name_b, file_name_b)
  216. assert isinstance(result_b, bytes)
  217. return result_b
  218. def filename_to_hex(filename: str | bytes) -> str:
  219. """Takes an object filename and returns its corresponding hex sha."""
  220. # grab the last (up to) two path components
  221. errmsg = f"Invalid object filename: {filename!r}"
  222. if isinstance(filename, str):
  223. names = filename.rsplit(os.path.sep, 2)[-2:]
  224. assert len(names) == 2, errmsg
  225. base, rest = names
  226. assert len(base) == 2 and len(rest) == 38, errmsg
  227. hex_str = base + rest
  228. hex_bytes = hex_str.encode("ascii")
  229. else:
  230. # filename is bytes
  231. sep = (
  232. os.path.sep.encode("ascii") if isinstance(os.path.sep, str) else os.path.sep
  233. )
  234. names_b = filename.rsplit(sep, 2)[-2:]
  235. assert len(names_b) == 2, errmsg
  236. base_b, rest_b = names_b
  237. assert len(base_b) == 2 and len(rest_b) == 38, errmsg
  238. hex_bytes = base_b + rest_b
  239. hex_to_sha(ObjectID(hex_bytes))
  240. return hex_bytes.decode("ascii")
  241. def object_header(num_type: int, length: int) -> bytes:
  242. """Return an object header for the given numeric type and text length."""
  243. cls = object_class(num_type)
  244. if cls is None:
  245. raise AssertionError(f"unsupported class type num: {num_type}")
  246. return cls.type_name + b" " + str(length).encode("ascii") + b"\0"
  247. def serializable_property(name: str, docstring: str | None = None) -> property:
  248. """A property that helps tracking whether serialization is necessary."""
  249. def set(obj: "ShaFile", value: object) -> None:
  250. """Set the property value and mark the object as needing serialization.
  251. Args:
  252. obj: The ShaFile object
  253. value: The value to set
  254. """
  255. setattr(obj, "_" + name, value)
  256. obj._needs_serialization = True
  257. def get(obj: "ShaFile") -> object:
  258. """Get the property value.
  259. Args:
  260. obj: The ShaFile object
  261. Returns:
  262. The property value
  263. """
  264. return getattr(obj, "_" + name)
  265. return property(get, set, doc=docstring)
  266. def object_class(type: bytes | int) -> type["ShaFile"] | None:
  267. """Get the object class corresponding to the given type.
  268. Args:
  269. type: Either a type name string or a numeric type.
  270. Returns: The ShaFile subclass corresponding to the given type, or None if
  271. type is not a valid type name/number.
  272. """
  273. return _TYPE_MAP.get(type, None)
  274. def check_hexsha(hex: str | bytes, error_msg: str) -> None:
  275. """Check if a string is a valid hex sha string.
  276. Args:
  277. hex: Hex string to check
  278. error_msg: Error message to use in exception
  279. Raises:
  280. ObjectFormatException: Raised when the string is not valid
  281. """
  282. if not valid_hexsha(hex):
  283. raise ObjectFormatException(f"{error_msg} {hex!r}")
  284. def check_identity(identity: bytes | None, error_msg: str) -> None:
  285. """Check if the specified identity is valid.
  286. This will raise an exception if the identity is not valid.
  287. Args:
  288. identity: Identity string
  289. error_msg: Error message to use in exception
  290. """
  291. if identity is None:
  292. raise ObjectFormatException(error_msg)
  293. email_start = identity.find(b"<")
  294. email_end = identity.find(b">")
  295. if not all(
  296. [
  297. email_start >= 1,
  298. identity[email_start - 1] == b" "[0],
  299. identity.find(b"<", email_start + 1) == -1,
  300. email_end == len(identity) - 1,
  301. b"\0" not in identity,
  302. b"\n" not in identity,
  303. ]
  304. ):
  305. raise ObjectFormatException(error_msg)
  306. def _path_to_bytes(path: str | bytes) -> bytes:
  307. """Convert a path to bytes for use in error messages."""
  308. if isinstance(path, str):
  309. return path.encode("utf-8", "surrogateescape")
  310. return path
  311. def check_time(time_seconds: int) -> None:
  312. """Check if the specified time is not prone to overflow error.
  313. This will raise an exception if the time is not valid.
  314. Args:
  315. time_seconds: time in seconds
  316. """
  317. # Prevent overflow error
  318. if time_seconds > MAX_TIME:
  319. raise ObjectFormatException(f"Date field should not exceed {MAX_TIME}")
  320. def git_line(*items: bytes) -> bytes:
  321. """Formats items into a space separated line."""
  322. return b" ".join(items) + b"\n"
  323. class FixedSha:
  324. """SHA object that behaves like hashlib's but is given a fixed value."""
  325. __slots__ = ("_hexsha", "_sha")
  326. def __init__(self, hexsha: str | bytes) -> None:
  327. """Initialize FixedSha with a fixed SHA value.
  328. Args:
  329. hexsha: Hex SHA value as string or bytes
  330. """
  331. if isinstance(hexsha, str):
  332. hexsha = hexsha.encode("ascii")
  333. if not isinstance(hexsha, bytes):
  334. raise TypeError(f"Expected bytes for hexsha, got {hexsha!r}")
  335. self._hexsha = hexsha
  336. self._sha = hex_to_sha(ObjectID(hexsha))
  337. def digest(self) -> bytes:
  338. """Return the raw SHA digest."""
  339. return self._sha
  340. def hexdigest(self) -> str:
  341. """Return the hex SHA digest."""
  342. return self._hexsha.decode("ascii")
  343. # Type guard functions for runtime type narrowing
  344. if TYPE_CHECKING:
  345. def is_commit(obj: "ShaFile") -> TypeGuard["Commit"]:
  346. """Check if a ShaFile is a Commit."""
  347. return obj.type_name == b"commit"
  348. def is_tree(obj: "ShaFile") -> TypeGuard["Tree"]:
  349. """Check if a ShaFile is a Tree."""
  350. return obj.type_name == b"tree"
  351. def is_blob(obj: "ShaFile") -> TypeGuard["Blob"]:
  352. """Check if a ShaFile is a Blob."""
  353. return obj.type_name == b"blob"
  354. def is_tag(obj: "ShaFile") -> TypeGuard["Tag"]:
  355. """Check if a ShaFile is a Tag."""
  356. return obj.type_name == b"tag"
  357. else:
  358. # Runtime versions without type narrowing
  359. def is_commit(obj: "ShaFile") -> bool:
  360. """Check if a ShaFile is a Commit."""
  361. return obj.type_name == b"commit"
  362. def is_tree(obj: "ShaFile") -> bool:
  363. """Check if a ShaFile is a Tree."""
  364. return obj.type_name == b"tree"
  365. def is_blob(obj: "ShaFile") -> bool:
  366. """Check if a ShaFile is a Blob."""
  367. return obj.type_name == b"blob"
  368. def is_tag(obj: "ShaFile") -> bool:
  369. """Check if a ShaFile is a Tag."""
  370. return obj.type_name == b"tag"
  371. class ShaFile:
  372. """A git SHA file."""
  373. __slots__ = ("_chunked_text", "_needs_serialization", "_sha", "object_format")
  374. _needs_serialization: bool
  375. type_name: bytes
  376. type_num: int
  377. _chunked_text: list[bytes] | None
  378. _sha: "FixedSha | None | HASH"
  379. def __init__(self) -> None:
  380. """Initialize a ShaFile."""
  381. self._sha = None
  382. self._chunked_text = None
  383. self._needs_serialization = True
  384. self.object_format = None
  385. @staticmethod
  386. def _parse_legacy_object_header(
  387. magic: bytes, f: BufferedIOBase | IO[bytes] | "_GitFile"
  388. ) -> "ShaFile":
  389. """Parse a legacy object, creating it but not reading the file."""
  390. bufsize = 1024
  391. decomp = zlib.decompressobj()
  392. header = decomp.decompress(magic)
  393. start = 0
  394. end = -1
  395. while end < 0:
  396. extra = f.read(bufsize)
  397. header += decomp.decompress(extra)
  398. magic += extra
  399. end = header.find(b"\0", start)
  400. start = len(header)
  401. header = header[:end]
  402. type_name, size = header.split(b" ", 1)
  403. try:
  404. int(size) # sanity check
  405. except ValueError as exc:
  406. raise ObjectFormatException(f"Object size not an integer: {exc}") from exc
  407. obj_class = object_class(type_name)
  408. if not obj_class:
  409. raise ObjectFormatException(
  410. "Not a known type: {}".format(type_name.decode("ascii"))
  411. )
  412. return obj_class()
  413. def _parse_legacy_object(self, map: bytes) -> None:
  414. """Parse a legacy object, setting the raw string."""
  415. text = _decompress(map)
  416. header_end = text.find(b"\0")
  417. if header_end < 0:
  418. raise ObjectFormatException("Invalid object header, no \\0")
  419. self.set_raw_string(text[header_end + 1 :])
  420. def as_legacy_object_chunks(self, compression_level: int = -1) -> Iterator[bytes]:
  421. """Return chunks representing the object in the experimental format.
  422. Returns: List of strings
  423. """
  424. compobj = zlib.compressobj(compression_level)
  425. yield compobj.compress(self._header())
  426. for chunk in self.as_raw_chunks():
  427. yield compobj.compress(chunk)
  428. yield compobj.flush()
  429. def as_legacy_object(self, compression_level: int = -1) -> bytes:
  430. """Return string representing the object in the experimental format."""
  431. return b"".join(
  432. self.as_legacy_object_chunks(compression_level=compression_level)
  433. )
  434. def as_raw_chunks(self) -> list[bytes]:
  435. """Return chunks with serialization of the object.
  436. Returns: List of strings, not necessarily one per line
  437. """
  438. if self._needs_serialization:
  439. self._sha = None
  440. self._chunked_text = self._serialize()
  441. self._needs_serialization = False
  442. assert self._chunked_text is not None
  443. return self._chunked_text
  444. def as_raw_string(self) -> bytes:
  445. """Return raw string with serialization of the object.
  446. Returns: String object
  447. """
  448. return b"".join(self.as_raw_chunks())
  449. def __bytes__(self) -> bytes:
  450. """Return raw string serialization of this object."""
  451. return self.as_raw_string()
  452. def __hash__(self) -> int:
  453. """Return unique hash for this object."""
  454. return hash(self.id)
  455. def as_pretty_string(self) -> str:
  456. """Return a string representing this object, fit for display."""
  457. return self.as_raw_string().decode("utf-8", "replace")
  458. def set_raw_string(
  459. self, text: bytes, sha: ObjectID | RawObjectID | None = None
  460. ) -> None:
  461. """Set the contents of this object from a serialized string."""
  462. if not isinstance(text, bytes):
  463. raise TypeError(f"Expected bytes for text, got {text!r}")
  464. self.set_raw_chunks([text], sha)
  465. def set_raw_chunks(
  466. self, chunks: list[bytes], sha: ObjectID | RawObjectID | None = None, *, object_format=None
  467. ) -> None:
  468. """Set the contents of this object from a list of chunks."""
  469. self._chunked_text = chunks
  470. # Set hash algorithm if provided
  471. if object_format is not None:
  472. self.object_format = object_format
  473. # Set SHA before deserialization so Tree can use hash algorithm
  474. if sha is None:
  475. self._sha = None
  476. else:
  477. self._sha = FixedSha(sha)
  478. self._deserialize(chunks)
  479. self._needs_serialization = False
  480. @staticmethod
  481. def _parse_object_header(
  482. magic: bytes, f: BufferedIOBase | IO[bytes] | "_GitFile"
  483. ) -> "ShaFile":
  484. """Parse a new style object, creating it but not reading the file."""
  485. num_type = (ord(magic[0:1]) >> 4) & 7
  486. obj_class = object_class(num_type)
  487. if not obj_class:
  488. raise ObjectFormatException(f"Not a known type {num_type}")
  489. return obj_class()
  490. def _parse_object(self, map: bytes) -> None:
  491. """Parse a new style object, setting self._text."""
  492. # skip type and size; type must have already been determined, and
  493. # we trust zlib to fail if it's otherwise corrupted
  494. byte = ord(map[0:1])
  495. used = 1
  496. while (byte & 0x80) != 0:
  497. byte = ord(map[used : used + 1])
  498. used += 1
  499. raw = map[used:]
  500. self.set_raw_string(_decompress(raw))
  501. @classmethod
  502. def _is_legacy_object(cls, magic: bytes) -> bool:
  503. b0 = ord(magic[0:1])
  504. b1 = ord(magic[1:2])
  505. word = (b0 << 8) + b1
  506. return (b0 & 0x8F) == 0x08 and (word % 31) == 0
  507. @classmethod
  508. def _parse_file(
  509. cls, f: BufferedIOBase | IO[bytes] | "_GitFile", *, object_format=None
  510. ) -> "ShaFile":
  511. map = f.read()
  512. if not map:
  513. raise EmptyFileException("Corrupted empty file detected")
  514. if cls._is_legacy_object(map):
  515. obj = cls._parse_legacy_object_header(map, f)
  516. if object_format is not None:
  517. obj.object_format = object_format
  518. obj._parse_legacy_object(map)
  519. else:
  520. obj = cls._parse_object_header(map, f)
  521. if object_format is not None:
  522. obj.object_format = object_format
  523. obj._parse_object(map)
  524. return obj
  525. def _deserialize(self, chunks: list[bytes]) -> None:
  526. raise NotImplementedError(self._deserialize)
  527. def _serialize(self) -> list[bytes]:
  528. raise NotImplementedError(self._serialize)
  529. @classmethod
  530. def from_path(
  531. cls, path: str | bytes, sha: ObjectID | None = None, *, object_format=None
  532. ) -> "ShaFile":
  533. """Open a SHA file from disk."""
  534. with GitFile(path, "rb") as f:
  535. return cls.from_file(f, sha, object_format=object_format)
  536. @classmethod
  537. def from_file(
  538. cls,
  539. f: BufferedIOBase | IO[bytes] | "_GitFile",
  540. sha: ObjectID | None = None,
  541. *,
  542. object_format=None,
  543. ) -> "ShaFile":
  544. """Get the contents of a SHA file on disk."""
  545. try:
  546. # Validate SHA length matches hash algorithm if both provided
  547. if sha is not None and object_format is not None:
  548. expected_len = object_format.hex_length
  549. if len(sha) != expected_len:
  550. raise ValueError(
  551. f"SHA length {len(sha)} doesn't match hash algorithm "
  552. f"{object_format.name} (expected {expected_len})"
  553. )
  554. obj = cls._parse_file(f, object_format=object_format)
  555. if sha is not None:
  556. obj._sha = FixedSha(sha)
  557. else:
  558. obj._sha = None
  559. return obj
  560. except (IndexError, ValueError) as exc:
  561. raise ObjectFormatException("invalid object header") from exc
  562. @staticmethod
  563. def from_raw_string(
  564. type_num: int,
  565. string: bytes,
  566. sha: ObjectID | RawObjectID | None = None,
  567. *,
  568. object_format=None,
  569. ) -> "ShaFile":
  570. """Creates an object of the indicated type from the raw string given.
  571. Args:
  572. type_num: The numeric type of the object.
  573. string: The raw uncompressed contents.
  574. sha: Optional known sha for the object
  575. object_format: Optional hash algorithm for the object
  576. """
  577. cls = object_class(type_num)
  578. if cls is None:
  579. raise AssertionError(f"unsupported class type num: {type_num}")
  580. obj = cls()
  581. if object_format is not None:
  582. obj.object_format = object_format
  583. obj.set_raw_string(string, sha)
  584. return obj
  585. @staticmethod
  586. def from_raw_chunks(
  587. type_num: int, chunks: list[bytes], sha: ObjectID | RawObjectID | None = None
  588. ) -> "ShaFile":
  589. """Creates an object of the indicated type from the raw chunks given.
  590. Args:
  591. type_num: The numeric type of the object.
  592. chunks: An iterable of the raw uncompressed contents.
  593. sha: Optional known sha for the object
  594. """
  595. cls = object_class(type_num)
  596. if cls is None:
  597. raise AssertionError(f"unsupported class type num: {type_num}")
  598. obj = cls()
  599. obj.set_raw_chunks(chunks, sha)
  600. return obj
  601. @classmethod
  602. def from_string(cls, string: bytes) -> Self:
  603. """Create a ShaFile from a string."""
  604. obj = cls()
  605. obj.set_raw_string(string)
  606. return obj
  607. def _check_has_member(self, member: str, error_msg: str) -> None:
  608. """Check that the object has a given member variable.
  609. Args:
  610. member: the member variable to check for
  611. error_msg: the message for an error if the member is missing
  612. Raises:
  613. ObjectFormatException: with the given error_msg if member is
  614. missing or is None
  615. """
  616. if getattr(self, member, None) is None:
  617. raise ObjectFormatException(error_msg)
  618. def check(self) -> None:
  619. """Check this object for internal consistency.
  620. Raises:
  621. ObjectFormatException: if the object is malformed in some way
  622. ChecksumMismatch: if the object was created with a SHA that does
  623. not match its contents
  624. """
  625. # TODO: if we find that error-checking during object parsing is a
  626. # performance bottleneck, those checks should be moved to the class's
  627. # check() method during optimization so we can still check the object
  628. # when necessary.
  629. old_sha = self.id
  630. try:
  631. self._deserialize(self.as_raw_chunks())
  632. self._sha = None
  633. new_sha = self.id
  634. except Exception as exc:
  635. raise ObjectFormatException(exc) from exc
  636. if old_sha != new_sha:
  637. raise ChecksumMismatch(new_sha, old_sha)
  638. def _header(self) -> bytes:
  639. return object_header(self.type_num, self.raw_length())
  640. def raw_length(self) -> int:
  641. """Returns the length of the raw string of this object."""
  642. return sum(map(len, self.as_raw_chunks()))
  643. def sha(self, object_format=None) -> "FixedSha | HASH":
  644. """The SHA object that is the name of this object.
  645. Args:
  646. object_format: Optional HashAlgorithm to use. Defaults to SHA1.
  647. """
  648. # If using a different hash algorithm, always recalculate
  649. if object_format is not None:
  650. new_sha = object_format.new_hash()
  651. new_sha.update(self._header())
  652. for chunk in self.as_raw_chunks():
  653. new_sha.update(chunk)
  654. return new_sha
  655. # Otherwise use cached SHA1 value
  656. if self._sha is None or self._needs_serialization:
  657. # this is a local because as_raw_chunks() overwrites self._sha
  658. new_sha = sha1()
  659. new_sha.update(self._header())
  660. for chunk in self.as_raw_chunks():
  661. new_sha.update(chunk)
  662. self._sha = new_sha
  663. return self._sha
  664. def copy(self) -> "ShaFile":
  665. """Create a new copy of this SHA1 object from its raw string."""
  666. obj_class = object_class(self.type_num)
  667. if obj_class is None:
  668. raise AssertionError(f"invalid type num {self.type_num}")
  669. return obj_class.from_raw_string(self.type_num, self.as_raw_string(), self.id)
  670. @property
  671. def id(self) -> ObjectID:
  672. """The hex SHA1 of this object.
  673. For SHA256 repositories, use get_id(object_format) instead.
  674. This property always returns SHA1 for backward compatibility.
  675. """
  676. return ObjectID(self.sha().hexdigest().encode("ascii"))
  677. def get_id(self, object_format=None) -> bytes:
  678. """Get the hex SHA of this object using the specified hash algorithm.
  679. Args:
  680. object_format: Optional HashAlgorithm to use. Defaults to SHA1.
  681. Example:
  682. >>> blob = Blob()
  683. >>> blob.data = b"Hello, World!"
  684. >>> blob.id # Always returns SHA1 for backward compatibility
  685. b'4ab299c8ad6ed14f31923dd94f8b5f5cb89dfb54'
  686. >>> blob.get_id() # Same as .id
  687. b'4ab299c8ad6ed14f31923dd94f8b5f5cb89dfb54'
  688. >>> from dulwich.object_format import SHA256
  689. >>> blob.get_id(SHA256) # Get SHA256 hash
  690. b'03ba204e2f2e707...' # 64-character SHA256
  691. """
  692. return self.sha(object_format).hexdigest().encode("ascii")
  693. def __repr__(self) -> str:
  694. """Return string representation of this object."""
  695. return f"<{self.__class__.__name__} {self.id!r}>"
  696. def __ne__(self, other: object) -> bool:
  697. """Check whether this object does not match the other."""
  698. return not isinstance(other, ShaFile) or self.id != other.id
  699. def __eq__(self, other: object) -> bool:
  700. """Return True if the SHAs of the two objects match."""
  701. return isinstance(other, ShaFile) and self.id == other.id
  702. def __lt__(self, other: object) -> bool:
  703. """Return whether SHA of this object is less than the other."""
  704. if not isinstance(other, ShaFile):
  705. raise TypeError
  706. return self.id < other.id
  707. def __le__(self, other: object) -> bool:
  708. """Check whether SHA of this object is less than or equal to the other."""
  709. if not isinstance(other, ShaFile):
  710. raise TypeError
  711. return self.id <= other.id
  712. class Blob(ShaFile):
  713. """A Git Blob object."""
  714. __slots__ = ()
  715. type_name = b"blob"
  716. type_num = 3
  717. _chunked_text: list[bytes]
  718. def __init__(self) -> None:
  719. """Initialize a new Blob object."""
  720. super().__init__()
  721. self._chunked_text = []
  722. self._needs_serialization = False
  723. def _get_data(self) -> bytes:
  724. return self.as_raw_string()
  725. def _set_data(self, data: bytes) -> None:
  726. self.set_raw_string(data)
  727. data = property(
  728. _get_data, _set_data, doc="The text contained within the blob object."
  729. )
  730. def _get_chunked(self) -> list[bytes]:
  731. return self._chunked_text
  732. def _set_chunked(self, chunks: list[bytes]) -> None:
  733. self._chunked_text = chunks
  734. def _serialize(self) -> list[bytes]:
  735. return self._chunked_text
  736. def _deserialize(self, chunks: list[bytes]) -> None:
  737. self._chunked_text = chunks
  738. chunked = property(
  739. _get_chunked,
  740. _set_chunked,
  741. doc="The text in the blob object, as chunks (not necessarily lines)",
  742. )
  743. @classmethod
  744. def from_path(cls, path: str | bytes, sha: ObjectID | None = None) -> "Blob":
  745. """Read a blob from a file on disk.
  746. Args:
  747. path: Path to the blob file
  748. sha: Optional known SHA for the object
  749. Returns:
  750. A Blob object
  751. Raises:
  752. NotBlobError: If the file is not a blob
  753. """
  754. blob = ShaFile.from_path(path, sha)
  755. if not isinstance(blob, cls):
  756. raise NotBlobError(_path_to_bytes(path))
  757. return blob
  758. def check(self) -> None:
  759. """Check this object for internal consistency.
  760. Raises:
  761. ObjectFormatException: if the object is malformed in some way
  762. """
  763. super().check()
  764. def splitlines(self) -> list[bytes]:
  765. """Return list of lines in this blob.
  766. This preserves the original line endings.
  767. """
  768. chunks = self.chunked
  769. if not chunks:
  770. return []
  771. if len(chunks) == 1:
  772. result: list[bytes] = chunks[0].splitlines(True)
  773. return result
  774. remaining = None
  775. ret = []
  776. for chunk in chunks:
  777. lines = chunk.splitlines(True)
  778. if len(lines) > 1:
  779. ret.append((remaining or b"") + lines[0])
  780. ret.extend(lines[1:-1])
  781. remaining = lines[-1]
  782. elif len(lines) == 1:
  783. if remaining is None:
  784. remaining = lines.pop()
  785. else:
  786. remaining += lines.pop()
  787. if remaining is not None:
  788. ret.append(remaining)
  789. return ret
  790. def _parse_message(
  791. chunks: Iterable[bytes],
  792. ) -> Iterator[tuple[None, None] | tuple[bytes | None, bytes]]:
  793. """Parse a message with a list of fields and a body.
  794. Args:
  795. chunks: the raw chunks of the tag or commit object.
  796. Returns: iterator of tuples of (field, value), one per header line, in the
  797. order read from the text, possibly including duplicates. Includes a
  798. field named None for the freeform tag/commit text.
  799. """
  800. f = BytesIO(b"".join(chunks))
  801. k = None
  802. v = b""
  803. eof = False
  804. def _strip_last_newline(value: bytes) -> bytes:
  805. """Strip the last newline from value."""
  806. if value and value.endswith(b"\n"):
  807. return value[:-1]
  808. return value
  809. # Parse the headers
  810. #
  811. # Headers can contain newlines. The next line is indented with a space.
  812. # We store the latest key as 'k', and the accumulated value as 'v'.
  813. for line in f:
  814. if line.startswith(b" "):
  815. # Indented continuation of the previous line
  816. v += line[1:]
  817. else:
  818. if k is not None:
  819. # We parsed a new header, return its value
  820. yield (k, _strip_last_newline(v))
  821. if line == b"\n":
  822. # Empty line indicates end of headers
  823. break
  824. (k, v) = line.split(b" ", 1)
  825. else:
  826. # We reached end of file before the headers ended. We still need to
  827. # return the previous header, then we need to return a None field for
  828. # the text.
  829. eof = True
  830. if k is not None:
  831. yield (k, _strip_last_newline(v))
  832. yield (None, None)
  833. if not eof:
  834. # We didn't reach the end of file while parsing headers. We can return
  835. # the rest of the file as a message.
  836. yield (None, f.read())
  837. f.close()
  838. def _format_message(
  839. headers: Sequence[tuple[bytes, bytes]], body: bytes | None
  840. ) -> Iterator[bytes]:
  841. for field, value in headers:
  842. lines = value.split(b"\n")
  843. yield git_line(field, lines[0])
  844. for line in lines[1:]:
  845. yield b" " + line + b"\n"
  846. yield b"\n" # There must be a new line after the headers
  847. if body:
  848. yield body
  849. class Tag(ShaFile):
  850. """A Git Tag object."""
  851. type_name = b"tag"
  852. type_num = 4
  853. __slots__ = (
  854. "_message",
  855. "_name",
  856. "_object_class",
  857. "_object_sha",
  858. "_signature",
  859. "_tag_time",
  860. "_tag_timezone",
  861. "_tag_timezone_neg_utc",
  862. "_tagger",
  863. )
  864. _message: bytes | None
  865. _name: bytes | None
  866. _object_class: "type[ShaFile] | None"
  867. _object_sha: bytes | None
  868. _signature: bytes | None
  869. _tag_time: int | None
  870. _tag_timezone: int | None
  871. _tag_timezone_neg_utc: bool | None
  872. _tagger: bytes | None
  873. def __init__(self) -> None:
  874. """Initialize a new Tag object."""
  875. super().__init__()
  876. self._tagger = None
  877. self._tag_time = None
  878. self._tag_timezone = None
  879. self._tag_timezone_neg_utc = False
  880. self._signature: bytes | None = None
  881. @classmethod
  882. def from_path(cls, filename: str | bytes, sha: ObjectID | None = None) -> "Tag":
  883. """Read a tag from a file on disk.
  884. Args:
  885. filename: Path to the tag file
  886. sha: Optional known SHA for the object
  887. Returns:
  888. A Tag object
  889. Raises:
  890. NotTagError: If the file is not a tag
  891. """
  892. tag = ShaFile.from_path(filename, sha)
  893. if not isinstance(tag, cls):
  894. raise NotTagError(_path_to_bytes(filename))
  895. return tag
  896. def check(self) -> None:
  897. """Check this object for internal consistency.
  898. Raises:
  899. ObjectFormatException: if the object is malformed in some way
  900. """
  901. super().check()
  902. assert self._chunked_text is not None
  903. self._check_has_member("_object_sha", "missing object sha")
  904. self._check_has_member("_object_class", "missing object type")
  905. self._check_has_member("_name", "missing tag name")
  906. if not self._name:
  907. raise ObjectFormatException("empty tag name")
  908. if self._object_sha is None:
  909. raise ObjectFormatException("missing object sha")
  910. check_hexsha(self._object_sha, "invalid object sha")
  911. if self._tagger is not None:
  912. check_identity(self._tagger, "invalid tagger")
  913. self._check_has_member("_tag_time", "missing tag time")
  914. if self._tag_time is None:
  915. raise ObjectFormatException("missing tag time")
  916. check_time(self._tag_time)
  917. last = None
  918. for field, _ in _parse_message(self._chunked_text):
  919. if field == _OBJECT_HEADER and last is not None:
  920. raise ObjectFormatException("unexpected object")
  921. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  922. raise ObjectFormatException("unexpected type")
  923. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  924. raise ObjectFormatException("unexpected tag name")
  925. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  926. raise ObjectFormatException("unexpected tagger")
  927. last = field
  928. def _serialize(self) -> list[bytes]:
  929. headers = []
  930. if self._object_sha is None:
  931. raise ObjectFormatException("missing object sha")
  932. headers.append((_OBJECT_HEADER, self._object_sha))
  933. if self._object_class is None:
  934. raise ObjectFormatException("missing object class")
  935. headers.append((_TYPE_HEADER, self._object_class.type_name))
  936. if self._name is None:
  937. raise ObjectFormatException("missing tag name")
  938. headers.append((_TAG_HEADER, self._name))
  939. if self._tagger:
  940. if self._tag_time is None:
  941. headers.append((_TAGGER_HEADER, self._tagger))
  942. else:
  943. if self._tag_timezone is None or self._tag_timezone_neg_utc is None:
  944. raise ObjectFormatException("missing timezone info")
  945. headers.append(
  946. (
  947. _TAGGER_HEADER,
  948. format_time_entry(
  949. self._tagger,
  950. self._tag_time,
  951. (self._tag_timezone, self._tag_timezone_neg_utc),
  952. ),
  953. )
  954. )
  955. if self.message is None and self._signature is None:
  956. body = None
  957. else:
  958. body = (self.message or b"") + (self._signature or b"")
  959. return list(_format_message(headers, body))
  960. def _deserialize(self, chunks: list[bytes]) -> None:
  961. """Grab the metadata attached to the tag."""
  962. self._tagger = None
  963. self._tag_time = None
  964. self._tag_timezone = None
  965. self._tag_timezone_neg_utc = False
  966. for field, value in _parse_message(chunks):
  967. if field == _OBJECT_HEADER:
  968. self._object_sha = value
  969. elif field == _TYPE_HEADER:
  970. assert isinstance(value, bytes)
  971. obj_class = object_class(value)
  972. if not obj_class:
  973. raise ObjectFormatException(f"Not a known type: {value!r}")
  974. self._object_class = obj_class
  975. elif field == _TAG_HEADER:
  976. self._name = value
  977. elif field == _TAGGER_HEADER:
  978. if value is None:
  979. raise ObjectFormatException("missing tagger value")
  980. (
  981. self._tagger,
  982. self._tag_time,
  983. (self._tag_timezone, self._tag_timezone_neg_utc),
  984. ) = parse_time_entry(value)
  985. elif field is None:
  986. if value is None:
  987. self._message = None
  988. self._signature = None
  989. else:
  990. # Try to find either PGP or SSH signature
  991. sig_idx = None
  992. try:
  993. sig_idx = value.index(BEGIN_PGP_SIGNATURE)
  994. except ValueError:
  995. try:
  996. sig_idx = value.index(BEGIN_SSH_SIGNATURE)
  997. except ValueError:
  998. pass
  999. if sig_idx is not None:
  1000. self._message = value[:sig_idx]
  1001. self._signature = value[sig_idx:]
  1002. else:
  1003. self._message = value
  1004. self._signature = None
  1005. else:
  1006. raise ObjectFormatException(
  1007. f"Unknown field {field.decode('ascii', 'replace')}"
  1008. )
  1009. def _get_object(self) -> tuple[type[ShaFile], bytes]:
  1010. """Get the object pointed to by this tag.
  1011. Returns: tuple of (object class, sha).
  1012. """
  1013. if self._object_class is None or self._object_sha is None:
  1014. raise ValueError("Tag object is not properly initialized")
  1015. return (self._object_class, self._object_sha)
  1016. def _set_object(self, value: tuple[type[ShaFile], bytes]) -> None:
  1017. (self._object_class, self._object_sha) = value
  1018. self._needs_serialization = True
  1019. object = property(_get_object, _set_object)
  1020. name = serializable_property("name", "The name of this tag")
  1021. tagger = serializable_property(
  1022. "tagger", "Returns the name of the person who created this tag"
  1023. )
  1024. tag_time = serializable_property(
  1025. "tag_time",
  1026. "The creation timestamp of the tag. As the number of seconds since the epoch",
  1027. )
  1028. tag_timezone = serializable_property(
  1029. "tag_timezone", "The timezone that tag_time is in."
  1030. )
  1031. message = serializable_property("message", "the message attached to this tag")
  1032. signature = serializable_property("signature", "Optional detached GPG signature")
  1033. def sign(self, keyid: str | None = None) -> None:
  1034. """Sign this tag with a GPG key.
  1035. Args:
  1036. keyid: Optional GPG key ID to use for signing. If not specified,
  1037. the default GPG key will be used.
  1038. """
  1039. import gpg
  1040. with gpg.Context(armor=True) as c:
  1041. if keyid is not None:
  1042. key = c.get_key(keyid)
  1043. with gpg.Context(armor=True, signers=[key]) as ctx:
  1044. self.signature, _unused_result = ctx.sign(
  1045. self.as_raw_string(),
  1046. mode=gpg.constants.sig.mode.DETACH,
  1047. )
  1048. else:
  1049. self.signature, _unused_result = c.sign(
  1050. self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH
  1051. )
  1052. def raw_without_sig(self) -> bytes:
  1053. """Return raw string serialization without the GPG/SSH signature.
  1054. self.signature is a signature for the returned raw byte string serialization.
  1055. """
  1056. ret = self.as_raw_string()
  1057. if self._signature:
  1058. ret = ret[: -len(self._signature)]
  1059. return ret
  1060. def extract_signature(self) -> tuple[bytes, bytes | None, bytes | None]:
  1061. """Extract the payload, signature, and signature type from this tag.
  1062. Returns:
  1063. tuple of (``payload``, ``signature``, ``signature_type``) where:
  1064. - ``payload``: The raw tag data without the signature
  1065. - ``signature``: The signature bytes if present, None otherwise
  1066. - ``signature_type``: SIGNATURE_PGP for PGP, SIGNATURE_SSH for SSH, None if no signature
  1067. Raises:
  1068. ObjectFormatException: If signature has unknown format
  1069. """
  1070. if self._signature is None:
  1071. return self.as_raw_string(), None, None
  1072. payload = self.raw_without_sig()
  1073. # Determine signature type
  1074. if self._signature.startswith(BEGIN_PGP_SIGNATURE):
  1075. sig_type = SIGNATURE_PGP
  1076. elif self._signature.startswith(BEGIN_SSH_SIGNATURE):
  1077. sig_type = SIGNATURE_SSH
  1078. else:
  1079. raise ObjectFormatException("Unknown signature format")
  1080. return payload, self._signature, sig_type
  1081. def verify(self, keyids: Iterable[str] | None = None) -> None:
  1082. """Verify GPG signature for this tag (if it is signed).
  1083. Args:
  1084. keyids: Optional iterable of trusted keyids for this tag.
  1085. If this tag is not signed by any key in keyids verification will
  1086. fail. If not specified, this function only verifies that the tag
  1087. has a valid signature.
  1088. Raises:
  1089. gpg.errors.BadSignatures: if GPG signature verification fails
  1090. gpg.errors.MissingSignatures: if tag was not signed by a key
  1091. specified in keyids
  1092. """
  1093. if self._signature is None:
  1094. return
  1095. import gpg
  1096. with gpg.Context() as ctx:
  1097. data, result = ctx.verify(
  1098. self.raw_without_sig(),
  1099. signature=self._signature,
  1100. )
  1101. if keyids:
  1102. keys = [ctx.get_key(key) for key in keyids]
  1103. for key in keys:
  1104. for subkey in key.subkeys:
  1105. for sig in result.signatures:
  1106. if subkey.can_sign and subkey.fpr == sig.fpr:
  1107. return
  1108. raise gpg.errors.MissingSignatures(result, keys, results=(data, result))
  1109. class TreeEntry(NamedTuple):
  1110. """Named tuple encapsulating a single tree entry."""
  1111. path: bytes
  1112. mode: int
  1113. sha: ObjectID
  1114. def in_path(self, path: bytes) -> "TreeEntry":
  1115. """Return a copy of this entry with the given path prepended."""
  1116. if not isinstance(self.path, bytes):
  1117. raise TypeError(f"Expected bytes for path, got {path!r}")
  1118. return TreeEntry(posixpath.join(path, self.path), self.mode, self.sha)
  1119. def parse_tree(
  1120. text: bytes, strict: bool = False, object_format=None
  1121. ) -> Iterator[tuple[bytes, int, ObjectID]]:
  1122. """Parse a tree text.
  1123. Args:
  1124. text: Serialized text to parse
  1125. strict: Whether to be strict about format
  1126. object_format: Hash algorithm object (SHA1 or SHA256) - if None, auto-detect
  1127. Returns: iterator of tuples of (name, mode, sha)
  1128. Raises:
  1129. ObjectFormatException: if the object was malformed in some way
  1130. """
  1131. if object_format is not None:
  1132. sha_len = object_format.oid_length
  1133. return _parse_tree_with_sha_len(text, strict, sha_len)
  1134. # Try both hash lengths and use the one that works
  1135. try:
  1136. # Try SHA1 first (more common)
  1137. return _parse_tree_with_sha_len(text, strict, 20)
  1138. except ObjectFormatException:
  1139. # If SHA1 fails, try SHA256
  1140. return _parse_tree_with_sha_len(text, strict, 32)
  1141. def _parse_tree_with_sha_len(
  1142. text: bytes, strict: bool, sha_len: int
  1143. ) -> Iterator[tuple[bytes, int, bytes]]:
  1144. """Helper function to parse tree with a specific hash length."""
  1145. count = 0
  1146. length = len(text)
  1147. while count < length:
  1148. mode_end = text.index(b" ", count)
  1149. mode_text = text[count:mode_end]
  1150. if strict and mode_text.startswith(b"0"):
  1151. raise ObjectFormatException(f"Invalid mode {mode_text!r}")
  1152. try:
  1153. mode = int(mode_text, 8)
  1154. except ValueError as exc:
  1155. raise ObjectFormatException(f"Invalid mode {mode_text!r}") from exc
  1156. name_end = text.index(b"\0", mode_end)
  1157. name = text[mode_end + 1 : name_end]
  1158. count = name_end + 1 + sha_len
  1159. if count > length:
  1160. raise ObjectFormatException(
  1161. f"Tree entry extends beyond tree length: {count} > {length}"
  1162. )
  1163. sha = text[name_end + 1 : count]
  1164. if len(sha) != sha_len:
  1165. raise ObjectFormatException(
  1166. f"Sha has invalid length: {len(sha)} != {sha_len}"
  1167. )
  1168. hexsha = sha_to_hex(RawObjectID(sha))
  1169. yield (name, mode, hexsha)
  1170. def serialize_tree(items: Iterable[tuple[bytes, int, ObjectID]]) -> Iterator[bytes]:
  1171. """Serialize the items in a tree to a text.
  1172. Args:
  1173. items: Sorted iterable over (name, mode, sha) tuples
  1174. Returns: Serialized tree text as chunks
  1175. """
  1176. for name, mode, hexsha in items:
  1177. yield (
  1178. (f"{mode:04o}").encode("ascii") + b" " + name + b"\0" + hex_to_sha(hexsha)
  1179. )
  1180. def sorted_tree_items(
  1181. entries: dict[bytes, tuple[int, ObjectID]], name_order: bool
  1182. ) -> Iterator[TreeEntry]:
  1183. """Iterate over a tree entries dictionary.
  1184. Args:
  1185. name_order: If True, iterate entries in order of their name. If
  1186. False, iterate entries in tree order, that is, treat subtree entries as
  1187. having '/' appended.
  1188. entries: Dictionary mapping names to (mode, sha) tuples
  1189. Returns: Iterator over (name, mode, hexsha)
  1190. """
  1191. if name_order:
  1192. key_func = key_entry_name_order
  1193. else:
  1194. key_func = key_entry
  1195. for name, entry in sorted(entries.items(), key=key_func):
  1196. mode, hexsha = entry
  1197. # Stricter type checks than normal to mirror checks in the Rust version.
  1198. mode = int(mode)
  1199. if not isinstance(hexsha, bytes):
  1200. raise TypeError(f"Expected bytes for SHA, got {hexsha!r}")
  1201. yield TreeEntry(name, mode, hexsha)
  1202. def key_entry(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes:
  1203. """Sort key for tree entry.
  1204. Args:
  1205. entry: (name, value) tuple
  1206. """
  1207. (name, (mode, _sha)) = entry
  1208. if stat.S_ISDIR(mode):
  1209. name += b"/"
  1210. return name
  1211. def key_entry_name_order(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes:
  1212. """Sort key for tree entry in name order."""
  1213. return entry[0]
  1214. def pretty_format_tree_entry(
  1215. name: bytes, mode: int, hexsha: ObjectID, encoding: str = "utf-8"
  1216. ) -> str:
  1217. """Pretty format tree entry.
  1218. Args:
  1219. name: Name of the directory entry
  1220. mode: Mode of entry
  1221. hexsha: Hexsha of the referenced object
  1222. encoding: Character encoding for the name
  1223. Returns: string describing the tree entry
  1224. """
  1225. if mode & stat.S_IFDIR:
  1226. kind = "tree"
  1227. else:
  1228. kind = "blob"
  1229. return "{:04o} {} {}\t{}\n".format(
  1230. mode,
  1231. kind,
  1232. hexsha.decode("ascii"),
  1233. name.decode(encoding, "replace"),
  1234. )
  1235. class SubmoduleEncountered(Exception):
  1236. """A submodule was encountered while resolving a path."""
  1237. def __init__(self, path: bytes, sha: ObjectID) -> None:
  1238. """Initialize SubmoduleEncountered exception.
  1239. Args:
  1240. path: Path where the submodule was encountered
  1241. sha: SHA of the submodule
  1242. """
  1243. self.path = path
  1244. self.sha = sha
  1245. class Tree(ShaFile):
  1246. """A Git tree object."""
  1247. type_name = b"tree"
  1248. type_num = 2
  1249. __slots__ = "_entries"
  1250. def __init__(self) -> None:
  1251. """Initialize an empty Tree."""
  1252. super().__init__()
  1253. self._entries: dict[bytes, tuple[int, ObjectID]] = {}
  1254. @classmethod
  1255. def from_path(cls, filename: str | bytes, sha: ObjectID | None = None) -> "Tree":
  1256. """Read a tree from a file on disk.
  1257. Args:
  1258. filename: Path to the tree file
  1259. sha: Optional known SHA for the object
  1260. Returns:
  1261. A Tree object
  1262. Raises:
  1263. NotTreeError: If the file is not a tree
  1264. """
  1265. tree = ShaFile.from_path(filename, sha)
  1266. if not isinstance(tree, cls):
  1267. raise NotTreeError(_path_to_bytes(filename))
  1268. return tree
  1269. def __contains__(self, name: bytes) -> bool:
  1270. """Check if name exists in tree."""
  1271. return name in self._entries
  1272. def __getitem__(self, name: bytes) -> tuple[int, ObjectID]:
  1273. """Get tree entry by name."""
  1274. return self._entries[name]
  1275. def __setitem__(self, name: bytes, value: tuple[int, ObjectID]) -> None:
  1276. """Set a tree entry by name.
  1277. Args:
  1278. name: The name of the entry, as a string.
  1279. value: A tuple of (mode, hexsha), where mode is the mode of the
  1280. entry as an integral type and hexsha is the hex SHA of the entry as
  1281. a string.
  1282. """
  1283. mode, hexsha = value
  1284. self._entries[name] = (mode, hexsha)
  1285. self._needs_serialization = True
  1286. def __delitem__(self, name: bytes) -> None:
  1287. """Delete tree entry by name."""
  1288. del self._entries[name]
  1289. self._needs_serialization = True
  1290. def __len__(self) -> int:
  1291. """Return number of entries in tree."""
  1292. return len(self._entries)
  1293. def __iter__(self) -> Iterator[bytes]:
  1294. """Iterate over tree entry names."""
  1295. return iter(self._entries)
  1296. def add(self, name: bytes, mode: int, hexsha: ObjectID) -> None:
  1297. """Add an entry to the tree.
  1298. Args:
  1299. mode: The mode of the entry as an integral type. Not all
  1300. possible modes are supported by git; see check() for details.
  1301. name: The name of the entry, as a string.
  1302. hexsha: The hex SHA of the entry as a string.
  1303. """
  1304. self._entries[name] = mode, hexsha
  1305. self._needs_serialization = True
  1306. def iteritems(self, name_order: bool = False) -> Iterator[TreeEntry]:
  1307. """Iterate over entries.
  1308. Args:
  1309. name_order: If True, iterate in name order instead of tree
  1310. order.
  1311. Returns: Iterator over (name, mode, sha) tuples
  1312. """
  1313. return sorted_tree_items(self._entries, name_order)
  1314. def items(self) -> list[TreeEntry]:
  1315. """Return the sorted entries in this tree.
  1316. Returns: List with (name, mode, sha) tuples
  1317. """
  1318. return list(self.iteritems())
  1319. def _deserialize(self, chunks: list[bytes]) -> None:
  1320. """Grab the entries in the tree."""
  1321. try:
  1322. parsed_entries = parse_tree(
  1323. b"".join(chunks), object_format=self.object_format
  1324. )
  1325. except ValueError as exc:
  1326. raise ObjectFormatException(exc) from exc
  1327. # TODO: list comprehension is for efficiency in the common (small)
  1328. # case; if memory efficiency in the large case is a concern, use a
  1329. # genexp.
  1330. self._entries = {n: (m, s) for n, m, s in parsed_entries}
  1331. def check(self) -> None:
  1332. """Check this object for internal consistency.
  1333. Raises:
  1334. ObjectFormatException: if the object is malformed in some way
  1335. """
  1336. super().check()
  1337. assert self._chunked_text is not None
  1338. last = None
  1339. allowed_modes = (
  1340. stat.S_IFREG | 0o755,
  1341. stat.S_IFREG | 0o644,
  1342. stat.S_IFLNK,
  1343. stat.S_IFDIR,
  1344. S_IFGITLINK,
  1345. # TODO: optionally exclude as in git fsck --strict
  1346. stat.S_IFREG | 0o664,
  1347. )
  1348. for name, mode, sha in parse_tree(
  1349. b"".join(self._chunked_text),
  1350. strict=True,
  1351. object_format=self.object_format,
  1352. ):
  1353. check_hexsha(sha, f"invalid sha {sha!r}")
  1354. if b"/" in name or name in (b"", b".", b"..", b".git"):
  1355. raise ObjectFormatException(
  1356. "invalid name {}".format(name.decode("utf-8", "replace"))
  1357. )
  1358. if mode not in allowed_modes:
  1359. raise ObjectFormatException(f"invalid mode {mode:06o}")
  1360. entry = (name, (mode, sha))
  1361. if last:
  1362. if key_entry(last) > key_entry(entry):
  1363. raise ObjectFormatException("entries not sorted")
  1364. if name == last[0]:
  1365. raise ObjectFormatException(f"duplicate entry {name!r}")
  1366. last = entry
  1367. def _serialize(self) -> list[bytes]:
  1368. return list(serialize_tree(self.iteritems()))
  1369. def as_pretty_string(self) -> str:
  1370. """Return a human-readable string representation of this tree.
  1371. Returns:
  1372. Pretty-printed tree entries
  1373. """
  1374. text: list[str] = []
  1375. for entry in self.iteritems():
  1376. if (
  1377. entry.path is not None
  1378. and entry.mode is not None
  1379. and entry.sha is not None
  1380. ):
  1381. text.append(pretty_format_tree_entry(entry.path, entry.mode, entry.sha))
  1382. return "".join(text)
  1383. def lookup_path(
  1384. self, lookup_obj: Callable[[ObjectID], ShaFile], path: bytes
  1385. ) -> tuple[int, ObjectID]:
  1386. """Look up an object in a Git tree.
  1387. Args:
  1388. lookup_obj: Callback for retrieving object by SHA1
  1389. path: Path to lookup
  1390. Returns: A tuple of (mode, SHA) of the resulting path.
  1391. """
  1392. # Handle empty path - return the tree itself
  1393. if not path:
  1394. return stat.S_IFDIR, self.id
  1395. parts = path.split(b"/")
  1396. sha = self.id
  1397. mode: int | None = None
  1398. for i, p in enumerate(parts):
  1399. if not p:
  1400. continue
  1401. if mode is not None and S_ISGITLINK(mode):
  1402. raise SubmoduleEncountered(b"/".join(parts[:i]), sha)
  1403. obj = lookup_obj(sha)
  1404. if not isinstance(obj, Tree):
  1405. raise NotTreeError(sha)
  1406. mode, sha = obj[p]
  1407. if mode is None:
  1408. raise ValueError("No valid path found")
  1409. return mode, sha
  1410. def parse_timezone(text: bytes) -> tuple[int, bool]:
  1411. """Parse a timezone text fragment (e.g. '+0100').
  1412. Args:
  1413. text: Text to parse.
  1414. Returns: Tuple with timezone as seconds difference to UTC
  1415. and a boolean indicating whether this was a UTC timezone
  1416. prefixed with a negative sign (-0000).
  1417. """
  1418. # cgit parses the first character as the sign, and the rest
  1419. # as an integer (using strtol), which could also be negative.
  1420. # We do the same for compatibility. See #697828.
  1421. if text[0] not in b"+-":
  1422. raise ValueError("Timezone must start with + or - ({text})".format(**vars()))
  1423. sign = text[:1]
  1424. offset = int(text[1:])
  1425. if sign == b"-":
  1426. offset = -offset
  1427. unnecessary_negative_timezone = offset >= 0 and sign == b"-"
  1428. signum = ((offset < 0) and -1) or 1
  1429. offset = abs(offset)
  1430. hours = int(offset / 100)
  1431. minutes = offset % 100
  1432. return (
  1433. signum * (hours * 3600 + minutes * 60),
  1434. unnecessary_negative_timezone,
  1435. )
  1436. def format_timezone(offset: int, unnecessary_negative_timezone: bool = False) -> bytes:
  1437. """Format a timezone for Git serialization.
  1438. Args:
  1439. offset: Timezone offset as seconds difference to UTC
  1440. unnecessary_negative_timezone: Whether to use a minus sign for
  1441. UTC or positive timezones (-0000 and --700 rather than +0000 / +0700).
  1442. """
  1443. if offset % 60 != 0:
  1444. raise ValueError("Unable to handle non-minute offset.")
  1445. if offset < 0 or unnecessary_negative_timezone:
  1446. sign = "-"
  1447. offset = -offset
  1448. else:
  1449. sign = "+"
  1450. return ("%c%02d%02d" % (sign, offset / 3600, (offset / 60) % 60)).encode("ascii") # noqa: UP031
  1451. def parse_time_entry(
  1452. value: bytes,
  1453. ) -> tuple[bytes, int | None, tuple[int | None, bool]]:
  1454. """Parse event.
  1455. Args:
  1456. value: Bytes representing a git commit/tag line
  1457. Raises:
  1458. ObjectFormatException in case of parsing error (malformed
  1459. field date)
  1460. Returns: Tuple of (author, time, (timezone, timezone_neg_utc))
  1461. """
  1462. try:
  1463. sep = value.rindex(b"> ")
  1464. except ValueError:
  1465. return (value, None, (None, False))
  1466. try:
  1467. person = value[0 : sep + 1]
  1468. rest = value[sep + 2 :]
  1469. timetext, timezonetext = rest.rsplit(b" ", 1)
  1470. time = int(timetext)
  1471. timezone, timezone_neg_utc = parse_timezone(timezonetext)
  1472. except ValueError as exc:
  1473. raise ObjectFormatException(exc) from exc
  1474. return person, time, (timezone, timezone_neg_utc)
  1475. def format_time_entry(
  1476. person: bytes, time: int, timezone_info: tuple[int, bool]
  1477. ) -> bytes:
  1478. """Format an event."""
  1479. (timezone, timezone_neg_utc) = timezone_info
  1480. return b" ".join(
  1481. [person, str(time).encode("ascii"), format_timezone(timezone, timezone_neg_utc)]
  1482. )
  1483. @replace_me(since="0.21.0", remove_in="0.24.0")
  1484. def parse_commit(
  1485. chunks: Iterable[bytes],
  1486. ) -> tuple[
  1487. bytes | None,
  1488. list[bytes],
  1489. tuple[bytes | None, int | None, tuple[int | None, bool | None]],
  1490. tuple[bytes | None, int | None, tuple[int | None, bool | None]],
  1491. bytes | None,
  1492. list[Tag],
  1493. bytes | None,
  1494. bytes | None,
  1495. list[tuple[bytes, bytes]],
  1496. ]:
  1497. """Parse a commit object from chunks.
  1498. Args:
  1499. chunks: Chunks to parse
  1500. Returns: Tuple of (tree, parents, author_info, commit_info,
  1501. encoding, mergetag, gpgsig, message, extra)
  1502. """
  1503. parents = []
  1504. extra = []
  1505. tree = None
  1506. author_info: tuple[bytes | None, int | None, tuple[int | None, bool | None]] = (
  1507. None,
  1508. None,
  1509. (None, None),
  1510. )
  1511. commit_info: tuple[bytes | None, int | None, tuple[int | None, bool | None]] = (
  1512. None,
  1513. None,
  1514. (None, None),
  1515. )
  1516. encoding = None
  1517. mergetag = []
  1518. message = None
  1519. gpgsig = None
  1520. for field, value in _parse_message(chunks):
  1521. # TODO(jelmer): Enforce ordering
  1522. if field == _TREE_HEADER:
  1523. tree = value
  1524. elif field == _PARENT_HEADER:
  1525. if value is None:
  1526. raise ObjectFormatException("missing parent value")
  1527. parents.append(value)
  1528. elif field == _AUTHOR_HEADER:
  1529. if value is None:
  1530. raise ObjectFormatException("missing author value")
  1531. author_info = parse_time_entry(value)
  1532. elif field == _COMMITTER_HEADER:
  1533. if value is None:
  1534. raise ObjectFormatException("missing committer value")
  1535. commit_info = parse_time_entry(value)
  1536. elif field == _ENCODING_HEADER:
  1537. encoding = value
  1538. elif field == _MERGETAG_HEADER:
  1539. if value is None:
  1540. raise ObjectFormatException("missing mergetag value")
  1541. tag = Tag.from_string(value + b"\n")
  1542. assert isinstance(tag, Tag)
  1543. mergetag.append(tag)
  1544. elif field == _GPGSIG_HEADER:
  1545. gpgsig = value
  1546. elif field is None:
  1547. message = value
  1548. else:
  1549. if value is None:
  1550. raise ObjectFormatException(f"missing value for field {field!r}")
  1551. extra.append((field, value))
  1552. return (
  1553. tree,
  1554. parents,
  1555. author_info,
  1556. commit_info,
  1557. encoding,
  1558. mergetag,
  1559. gpgsig,
  1560. message,
  1561. extra,
  1562. )
  1563. class Commit(ShaFile):
  1564. """A git commit object."""
  1565. type_name = b"commit"
  1566. type_num = 1
  1567. __slots__ = (
  1568. "_author",
  1569. "_author_time",
  1570. "_author_timezone",
  1571. "_author_timezone_neg_utc",
  1572. "_commit_time",
  1573. "_commit_timezone",
  1574. "_commit_timezone_neg_utc",
  1575. "_committer",
  1576. "_encoding",
  1577. "_extra",
  1578. "_gpgsig",
  1579. "_mergetag",
  1580. "_message",
  1581. "_parents",
  1582. "_tree",
  1583. )
  1584. def __init__(self) -> None:
  1585. """Initialize an empty Commit."""
  1586. super().__init__()
  1587. self._parents: list[ObjectID] = []
  1588. self._encoding: bytes | None = None
  1589. self._mergetag: list[Tag] = []
  1590. self._gpgsig: bytes | None = None
  1591. self._extra: list[tuple[bytes, bytes | None]] = []
  1592. self._author_timezone_neg_utc: bool | None = False
  1593. self._commit_timezone_neg_utc: bool | None = False
  1594. @classmethod
  1595. def from_path(cls, path: str | bytes, sha: ObjectID | None = None) -> "Commit":
  1596. """Read a commit from a file on disk.
  1597. Args:
  1598. path: Path to the commit file
  1599. sha: Optional known SHA for the object
  1600. Returns:
  1601. A Commit object
  1602. Raises:
  1603. NotCommitError: If the file is not a commit
  1604. """
  1605. commit = ShaFile.from_path(path, sha)
  1606. if not isinstance(commit, cls):
  1607. raise NotCommitError(_path_to_bytes(path))
  1608. return commit
  1609. def _deserialize(self, chunks: list[bytes]) -> None:
  1610. self._parents = []
  1611. self._extra = []
  1612. self._tree = None
  1613. author_info: tuple[bytes | None, int | None, tuple[int | None, bool | None]] = (
  1614. None,
  1615. None,
  1616. (None, None),
  1617. )
  1618. commit_info: tuple[bytes | None, int | None, tuple[int | None, bool | None]] = (
  1619. None,
  1620. None,
  1621. (None, None),
  1622. )
  1623. self._encoding = None
  1624. self._mergetag = []
  1625. self._message = None
  1626. self._gpgsig = None
  1627. for field, value in _parse_message(chunks):
  1628. # TODO(jelmer): Enforce ordering
  1629. if field == _TREE_HEADER:
  1630. self._tree = value
  1631. elif field == _PARENT_HEADER:
  1632. assert value is not None
  1633. self._parents.append(ObjectID(value))
  1634. elif field == _AUTHOR_HEADER:
  1635. if value is None:
  1636. raise ObjectFormatException("missing author value")
  1637. author_info = parse_time_entry(value)
  1638. elif field == _COMMITTER_HEADER:
  1639. if value is None:
  1640. raise ObjectFormatException("missing committer value")
  1641. commit_info = parse_time_entry(value)
  1642. elif field == _ENCODING_HEADER:
  1643. self._encoding = value
  1644. elif field == _MERGETAG_HEADER:
  1645. assert value is not None
  1646. tag = Tag.from_string(value + b"\n")
  1647. assert isinstance(tag, Tag)
  1648. self._mergetag.append(tag)
  1649. elif field == _GPGSIG_HEADER:
  1650. self._gpgsig = value
  1651. elif field is None:
  1652. self._message = value
  1653. else:
  1654. self._extra.append((field, value))
  1655. (
  1656. self._author,
  1657. self._author_time,
  1658. (self._author_timezone, self._author_timezone_neg_utc),
  1659. ) = author_info
  1660. (
  1661. self._committer,
  1662. self._commit_time,
  1663. (self._commit_timezone, self._commit_timezone_neg_utc),
  1664. ) = commit_info
  1665. def check(self) -> None:
  1666. """Check this object for internal consistency.
  1667. Raises:
  1668. ObjectFormatException: if the object is malformed in some way
  1669. """
  1670. super().check()
  1671. assert self._chunked_text is not None
  1672. self._check_has_member("_tree", "missing tree")
  1673. self._check_has_member("_author", "missing author")
  1674. self._check_has_member("_committer", "missing committer")
  1675. self._check_has_member("_author_time", "missing author time")
  1676. self._check_has_member("_commit_time", "missing commit time")
  1677. for parent in self._parents:
  1678. check_hexsha(parent, "invalid parent sha")
  1679. assert self._tree is not None # checked by _check_has_member above
  1680. check_hexsha(self._tree, "invalid tree sha")
  1681. assert self._author is not None # checked by _check_has_member above
  1682. assert self._committer is not None # checked by _check_has_member above
  1683. check_identity(self._author, "invalid author")
  1684. check_identity(self._committer, "invalid committer")
  1685. assert self._author_time is not None # checked by _check_has_member above
  1686. assert self._commit_time is not None # checked by _check_has_member above
  1687. check_time(self._author_time)
  1688. check_time(self._commit_time)
  1689. last = None
  1690. for field, _ in _parse_message(self._chunked_text):
  1691. if field == _TREE_HEADER and last is not None:
  1692. raise ObjectFormatException("unexpected tree")
  1693. elif field == _PARENT_HEADER and last not in (
  1694. _PARENT_HEADER,
  1695. _TREE_HEADER,
  1696. ):
  1697. raise ObjectFormatException("unexpected parent")
  1698. elif field == _AUTHOR_HEADER and last not in (
  1699. _TREE_HEADER,
  1700. _PARENT_HEADER,
  1701. ):
  1702. raise ObjectFormatException("unexpected author")
  1703. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  1704. raise ObjectFormatException("unexpected committer")
  1705. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  1706. raise ObjectFormatException("unexpected encoding")
  1707. last = field
  1708. # TODO: optionally check for duplicate parents
  1709. def sign(self, keyid: str | None = None) -> None:
  1710. """Sign this commit with a GPG key.
  1711. Args:
  1712. keyid: Optional GPG key ID to use for signing. If not specified,
  1713. the default GPG key will be used.
  1714. """
  1715. import gpg
  1716. with gpg.Context(armor=True) as c:
  1717. if keyid is not None:
  1718. key = c.get_key(keyid)
  1719. with gpg.Context(armor=True, signers=[key]) as ctx:
  1720. self.gpgsig, _unused_result = ctx.sign(
  1721. self.as_raw_string(),
  1722. mode=gpg.constants.sig.mode.DETACH,
  1723. )
  1724. else:
  1725. self.gpgsig, _unused_result = c.sign(
  1726. self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH
  1727. )
  1728. def raw_without_sig(self) -> bytes:
  1729. """Return raw string serialization without the GPG/SSH signature.
  1730. self.gpgsig is a signature for the returned raw byte string serialization.
  1731. """
  1732. tmp = self.copy()
  1733. assert isinstance(tmp, Commit)
  1734. tmp._gpgsig = None
  1735. tmp.gpgsig = None
  1736. return tmp.as_raw_string()
  1737. def extract_signature(self) -> tuple[bytes, bytes | None, bytes | None]:
  1738. """Extract the payload, signature, and signature type from this commit.
  1739. Returns:
  1740. tuple of (``payload``, ``signature``, ``signature_type``) where:
  1741. - ``payload``: The raw commit data without the signature
  1742. - ``signature``: The signature bytes if present, None otherwise
  1743. - ``signature_type``: SIGNATURE_PGP for PGP, SIGNATURE_SSH for SSH, None if no signature
  1744. Raises:
  1745. ObjectFormatException: If signature has unknown format
  1746. """
  1747. if self._gpgsig is None:
  1748. return self.as_raw_string(), None, None
  1749. payload = self.raw_without_sig()
  1750. # Determine signature type
  1751. if self._gpgsig.startswith(BEGIN_PGP_SIGNATURE):
  1752. sig_type = SIGNATURE_PGP
  1753. elif self._gpgsig.startswith(BEGIN_SSH_SIGNATURE):
  1754. sig_type = SIGNATURE_SSH
  1755. else:
  1756. raise ObjectFormatException("Unknown signature format")
  1757. return payload, self._gpgsig, sig_type
  1758. def verify(self, keyids: Iterable[str] | None = None) -> None:
  1759. """Verify GPG signature for this commit (if it is signed).
  1760. Args:
  1761. keyids: Optional iterable of trusted keyids for this commit.
  1762. If this commit is not signed by any key in keyids verification will
  1763. fail. If not specified, this function only verifies that the commit
  1764. has a valid signature.
  1765. Raises:
  1766. gpg.errors.BadSignatures: if GPG signature verification fails
  1767. gpg.errors.MissingSignatures: if commit was not signed by a key
  1768. specified in keyids
  1769. """
  1770. if self._gpgsig is None:
  1771. return
  1772. import gpg
  1773. with gpg.Context() as ctx:
  1774. data, result = ctx.verify(
  1775. self.raw_without_sig(),
  1776. signature=self._gpgsig,
  1777. )
  1778. if keyids:
  1779. keys = [ctx.get_key(key) for key in keyids]
  1780. for key in keys:
  1781. for subkey in key.subkeys:
  1782. for sig in result.signatures:
  1783. if subkey.can_sign and subkey.fpr == sig.fpr:
  1784. return
  1785. raise gpg.errors.MissingSignatures(result, keys, results=(data, result))
  1786. def _serialize(self) -> list[bytes]:
  1787. headers = []
  1788. assert self._tree is not None
  1789. tree_bytes = self._tree.id if isinstance(self._tree, Tree) else self._tree
  1790. headers.append((_TREE_HEADER, tree_bytes))
  1791. for p in self._parents:
  1792. headers.append((_PARENT_HEADER, p))
  1793. assert self._author is not None
  1794. assert self._author_time is not None
  1795. assert self._author_timezone is not None
  1796. assert self._author_timezone_neg_utc is not None
  1797. headers.append(
  1798. (
  1799. _AUTHOR_HEADER,
  1800. format_time_entry(
  1801. self._author,
  1802. self._author_time,
  1803. (self._author_timezone, self._author_timezone_neg_utc),
  1804. ),
  1805. )
  1806. )
  1807. assert self._committer is not None
  1808. assert self._commit_time is not None
  1809. assert self._commit_timezone is not None
  1810. assert self._commit_timezone_neg_utc is not None
  1811. headers.append(
  1812. (
  1813. _COMMITTER_HEADER,
  1814. format_time_entry(
  1815. self._committer,
  1816. self._commit_time,
  1817. (self._commit_timezone, self._commit_timezone_neg_utc),
  1818. ),
  1819. )
  1820. )
  1821. if self.encoding:
  1822. headers.append((_ENCODING_HEADER, self.encoding))
  1823. for mergetag in self.mergetag:
  1824. headers.append((_MERGETAG_HEADER, mergetag.as_raw_string()[:-1]))
  1825. headers.extend(
  1826. (field, value) for field, value in self._extra if value is not None
  1827. )
  1828. if self.gpgsig:
  1829. headers.append((_GPGSIG_HEADER, self.gpgsig))
  1830. return list(_format_message(headers, self._message))
  1831. tree = serializable_property("tree", "Tree that is the state of this commit")
  1832. def _get_parents(self) -> list[ObjectID]:
  1833. """Return a list of parents of this commit."""
  1834. return self._parents
  1835. def _set_parents(self, value: list[ObjectID]) -> None:
  1836. """Set a list of parents of this commit."""
  1837. self._needs_serialization = True
  1838. self._parents = value
  1839. parents = property(
  1840. _get_parents,
  1841. _set_parents,
  1842. doc="Parents of this commit, by their SHA1.",
  1843. )
  1844. @replace_me(since="0.21.0", remove_in="0.24.0")
  1845. def _get_extra(self) -> list[tuple[bytes, bytes | None]]:
  1846. """Return extra settings of this commit."""
  1847. return self._extra
  1848. extra = property(
  1849. _get_extra,
  1850. doc="Extra header fields not understood (presumably added in a "
  1851. "newer version of git). Kept verbatim so the object can "
  1852. "be correctly reserialized. For private commit metadata, use "
  1853. "pseudo-headers in Commit.message, rather than this field.",
  1854. )
  1855. author = serializable_property("author", "The name of the author of the commit")
  1856. committer = serializable_property(
  1857. "committer", "The name of the committer of the commit"
  1858. )
  1859. message = serializable_property("message", "The commit message")
  1860. commit_time = serializable_property(
  1861. "commit_time",
  1862. "The timestamp of the commit. As the number of seconds since the epoch.",
  1863. )
  1864. commit_timezone = serializable_property(
  1865. "commit_timezone", "The zone the commit time is in"
  1866. )
  1867. author_time = serializable_property(
  1868. "author_time",
  1869. "The timestamp the commit was written. As the number of "
  1870. "seconds since the epoch.",
  1871. )
  1872. author_timezone = serializable_property(
  1873. "author_timezone", "Returns the zone the author time is in."
  1874. )
  1875. encoding = serializable_property("encoding", "Encoding of the commit message.")
  1876. mergetag = serializable_property("mergetag", "Associated signed tag.")
  1877. gpgsig = serializable_property("gpgsig", "GPG Signature.")
  1878. OBJECT_CLASSES = (
  1879. Commit,
  1880. Tree,
  1881. Blob,
  1882. Tag,
  1883. )
  1884. _TYPE_MAP: dict[bytes | int, type[ShaFile]] = {}
  1885. for cls in OBJECT_CLASSES:
  1886. _TYPE_MAP[cls.type_name] = cls
  1887. _TYPE_MAP[cls.type_num] = cls
  1888. # Hold on to the pure-python implementations for testing
  1889. _parse_tree_py = parse_tree
  1890. _sorted_tree_items_py = sorted_tree_items
  1891. try:
  1892. # Try to import Rust versions
  1893. from dulwich._objects import (
  1894. parse_tree as _parse_tree_rs,
  1895. )
  1896. from dulwich._objects import (
  1897. sorted_tree_items as _sorted_tree_items_rs,
  1898. )
  1899. except ImportError:
  1900. pass
  1901. else:
  1902. parse_tree = _parse_tree_rs
  1903. sorted_tree_items = _sorted_tree_items_rs