objects.py 52 KB

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