objects.py 79 KB

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