objects.py 52 KB

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