From 19d518fc4c4585e7ff5570bbcb23a6db6d640ea3 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Sat, 2 Jul 2022 18:37:57 +0300 Subject: [PATCH] Fix PyLint: Consider explicitly re-raising --- .pylintrc | 6 +----- platformio/__main__.py | 18 +++++++++--------- platformio/account/client.py | 4 ++-- platformio/app.py | 14 ++++++++------ platformio/builder/tools/piolib.py | 8 ++++---- platformio/builder/tools/pioplatform.py | 4 ++-- platformio/builder/tools/pioupload.py | 4 ++-- platformio/commands/ci.py | 4 ++-- platformio/commands/upgrade.py | 8 ++++---- platformio/debug/cli.py | 6 +++--- platformio/debug/config/base.py | 4 ++-- platformio/device/list/util.py | 4 ++-- platformio/device/monitor/terminal.py | 6 +++--- platformio/fs.py | 8 ++++---- platformio/home/rpc/handlers/account.py | 6 +++--- platformio/home/rpc/handlers/piocore.py | 12 ++++++------ platformio/http.py | 6 +++--- platformio/package/commands/exec.py | 2 +- platformio/package/commands/pack.py | 4 ++-- platformio/package/commands/publish.py | 4 ++-- platformio/package/lockfile.py | 4 ++-- platformio/package/manager/_download.py | 4 ++-- platformio/package/manager/_install.py | 4 ++-- platformio/package/manager/_registry.py | 4 ++-- platformio/package/manager/base.py | 4 ++-- platformio/package/manager/core.py | 2 +- platformio/package/manager/platform.py | 4 ++-- platformio/package/manifest/parser.py | 10 +++++----- platformio/package/manifest/schema.py | 8 ++++---- platformio/package/vcsclient.py | 16 ++++++++-------- platformio/platform/board.py | 4 ++-- platformio/platform/factory.py | 4 ++-- platformio/proc.py | 4 ++-- platformio/project/commands/init.py | 4 ++-- platformio/project/config.py | 16 ++++++++-------- platformio/registry/client.py | 6 +++--- platformio/remote/ac/base.py | 4 ++-- platformio/remote/client/agent_service.py | 4 ++-- platformio/remote/factory/client.py | 4 ++-- platformio/telemetry.py | 6 +++--- platformio/test/runners/base.py | 8 ++++---- platformio/test/runners/factory.py | 4 ++-- platformio/test/runners/readers/program.py | 4 ++-- platformio/test/runners/readers/serial.py | 4 ++-- tests/package/test_manifest.py | 6 +++--- 45 files changed, 136 insertions(+), 138 deletions(-) diff --git a/.pylintrc b/.pylintrc index 3943bac6..8f80370c 100644 --- a/.pylintrc +++ b/.pylintrc @@ -16,8 +16,4 @@ disable= useless-import-alias, bad-option-value, consider-using-dict-items, - consider-using-f-string, - - ; PY2 Compat - super-with-arguments, - raise-missing-from + consider-using-f-string diff --git a/platformio/__main__.py b/platformio/__main__.py index c7f8e245..6a1cda94 100644 --- a/platformio/__main__.py +++ b/platformio/__main__.py @@ -100,15 +100,15 @@ def main(argv=None): ensure_python3(raise_exception=True) configure() cli() # pylint: disable=no-value-for-parameter - except SystemExit as e: - if e.code and str(e.code).isdigit(): - exit_code = int(e.code) - except Exception as e: # pylint: disable=broad-except - if not isinstance(e, exception.ReturnErrorCode): - maintenance.on_platformio_exception(e) + except SystemExit as exc: + if exc.code and str(exc.code).isdigit(): + exit_code = int(exc.code) + except Exception as exc: # pylint: disable=broad-except + if not isinstance(exc, exception.ReturnErrorCode): + maintenance.on_platformio_exception(exc) error_str = "Error: " - if isinstance(e, exception.PlatformioException): - error_str += str(e) + if isinstance(exc, exception.PlatformioException): + error_str += str(exc) else: error_str += format_exc() error_str += """ @@ -128,7 +128,7 @@ An unexpected error occurred. Further steps: ============================================================ """ click.secho(error_str, fg="red", err=True) - exit_code = int(str(e)) if str(e).isdigit() else 1 + exit_code = int(str(exc)) if str(exc).isdigit() else 1 sys.argv = prev_sys_argv return exit_code diff --git a/platformio/account/client.py b/platformio/account/client.py index a2eb0c28..7aabb24d 100644 --- a/platformio/account/client.py +++ b/platformio/account/client.py @@ -46,8 +46,8 @@ class AccountClient(HTTPClient): # pylint:disable=too-many-public-methods def get_refresh_token(): try: return app.get_state_item("account").get("auth").get("refresh_token") - except: # pylint:disable=bare-except - raise AccountNotAuthorized() + except Exception as exc: + raise AccountNotAuthorized() from exc @staticmethod def delete_local_session(): diff --git a/platformio/app.py b/platformio/app.py index 26b4c80b..c9af8190 100644 --- a/platformio/app.py +++ b/platformio/app.py @@ -103,8 +103,10 @@ class State(object): try: with open(self.path, mode="w", encoding="utf8") as fp: fp.write(json.dumps(self._storage)) - except IOError: - raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) + except IOError as exc: + raise exception.HomeDirPermissionsError( + os.path.dirname(self.path) + ) from exc self._unlock_state_file() def _lock_state_file(self): @@ -113,8 +115,8 @@ class State(object): self._lockfile = LockFile(self.path) try: self._lockfile.acquire() - except IOError: - raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) + except IOError as exc: + raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) from exc def _unlock_state_file(self): if hasattr(self, "_lockfile") and self._lockfile: @@ -169,8 +171,8 @@ def sanitize_setting(name, value): value = str(value).lower() in ("true", "yes", "y", "1") elif isinstance(defdata["value"], int): value = int(value) - except Exception: - raise exception.InvalidSettingValue(value, name) + except Exception as exc: + raise exception.InvalidSettingValue(value, name) from exc return value diff --git a/platformio/builder/tools/piolib.py b/platformio/builder/tools/piolib.py index bab464ba..137692b8 100644 --- a/platformio/builder/tools/piolib.py +++ b/platformio/builder/tools/piolib.py @@ -360,11 +360,11 @@ class LibBuilderBase: depth=self.CCONDITIONAL_SCANNER_DEPTH, ) - except Exception as e: # pylint: disable=broad-except + except Exception as exc: # pylint: disable=broad-except if self.verbose and "+" in self.lib_ldf_mode: sys.stderr.write( "Warning! Classic Pre Processor is used for `%s`, " - "advanced has failed with `%s`\n" % (path, e) + "advanced has failed with `%s`\n" % (path, exc) ) candidates = self.env.File(path).get_implicit_deps( self.env, @@ -956,8 +956,8 @@ class ProjectAsLibBuilder(LibBuilderBase): try: lm.install(spec) did_install = True - except (HTTPClientError, UnknownPackageError, InternetIsOffline) as e: - click.secho("Warning! %s" % e, fg="yellow") + except (HTTPClientError, UnknownPackageError, InternetIsOffline) as exc: + click.secho("Warning! %s" % exc, fg="yellow") # reset cache if did_install: diff --git a/platformio/builder/tools/pioplatform.py b/platformio/builder/tools/pioplatform.py index c8c2785f..d6e71e58 100644 --- a/platformio/builder/tools/pioplatform.py +++ b/platformio/builder/tools/pioplatform.py @@ -51,8 +51,8 @@ def BoardConfig(env, board=None): board = board or env.get("BOARD") assert board, "BoardConfig: Board is not defined" return p.board_config(board) - except (AssertionError, UnknownBoard) as e: - sys.stderr.write("Error: %s\n" % str(e)) + except (AssertionError, UnknownBoard) as exc: + sys.stderr.write("Error: %s\n" % str(exc)) env.Exit(1) return None diff --git a/platformio/builder/tools/pioupload.py b/platformio/builder/tools/pioupload.py index f85dc735..2229a9fb 100644 --- a/platformio/builder/tools/pioupload.py +++ b/platformio/builder/tools/pioupload.py @@ -109,8 +109,8 @@ def AutodetectUploadPort(*args, **kwargs): else: try: fs.ensure_udev_rules() - except exception.InvalidUdevRules as e: - sys.stderr.write("\n%s\n\n" % e) + except exception.InvalidUdevRules as exc: + sys.stderr.write("\n%s\n\n" % exc) env.Replace( UPLOAD_PORT=find_serial_port( initial_port=initial_port, diff --git a/platformio/commands/ci.py b/platformio/commands/ci.py index f1875b23..9364d1e9 100644 --- a/platformio/commands/ci.py +++ b/platformio/commands/ci.py @@ -39,8 +39,8 @@ def validate_path(ctx, param, value): # pylint: disable=unused-argument try: assert invalid_path is None return value - except AssertionError: - raise click.BadParameter("Found invalid path: %s" % invalid_path) + except AssertionError as exc: + raise click.BadParameter("Found invalid path: %s" % invalid_path) from exc @click.command("ci", short_help="Continuous Integration") diff --git a/platformio/commands/upgrade.py b/platformio/commands/upgrade.py index 7664732a..2766dbd5 100644 --- a/platformio/commands/upgrade.py +++ b/platformio/commands/upgrade.py @@ -71,9 +71,9 @@ def cli(dev): click.secho( "Warning! Please restart IDE to affect PIO Home changes", fg="yellow" ) - except Exception as e: # pylint: disable=broad-except + except Exception as exc: if not r: - raise exception.UpgradeError("\n".join([str(cmd), str(e)])) + raise exception.UpgradeError("\n".join([str(cmd), str(exc)])) from exc permission_errors = ("permission denied", "not permitted") if any(m in r["err"].lower() for m in permission_errors) and not IS_WINDOWS: click.secho( @@ -127,8 +127,8 @@ def get_latest_version(): except: # pylint: disable=bare-except pass return get_pypi_latest_version() - except: - raise exception.GetLatestVersionError() + except Exception as exc: + raise exception.GetLatestVersionError() from exc def get_develop_latest_version(): diff --git a/platformio/debug/cli.py b/platformio/debug/cli.py index 01e81f36..64bd1b43 100644 --- a/platformio/debug/cli.py +++ b/platformio/debug/cli.py @@ -129,11 +129,11 @@ def _debug_in_project_dir( try: fs.ensure_udev_rules() - except exception.InvalidUdevRules as e: + except exception.InvalidUdevRules as exc: click.echo( - helpers.escape_gdbmi_stream("~", str(e) + "\n") + helpers.escape_gdbmi_stream("~", str(exc) + "\n") if helpers.is_gdbmi_mode() - else str(e) + "\n", + else str(exc) + "\n", nl=False, ) diff --git a/platformio/debug/config/base.py b/platformio/debug/config/base.py index 46a91673..a5867340 100644 --- a/platformio/debug/config/base.py +++ b/platformio/debug/config/base.py @@ -203,8 +203,8 @@ class DebugConfigBase: # pylint: disable=too-many-instance-attributes def get_init_script(self, debugger): try: return getattr(self, "%s_INIT_SCRIPT" % debugger.upper()) - except AttributeError: - raise NotImplementedError + except AttributeError as exc: + raise NotImplementedError from exc def reveal_patterns(self, source, recursive=True): program_path = self.program_path or "" diff --git a/platformio/device/list/util.py b/platformio/device/list/util.py index 25387484..e82dc601 100644 --- a/platformio/device/list/util.py +++ b/platformio/device/list/util.py @@ -28,8 +28,8 @@ def list_serial_ports(filter_hwid=False, as_objects=False): try: # pylint: disable=import-outside-toplevel from serial.tools.list_ports import comports - except ImportError: - raise exception.GetSerialPortsError(os.name) + except ImportError as exc: + raise exception.GetSerialPortsError(os.name) from exc if as_objects: return comports() diff --git a/platformio/device/monitor/terminal.py b/platformio/device/monitor/terminal.py index 05c241c9..38c18390 100644 --- a/platformio/device/monitor/terminal.py +++ b/platformio/device/monitor/terminal.py @@ -137,9 +137,9 @@ def new_serial_instance(options): # pylint: disable=too-many-branches if port is None or port == "-": try: port = miniterm.ask_for_port() - except KeyboardInterrupt: + except KeyboardInterrupt as exc: click.echo("", err=True) - raise UserSideException("User aborted and port is not given") + raise UserSideException("User aborted and port is not given") from exc else: if not port: raise UserSideException("Port is not given") @@ -180,6 +180,6 @@ def new_serial_instance(options): # pylint: disable=too-many-branches serial_instance.open() except serial.SerialException as exc: - raise UserSideException(exc) + raise UserSideException(exc) from exc return serial_instance diff --git a/platformio/fs.py b/platformio/fs.py index 29dd118f..b6678cc7 100644 --- a/platformio/fs.py +++ b/platformio/fs.py @@ -54,8 +54,8 @@ def load_json(file_path): try: with open(file_path, mode="r", encoding="utf8") as f: return json.load(f) - except ValueError: - raise exception.InvalidJSONFile(file_path) + except ValueError as exc: + raise exception.InvalidJSONFile(file_path) from exc def humanize_file_size(filesize): @@ -231,9 +231,9 @@ def rmtree(path): if st_mode & stat.S_IREAD: os.chmod(path, st_mode | stat.S_IWRITE) func(path) - except Exception as e: # pylint: disable=broad-except + except Exception as exc: # pylint: disable=broad-except click.secho( - "%s \nPlease manually remove the file `%s`" % (str(e), path), + "%s \nPlease manually remove the file `%s`" % (str(exc), path), fg="red", err=True, ) diff --git a/platformio/home/rpc/handlers/account.py b/platformio/home/rpc/handlers/account.py index 23777437..d857d587 100644 --- a/platformio/home/rpc/handlers/account.py +++ b/platformio/home/rpc/handlers/account.py @@ -23,7 +23,7 @@ class AccountRPC: try: client = AccountClient() return getattr(client, method)(*args, **kwargs) - except Exception as e: # pylint: disable=bare-except + except Exception as exc: # pylint: disable=bare-except raise JSONRPC20DispatchException( - code=4003, message="PIO Account Call Error", data=str(e) - ) + code=4003, message="PIO Account Call Error", data=str(exc) + ) from exc diff --git a/platformio/home/rpc/handlers/piocore.py b/platformio/home/rpc/handlers/piocore.py index add05a31..a1098f3a 100644 --- a/platformio/home/rpc/handlers/piocore.py +++ b/platformio/home/rpc/handlers/piocore.py @@ -94,10 +94,10 @@ class PIOCoreRPC: # fall-back to subprocess method result = await PIOCoreRPC._call_subprocess(args, options) return PIOCoreRPC._process_result(result, to_json) - except Exception as e: # pylint: disable=bare-except + except Exception as exc: # pylint: disable=bare-except raise JSONRPC20DispatchException( - code=4003, message="PIO Core Call Error", data=str(e) - ) + code=4003, message="PIO Core Call Error", data=str(exc) + ) from exc @staticmethod async def _call_subprocess(args, options): @@ -139,8 +139,8 @@ class PIOCoreRPC: return text try: return json.loads(out) - except ValueError as e: - click.secho("%s => `%s`" % (e, out), fg="red", err=True) + except ValueError as exc: + click.secho("%s => `%s`" % (exc, out), fg="red", err=True) # if PIO Core prints unhandled warnings for line in out.split("\n"): line = line.strip() @@ -150,4 +150,4 @@ class PIOCoreRPC: return json.loads(line) except ValueError: pass - raise e + raise exc diff --git a/platformio/http.py b/platformio/http.py index 5f5fbdd2..2b31411f 100644 --- a/platformio/http.py +++ b/platformio/http.py @@ -132,11 +132,11 @@ class HTTPClient(object): except ( requests.exceptions.ConnectionError, requests.exceptions.Timeout, - ) as e: + ) as exc: try: self._next_session() - except: # pylint: disable=bare-except - raise HTTPClientError(str(e)) + except Exception as exc2: + raise HTTPClientError(str(exc2)) from exc def fetch_json_data(self, method, path, **kwargs): if method not in ("get", "head", "options"): diff --git a/platformio/package/commands/exec.py b/platformio/package/commands/exec.py index b5484f73..fc100f19 100644 --- a/platformio/package/commands/exec.py +++ b/platformio/package/commands/exec.py @@ -67,7 +67,7 @@ def package_exec_cmd(obj, package, call, args): if force_click_stream: click.echo(result.stdout.decode().strip(), err=result.returncode != 0) except Exception as exc: - raise UserSideException(exc) + raise UserSideException(exc) from exc if result and result.returncode != 0: raise ReturnErrorCode(result.returncode) diff --git a/platformio/package/commands/pack.py b/platformio/package/commands/pack.py index c80995e4..038ffc15 100644 --- a/platformio/package/commands/pack.py +++ b/platformio/package/commands/pack.py @@ -39,7 +39,7 @@ def package_pack_cmd(package, output): ManifestSchema().load_manifest( ManifestParserFactory.new_from_archive(archive_path).as_dict() ) - except ManifestValidationError as e: + except ManifestValidationError as exc: os.remove(archive_path) - raise e + raise exc click.secho('Wrote a tarball to "%s"' % archive_path, fg="green") diff --git a/platformio/package/commands/publish.py b/platformio/package/commands/publish.py index 6d2c73ed..8d282fa0 100644 --- a/platformio/package/commands/publish.py +++ b/platformio/package/commands/publish.py @@ -36,8 +36,8 @@ def validate_datetime(ctx, param, value): # pylint: disable=unused-argument return value try: datetime.strptime(value, "%Y-%m-%d %H:%M:%S") - except ValueError as e: - raise click.BadParameter(e) + except ValueError as exc: + raise click.BadParameter(exc) return value diff --git a/platformio/package/lockfile.py b/platformio/package/lockfile.py index 296036aa..3a410a60 100644 --- a/platformio/package/lockfile.py +++ b/platformio/package/lockfile.py @@ -72,10 +72,10 @@ class LockFile(object): msvcrt.locking( # pylint: disable=used-before-assignment self._fp.fileno(), msvcrt.LK_NBLCK, 1 ) - except (BlockingIOError, IOError): + except (BlockingIOError, IOError) as exc: self._fp.close() self._fp = None - raise LockFileExists + raise LockFileExists from exc return True def _unlock(self): diff --git a/platformio/package/manager/_download.py b/platformio/package/manager/_download.py index e408908a..0c073e11 100644 --- a/platformio/package/manager/_download.py +++ b/platformio/package/manager/_download.py @@ -70,7 +70,7 @@ class PackageManagerDownloadMixin(object): fd = FileDownloader(url) fd.set_destination(tmp_path) fd.start(with_progress=with_progress, silent=silent) - except IOError as e: + except IOError as exc: raise_error = not with_progress if with_progress: try: @@ -86,7 +86,7 @@ class PackageManagerDownloadMixin(object): fg="red", ) ) - raise e + raise exc if checksum: fd.verify(checksum) os.close(tmp_fd) diff --git a/platformio/package/manager/_install.py b/platformio/package/manager/_install.py index 8129d9b0..a885b68f 100644 --- a/platformio/package/manager/_install.py +++ b/platformio/package/manager/_install.py @@ -36,9 +36,9 @@ class PackageManagerInstallMixin(object): try: with FileUnpacker(src) as fu: return fu.unpack(dst, with_progress=with_progress) - except IOError as e: + except IOError as exc: if not with_progress: - raise e + raise exc with FileUnpacker(src) as fu: return fu.unpack(dst, with_progress=False) diff --git a/platformio/package/manager/_registry.py b/platformio/package/manager/_registry.py index 0a9f39c5..f861ddf4 100644 --- a/platformio/package/manager/_registry.py +++ b/platformio/package/manager/_registry.py @@ -56,9 +56,9 @@ class PackageManagerRegistryMixin(object): ), checksum or pkgfile["checksum"]["sha256"], ) - except Exception as e: # pylint: disable=broad-except + except Exception as exc: # pylint: disable=broad-except self.log.warning( - click.style("Warning! Package Mirror: %s" % e, fg="yellow") + click.style("Warning! Package Mirror: %s" % exc, fg="yellow") ) self.log.warning( click.style("Looking for another mirror...", fg="yellow") diff --git a/platformio/package/manager/base.py b/platformio/package/manager/base.py index b692140f..c90b940f 100644 --- a/platformio/package/manager/base.py +++ b/platformio/package/manager/base.py @@ -187,9 +187,9 @@ class BasePackageManager( # pylint: disable=too-many-public-methods,too-many-in result = ManifestParserFactory.new_from_file(item).as_dict() self.memcache_set(cache_key, result) return result - except ManifestException as e: + except ManifestException as exc: if not PlatformioCLI.in_silence(): - self.log.warning(click.style(str(e), fg="yellow")) + self.log.warning(click.style(str(exc), fg="yellow")) raise MissingPackageManifestError(", ".join(self.manifest_names)) @staticmethod diff --git a/platformio/package/manager/core.py b/platformio/package/manager/core.py index d9a05cb5..28fab07b 100644 --- a/platformio/package/manager/core.py +++ b/platformio/package/manager/core.py @@ -156,7 +156,7 @@ def build_contrib_pysite_package(target_dir, with_metadata=True): raise UserSideException( "\n\nPlease ensure that the next packages are installed:\n\n" "sudo apt install python3-dev libffi-dev libssl-dev\n" - ) + ) from exc raise exc # build manifests diff --git a/platformio/package/manager/platform.py b/platformio/package/manager/platform.py index 41f7b41e..e5e948ba 100644 --- a/platformio/package/manager/platform.py +++ b/platformio/package/manager/platform.py @@ -53,9 +53,9 @@ class PlatformPackageManager(BasePackageManager): # pylint: disable=too-many-an # set logging level for underlying tool manager p.pm.set_log_level(self.log.getEffectiveLevel()) p.ensure_engine_compatible() - except IncompatiblePlatform as e: + except IncompatiblePlatform as exc: super().uninstall(pkg, skip_dependencies=True) - raise e + raise exc if project_env: p.configure_project_packages(project_env, project_targets) if not skip_dependencies: diff --git a/platformio/package/manifest/parser.py b/platformio/package/manifest/parser.py index 8735bcff..8b0c4e87 100644 --- a/platformio/package/manifest/parser.py +++ b/platformio/package/manifest/parser.py @@ -61,9 +61,9 @@ class ManifestParserFactory(object): try: with io.open(path, encoding=encoding) as fp: return fp.read() - except UnicodeDecodeError as e: - last_err = e - raise last_err # pylint: disable=raising-bad-type + except UnicodeDecodeError as exc: + last_err = exc + raise last_err @classmethod def new_from_file(cls, path, remote_url=False): @@ -145,8 +145,8 @@ class BaseManifestParser(object): self.package_dir = package_dir try: self._data = self.parse(contents) - except Exception as e: - raise ManifestParserError("Could not parse manifest -> %s" % e) + except Exception as exc: + raise ManifestParserError("Could not parse manifest -> %s" % exc) from exc self._data = self.normalize_repository(self._data) self._data = self.parse_examples(self._data) diff --git a/platformio/package/manifest/schema.py b/platformio/package/manifest/schema.py index 8258dfe8..8f8a7d16 100644 --- a/platformio/package/manifest/schema.py +++ b/platformio/package/manifest/schema.py @@ -243,17 +243,17 @@ class ManifestSchema(BaseSchema): if "Invalid leading zero" in str(exc): raise exc semantic_version.Version.coerce(value) - except (AssertionError, ValueError): + except (AssertionError, ValueError) as exc: raise ValidationError( "Invalid semantic versioning format, see https://semver.org/" - ) + ) from exc @validates("license") def validate_license(self, value): try: spdx = self.load_spdx_licenses() - except requests.exceptions.RequestException: - raise ValidationError("Could not load SPDX licenses for validation") + except requests.exceptions.RequestException as exc: + raise ValidationError("Could not load SPDX licenses for validation") from exc known_ids = set(item.get("licenseId") for item in spdx.get("licenses", [])) if value in known_ids: return True diff --git a/platformio/package/vcsclient.py b/platformio/package/vcsclient.py index dc4c090d..9299ada9 100644 --- a/platformio/package/vcsclient.py +++ b/platformio/package/vcsclient.py @@ -51,8 +51,8 @@ class VCSClientFactory(object): ) assert isinstance(obj, VCSClientBase) return obj - except (KeyError, AssertionError): - raise VCSBaseException("VCS: Unknown repository type %s" % remote_url) + except (KeyError, AssertionError) as exc: + raise VCSBaseException("VCS: Unknown repository type %s" % remote_url) from exc class VCSClientBase(object): @@ -73,10 +73,10 @@ class VCSClientBase(object): self.get_cmd_output(["--version"]) else: assert self.run_cmd(["--version"]) - except (AssertionError, OSError, PlatformioException): + except (AssertionError, OSError, PlatformioException) as exc: raise UserSideException( "VCS: `%s` client is not installed in your system" % self.command - ) + ) from exc return True @property @@ -108,8 +108,8 @@ class VCSClientBase(object): try: subprocess.check_call(args, **kwargs) return True - except subprocess.CalledProcessError as e: - raise VCSBaseException("VCS: Could not process command %s" % e.cmd) + except subprocess.CalledProcessError as exc: + raise VCSBaseException("VCS: Could not process command %s" % exc.cmd) from exc def get_cmd_output(self, args, **kwargs): args = [self.command] + args @@ -152,10 +152,10 @@ class GitClient(VCSClientBase): def check_client(self): try: return VCSClientBase.check_client(self) - except UserSideException: + except UserSideException as exc: raise UserSideException( "Please install Git client from https://git-scm.com/downloads" - ) + ) from exc def get_branches(self): output = self.get_cmd_output(["branch"]) diff --git a/platformio/platform/board.py b/platformio/platform/board.py index 2e998ac0..fa0cdf9c 100644 --- a/platformio/platform/board.py +++ b/platformio/platform/board.py @@ -28,8 +28,8 @@ class PlatformBoardConfig(object): self.manifest_path = manifest_path try: self._manifest = fs.load_json(manifest_path) - except ValueError: - raise InvalidBoardManifest(manifest_path) + except ValueError as exc: + raise InvalidBoardManifest(manifest_path) from exc if not set(["name", "url", "vendor"]) <= set(self._manifest): raise UserSideException( "Please specify name, url and vendor fields for " + manifest_path diff --git a/platformio/platform/factory.py b/platformio/platform/factory.py index 0345cb2a..72b44790 100644 --- a/platformio/platform/factory.py +++ b/platformio/platform/factory.py @@ -35,8 +35,8 @@ class PlatformFactory(object): sys.modules["platformio.managers.platform"] = base try: return load_python_module("platformio.platform.%s" % name, path) - except ImportError: - raise UnknownPlatform(name) + except ImportError as exc: + raise UnknownPlatform(name) from exc @classmethod def new(cls, pkg_or_spec, autoinstall=False) -> base.PlatformBase: diff --git a/platformio/proc.py b/platformio/proc.py index 83943273..f32fe715 100644 --- a/platformio/proc.py +++ b/platformio/proc.py @@ -115,8 +115,8 @@ def exec_command(*args, **kwargs): try: result["out"], result["err"] = p.communicate() result["returncode"] = p.returncode - except KeyboardInterrupt: - raise exception.AbortedByUser() + except KeyboardInterrupt as exc: + raise exception.AbortedByUser() from exc finally: for s in ("stdout", "stderr"): if isinstance(kwargs[s], AsyncPipeBase): diff --git a/platformio/project/commands/init.py b/platformio/project/commands/init.py index 7c3b77cb..0f3b719b 100644 --- a/platformio/project/commands/init.py +++ b/platformio/project/commands/init.py @@ -34,11 +34,11 @@ def validate_boards(ctx, param, value): # pylint: disable=W0613 for id_ in value: try: pm.board_config(id_) - except UnknownBoard: + except UnknownBoard as exc: raise click.BadParameter( "`%s`. Please search for board ID using `platformio boards` " "command" % id_ - ) + ) from exc return value diff --git a/platformio/project/config.py b/platformio/project/config.py index 999827d5..e9440bc9 100644 --- a/platformio/project/config.py +++ b/platformio/project/config.py @@ -97,8 +97,8 @@ class ProjectConfigBase(object): self._parsed.append(path) try: self._parser.read(path, "utf-8") - except configparser.Error as e: - raise exception.InvalidProjectConfError(path, str(e)) + except configparser.Error as exc: + raise exception.InvalidProjectConfError(path, str(exc)) if not parse_extra: return @@ -324,10 +324,10 @@ class ProjectConfigBase(object): # handle nested calls try: value = self.get(section, option) - except RecursionError: + except RecursionError as exc: raise exception.ProjectOptionValueError( "Infinite recursion has been detected", option, section - ) + ) from exc if isinstance(value, list): return "\n".join(value) return str(value) @@ -336,8 +336,8 @@ class ProjectConfigBase(object): value = None try: value = self.getraw(section, option, default) - except configparser.Error as e: - raise exception.InvalidProjectConfError(self.path, str(e)) + except configparser.Error as exc: + raise exception.InvalidProjectConfError(self.path, str(exc)) option_meta = self.find_option_meta(section, option) if not option_meta: @@ -349,10 +349,10 @@ class ProjectConfigBase(object): value = self.parse_multi_values(value or []) try: return self.cast_to(value, option_meta.type) - except click.BadParameter as e: + except click.BadParameter as exc: if not self.expand_interpolations: return value - raise exception.ProjectOptionValueError(e.format_message(), option, section) + raise exception.ProjectOptionValueError(exc.format_message(), option, section) @staticmethod def cast_to(value, to_type): diff --git a/platformio/registry/client.py b/platformio/registry/client.py index 2c465e0c..a682db57 100644 --- a/platformio/registry/client.py +++ b/platformio/registry/client.py @@ -153,7 +153,7 @@ class RegistryClient(HTTPClient): x_cache_valid="1h", x_with_authorization=self.allowed_private_packages(), ) - except HTTPClientError as e: - if e.response is not None and e.response.status_code == 404: + except HTTPClientError as exc: + if exc.response is not None and exc.response.status_code == 404: return None - raise e + raise exc diff --git a/platformio/remote/ac/base.py b/platformio/remote/ac/base.py index 7b76a327..e92118c9 100644 --- a/platformio/remote/ac/base.py +++ b/platformio/remote/ac/base.py @@ -30,8 +30,8 @@ class AsyncCommandBase(object): try: self.start() - except Exception as e: - raise pb.Error(str(e)) + except Exception as exc: + raise pb.Error(str(exc)) from exc @property def id(self): diff --git a/platformio/remote/client/agent_service.py b/platformio/remote/client/agent_service.py index ac227795..3a884e6e 100644 --- a/platformio/remote/client/agent_service.py +++ b/platformio/remote/client/agent_service.py @@ -164,8 +164,8 @@ class RemoteAgentService(RemoteClientBase): origin_pio_ini, (os.path.getatime(back_pio_ini), os.path.getmtime(back_pio_ini)), ) - except NotPlatformIOProjectError as e: - raise pb.Error(str(e)) + except NotPlatformIOProjectError as exc: + raise pb.Error(str(exc)) from exc cmd_args = ["platformio", "--force", command, "-d", project_dir] for env in options.get("environment", []): diff --git a/platformio/remote/factory/client.py b/platformio/remote/factory/client.py index 2565e6ad..b9e3cd5a 100644 --- a/platformio/remote/factory/client.py +++ b/platformio/remote/factory/client.py @@ -38,10 +38,10 @@ class RemoteClientFactory(pb.PBClientFactory, protocol.ReconnectingClientFactory auth_token = None try: auth_token = AccountClient().fetch_authentication_token() - except Exception as e: # pylint:disable=broad-except + except Exception as exc: # pylint:disable=broad-except d = defer.Deferred() d.addErrback(self.clientAuthorizationFailed) - d.errback(pb.Error(e)) + d.errback(pb.Error(exc)) return d d = self.login( diff --git a/platformio/telemetry.py b/platformio/telemetry.py index c0fbf97d..8606e48e 100644 --- a/platformio/telemetry.py +++ b/platformio/telemetry.py @@ -274,11 +274,11 @@ class MPDataPusher(object): ) r.raise_for_status() return True - except requests.exceptions.HTTPError as e: + except requests.exceptions.HTTPError as exc: # skip Bad Request - if 400 >= e.response.status_code < 500: + if 400 >= exc.response.status_code < 500: return True - except: # pylint: disable=W0702 + except: # pylint: disable=bare-except pass self._http_offline = True return False diff --git a/platformio/test/runners/base.py b/platformio/test/runners/base.py index 218e0c11..73d3b731 100644 --- a/platformio/test/runners/base.py +++ b/platformio/test/runners/base.py @@ -128,11 +128,11 @@ class TestRunnerBase: targets.append("checkprogsize") try: return self.run_project_targets(targets) - except ReturnErrorCode: + except ReturnErrorCode as exc: raise UnitTestSuiteError( "Building stage has failed, see errors above. " "Use `pio test -vvv` option to enable verbose output." - ) + ) from exc def stage_uploading(self): is_embedded = self.platform.is_embedded() @@ -150,11 +150,11 @@ class TestRunnerBase: targets.append("__debug") try: return self.run_project_targets(targets) - except ReturnErrorCode: + except ReturnErrorCode as exc: raise UnitTestSuiteError( "Uploading stage has failed, see errors above. " "Use `pio test -vvv` option to enable verbose output." - ) + ) from exc def stage_testing(self): if self.options.without_testing: diff --git a/platformio/test/runners/factory.py b/platformio/test/runners/factory.py index 6c428316..64381807 100644 --- a/platformio/test/runners/factory.py +++ b/platformio/test/runners/factory.py @@ -56,11 +56,11 @@ class TestRunnerFactory(object): try: mod = load_python_module(module_name, custom_runner_path) - except (FileNotFoundError, ImportError): + except (FileNotFoundError, ImportError) as exc: raise UserSideException( "Could not find custom test runner " f"by this path -> {custom_runner_path}" - ) + ) from exc else: mod = importlib.import_module(module_name) runner_cls = getattr(mod, cls.get_clsname(test_framework)) diff --git a/platformio/test/runners/readers/program.py b/platformio/test/runners/readers/program.py index b0b33130..82cc6a2a 100644 --- a/platformio/test/runners/readers/program.py +++ b/platformio/test/runners/readers/program.py @@ -108,8 +108,8 @@ class ProgramTestOutputReader: raise UnitTestError( f"Program received signal {sig.name} ({signal_description})" ) - except ValueError: - raise UnitTestError("Program errored with %d code" % return_code) + except ValueError as exc: + raise UnitTestError("Program errored with %d code" % return_code) from exc def begin(self): try: diff --git a/platformio/test/runners/readers/serial.py b/platformio/test/runners/readers/serial.py index e2a7eddb..da4b1a05 100644 --- a/platformio/test/runners/readers/serial.py +++ b/platformio/test/runners/readers/serial.py @@ -45,8 +45,8 @@ class SerialTestOutputReader: ser.rts = self.test_runner.options.monitor_rts ser.dtr = self.test_runner.options.monitor_dtr ser.open() - except serial.SerialException as e: - click.secho(str(e), fg="red", err=True) + except serial.SerialException as exc: + click.secho(str(exc), fg="red", err=True) return None if not self.test_runner.options.no_reset: diff --git a/tests/package/test_manifest.py b/tests/package/test_manifest.py index c16ce04b..828412f4 100644 --- a/tests/package/test_manifest.py +++ b/tests/package/test_manifest.py @@ -531,9 +531,9 @@ includes=MozziGuts.h errors = None try: ManifestSchema().load_manifest(raw_data) - except ManifestValidationError as e: - data = e.valid_data - errors = e.messages + except ManifestValidationError as exc: + data = exc.valid_data + errors = exc.messages assert errors["authors"]