objects.py 52 KB

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