From nobody Mon Feb 9 16:19:40 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1623096912; cv=none; d=zohomail.com; s=zohoarc; b=HUcbdrz3cCd0fbgzH9KH6t/uSxXP+9bKGg56LuPdlzUvCDxe4Nzt8hId3O/2Rbmr+06Kmaotk2wSrG+1zfEi8+swDim+Bg/qOnbizVh+69aUl0MlLtfXjEBhF1EFrT0WkbYBpiEoc18llKAx/d1DbJ1x7bn1sG6QbPBx1WBWXho= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1623096912; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=X67zZQznA/dmqztz2ytUiTTb1EaymoszsnIuKjXCVEg=; b=R3QV9AEdmHjyp5U7Qm9ann9dPjbuE6z8ja4DVdMSq+vfY1uwDUwQZ1EWze60TqcFbwNJQ2t5mb0sxyWTsY6ePO2Hr1zgRpqaAMFFi3vk4vosZEFUIR2p7XHitxQ4Hzc1r6wztjtoxOUp7sCYZK2C5m3drDLOUcd9MpUqZyHyjs4= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail header.from= (p=none dis=none) header.from= Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1623096912706503.2101275476666; Mon, 7 Jun 2021 13:15:12 -0700 (PDT) Received: from localhost ([::1]:52964 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1lqLeR-00070Z-Ek for importer@patchew.org; Mon, 07 Jun 2021 16:15:11 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:37614) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1lqLWy-00046o-VT for qemu-devel@nongnu.org; Mon, 07 Jun 2021 16:07:28 -0400 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]:23504) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1lqLWt-0006V4-IN for qemu-devel@nongnu.org; Mon, 07 Jun 2021 16:07:28 -0400 Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id us-mta-356-kyn71RS_OS2MWPcv8Vb6iA-1; Mon, 07 Jun 2021 16:07:21 -0400 Received: from smtp.corp.redhat.com (int-mx06.intmail.prod.int.phx2.redhat.com [10.5.11.16]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx01.redhat.com (Postfix) with ESMTPS id BEC27108C2AD; Mon, 7 Jun 2021 20:07:20 +0000 (UTC) Received: from scv.redhat.com (ovpn-116-137.rdu2.redhat.com [10.10.116.137]) by smtp.corp.redhat.com (Postfix) with ESMTP id CDFC05C1C2; Mon, 7 Jun 2021 20:07:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1623096442; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=X67zZQznA/dmqztz2ytUiTTb1EaymoszsnIuKjXCVEg=; b=ctQpGeBpCxeU1xrCYu+WWHf0nN0rqR5nyQJjltcyXseV20usQ/7Ocp6n2G+KGlLXflFRcz pK4+qrldHH1ib/0i+XeeoNHj+F1WbcGjtuXJ0m/Cw4oqr5jx5/FBHE1Xg6wj1Fq2CpzHo8 MqPd9SOy5eqhFvZLLKCKssp9GqXDVkI= X-MC-Unique: kyn71RS_OS2MWPcv8Vb6iA-1 From: John Snow To: qemu-devel@nongnu.org Subject: [PATCH 27/42] scripts/qmp-shell: add mypy types Date: Mon, 7 Jun 2021 16:06:34 -0400 Message-Id: <20210607200649.1840382-28-jsnow@redhat.com> In-Reply-To: <20210607200649.1840382-1-jsnow@redhat.com> References: <20210607200649.1840382-1-jsnow@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.79 on 10.5.11.16 Authentication-Results: relay.mimecast.com; auth=pass smtp.auth=CUSA124A263 smtp.mailfrom=jsnow@redhat.com X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=170.10.133.124; envelope-from=jsnow@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -29 X-Spam_score: -3.0 X-Spam_bar: --- X-Spam_report: (-3.0 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.2, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_LOW=-0.7, RCVD_IN_MSPIKE_H4=0.001, RCVD_IN_MSPIKE_WL=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: "Niteesh G . S ." , Cleber Rosa , John Snow , Markus Armbruster , Eduardo Habkost Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) Content-Type: text/plain; charset="utf-8" As per my usual, this patch is annotations only. Any changes with side effects are done elsewhere. Note: pylint does not understand the subscripts for Collection in Python 3.= 6, so use the stronger Sequence type as a workaround. Signed-off-by: John Snow --- scripts/qmp/qmp-shell | 67 ++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 26 deletions(-) diff --git a/scripts/qmp/qmp-shell b/scripts/qmp/qmp-shell index 670361322c..2d0e85b5f7 100755 --- a/scripts/qmp/qmp-shell +++ b/scripts/qmp/qmp-shell @@ -72,10 +72,18 @@ import os import re import readline import sys +from typing import ( + Iterator, + List, + NoReturn, + Optional, + Sequence, +) =20 =20 sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'pytho= n')) from qemu import qmp +from qemu.qmp import QMPMessage =20 =20 class QMPCompleter: @@ -122,25 +130,26 @@ class FuzzyJSON(ast.NodeTransformer): # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and # _execute_cmd()). Let's design a better one. class QMPShell(qmp.QEMUMonitorProtocol): - def __init__(self, address, pretty=3DFalse, verbose=3DFalse): + def __init__(self, address: str, pretty: bool =3D False, + verbose: bool =3D False): super().__init__(self.parse_address(address)) - self._greeting =3D None + self._greeting: Optional[QMPMessage] =3D None self._completer =3D QMPCompleter() self._pretty =3D pretty self._transmode =3D False - self._actions =3D list() + self._actions: List[QMPMessage] =3D [] self._histfile =3D os.path.join(os.path.expanduser('~'), '.qmp-shell_history') self.verbose =3D verbose =20 - def _fill_completion(self): + def _fill_completion(self) -> None: cmds =3D self.cmd('query-commands') if 'error' in cmds: return for cmd in cmds['return']: self._completer.append(cmd['name']) =20 - def __completer_setup(self): + def __completer_setup(self) -> None: self._completer =3D QMPCompleter() self._fill_completion() readline.set_history_length(1024) @@ -157,14 +166,14 @@ class QMPShell(qmp.QEMUMonitorProtocol): print(f"Failed to read history '{self._histfile}': {err!s}") atexit.register(self.__save_history) =20 - def __save_history(self): + def __save_history(self) -> None: try: readline.write_history_file(self._histfile) except IOError as err: print(f"Failed to save history file '{self._histfile}': {err!s= }") =20 @classmethod - def __parse_value(cls, val): + def __parse_value(cls, val: str) -> object: try: return int(val) except ValueError: @@ -189,7 +198,9 @@ class QMPShell(qmp.QEMUMonitorProtocol): pass return val =20 - def __cli_expr(self, tokens, parent): + def __cli_expr(self, + tokens: Sequence[str], + parent: qmp.QMPObject) -> None: for arg in tokens: (key, sep, val) =3D arg.partition('=3D') if sep !=3D '=3D': @@ -215,7 +226,7 @@ class QMPShell(qmp.QEMUMonitorProtocol): raise QMPShellError(f'Cannot set "{key}" multiple times') parent[optpath[-1]] =3D value =20 - def __build_cmd(self, cmdline): + def __build_cmd(self, cmdline: str) -> Optional[QMPMessage]: """ Build a QMP input object from a user provided command-line in the following format: @@ -224,6 +235,7 @@ class QMPShell(qmp.QEMUMonitorProtocol): """ argument_regex =3D r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')= +''' cmdargs =3D re.findall(argument_regex, cmdline) + qmpcmd: QMPMessage =20 # Transactional CLI entry/exit: if cmdargs[0] =3D=3D 'transaction(': @@ -261,14 +273,14 @@ class QMPShell(qmp.QEMUMonitorProtocol): self.__cli_expr(cmdargs[1:], qmpcmd['arguments']) return qmpcmd =20 - def _print(self, qmp_message): + def _print(self, qmp_message: object) -> None: indent =3D None if self._pretty: indent =3D 4 jsobj =3D json.dumps(qmp_message, indent=3Dindent, sort_keys=3Dsel= f._pretty) print(str(jsobj)) =20 - def _execute_cmd(self, cmdline): + def _execute_cmd(self, cmdline: str) -> bool: try: qmpcmd =3D self.__build_cmd(cmdline) except Exception as err: @@ -288,11 +300,12 @@ class QMPShell(qmp.QEMUMonitorProtocol): self._print(resp) return True =20 - def connect(self, negotiate: bool =3D True): + def connect(self, negotiate: bool =3D True) -> None: self._greeting =3D super().connect(negotiate) self.__completer_setup() =20 - def show_banner(self, msg=3D'Welcome to the QMP low-level shell!'): + def show_banner(self, + msg: str =3D 'Welcome to the QMP low-level shell!') ->= None: print(msg) if not self._greeting: print('Connected') @@ -301,12 +314,12 @@ class QMPShell(qmp.QEMUMonitorProtocol): print("Connected to QEMU {major}.{minor}.{micro}\n".format(**versi= on)) =20 @property - def prompt(self): + def prompt(self) -> str: if self._transmode: return 'TRANS> ' return '(QEMU) ' =20 - def read_exec_command(self): + def read_exec_command(self) -> bool: """ Read and execute a command. =20 @@ -326,7 +339,7 @@ class QMPShell(qmp.QEMUMonitorProtocol): =20 return self._execute_cmd(cmdline) =20 - def repl(self): + def repl(self) -> Iterator[None]: self.show_banner() while self.read_exec_command(): yield @@ -334,11 +347,12 @@ class QMPShell(qmp.QEMUMonitorProtocol): =20 =20 class HMPShell(QMPShell): - def __init__(self, address, pretty=3DFalse, verbose=3DFalse): + def __init__(self, address: str, + pretty: bool =3D False, verbose: bool =3D False): super().__init__(address, pretty, verbose) self.__cpu_index =3D 0 =20 - def __cmd_completion(self): + def __cmd_completion(self) -> None: for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'): if cmd and cmd[0] !=3D '[' and cmd[0] !=3D '\t': name =3D cmd.split()[0] # drop help text @@ -355,21 +369,22 @@ class HMPShell(QMPShell): self._completer.append(name) self._completer.append('help ' + name) # help completion =20 - def __info_completion(self): + def __info_completion(self) -> None: for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'): if cmd: self._completer.append('info ' + cmd.split()[1]) =20 - def __other_completion(self): + def __other_completion(self) -> None: # special cases self._completer.append('help info') =20 - def _fill_completion(self): + def _fill_completion(self) -> None: self.__cmd_completion() self.__info_completion() self.__other_completion() =20 - def __cmd_passthrough(self, cmdline, cpu_index=3D0): + def __cmd_passthrough(self, cmdline: str, + cpu_index: int =3D 0) -> QMPMessage: return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments': { @@ -378,7 +393,7 @@ class HMPShell(QMPShell): } }) =20 - def _execute_cmd(self, cmdline): + def _execute_cmd(self, cmdline: str) -> bool: if cmdline.split()[0] =3D=3D "cpu": # trap the cpu command, it requires special setting try: @@ -404,16 +419,16 @@ class HMPShell(QMPShell): print('%s: %s' % (resp['error']['class'], resp['error']['desc'= ])) return True =20 - def show_banner(self, msg=3D'Welcome to the HMP shell!'): + def show_banner(self, msg: str =3D 'Welcome to the HMP shell!') -> Non= e: QMPShell.show_banner(self, msg) =20 =20 -def die(msg): +def die(msg: str) -> NoReturn: sys.stderr.write('ERROR: %s\n' % msg) sys.exit(1) =20 =20 -def main(): +def main() -> None: parser =3D argparse.ArgumentParser() parser.add_argument('-H', '--hmp', action=3D'store_true', help=3D'Use HMP interface') --=20 2.31.1