objects.py 53 KB

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