Fix PyLint: Consider explicitly re-raising

This commit is contained in:
Ivan Kravets
2022-07-02 18:37:57 +03:00
parent f01cd7570c
commit 19d518fc4c
45 changed files with 136 additions and 138 deletions

View File

@ -16,8 +16,4 @@ disable=
useless-import-alias, useless-import-alias,
bad-option-value, bad-option-value,
consider-using-dict-items, consider-using-dict-items,
consider-using-f-string, consider-using-f-string
; PY2 Compat
super-with-arguments,
raise-missing-from

View File

@ -100,15 +100,15 @@ def main(argv=None):
ensure_python3(raise_exception=True) ensure_python3(raise_exception=True)
configure() configure()
cli() # pylint: disable=no-value-for-parameter cli() # pylint: disable=no-value-for-parameter
except SystemExit as e: except SystemExit as exc:
if e.code and str(e.code).isdigit(): if exc.code and str(exc.code).isdigit():
exit_code = int(e.code) exit_code = int(exc.code)
except Exception as e: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
if not isinstance(e, exception.ReturnErrorCode): if not isinstance(exc, exception.ReturnErrorCode):
maintenance.on_platformio_exception(e) maintenance.on_platformio_exception(exc)
error_str = "Error: " error_str = "Error: "
if isinstance(e, exception.PlatformioException): if isinstance(exc, exception.PlatformioException):
error_str += str(e) error_str += str(exc)
else: else:
error_str += format_exc() error_str += format_exc()
error_str += """ error_str += """
@ -128,7 +128,7 @@ An unexpected error occurred. Further steps:
============================================================ ============================================================
""" """
click.secho(error_str, fg="red", err=True) 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 sys.argv = prev_sys_argv
return exit_code return exit_code

View File

@ -46,8 +46,8 @@ class AccountClient(HTTPClient): # pylint:disable=too-many-public-methods
def get_refresh_token(): def get_refresh_token():
try: try:
return app.get_state_item("account").get("auth").get("refresh_token") return app.get_state_item("account").get("auth").get("refresh_token")
except: # pylint:disable=bare-except except Exception as exc:
raise AccountNotAuthorized() raise AccountNotAuthorized() from exc
@staticmethod @staticmethod
def delete_local_session(): def delete_local_session():

View File

@ -103,8 +103,10 @@ class State(object):
try: try:
with open(self.path, mode="w", encoding="utf8") as fp: with open(self.path, mode="w", encoding="utf8") as fp:
fp.write(json.dumps(self._storage)) fp.write(json.dumps(self._storage))
except IOError: except IOError as exc:
raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) raise exception.HomeDirPermissionsError(
os.path.dirname(self.path)
) from exc
self._unlock_state_file() self._unlock_state_file()
def _lock_state_file(self): def _lock_state_file(self):
@ -113,8 +115,8 @@ class State(object):
self._lockfile = LockFile(self.path) self._lockfile = LockFile(self.path)
try: try:
self._lockfile.acquire() self._lockfile.acquire()
except IOError: except IOError as exc:
raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) raise exception.HomeDirPermissionsError(os.path.dirname(self.path)) from exc
def _unlock_state_file(self): def _unlock_state_file(self):
if hasattr(self, "_lockfile") and self._lockfile: 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") value = str(value).lower() in ("true", "yes", "y", "1")
elif isinstance(defdata["value"], int): elif isinstance(defdata["value"], int):
value = int(value) value = int(value)
except Exception: except Exception as exc:
raise exception.InvalidSettingValue(value, name) raise exception.InvalidSettingValue(value, name) from exc
return value return value

View File

@ -360,11 +360,11 @@ class LibBuilderBase:
depth=self.CCONDITIONAL_SCANNER_DEPTH, 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: if self.verbose and "+" in self.lib_ldf_mode:
sys.stderr.write( sys.stderr.write(
"Warning! Classic Pre Processor is used for `%s`, " "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( candidates = self.env.File(path).get_implicit_deps(
self.env, self.env,
@ -956,8 +956,8 @@ class ProjectAsLibBuilder(LibBuilderBase):
try: try:
lm.install(spec) lm.install(spec)
did_install = True did_install = True
except (HTTPClientError, UnknownPackageError, InternetIsOffline) as e: except (HTTPClientError, UnknownPackageError, InternetIsOffline) as exc:
click.secho("Warning! %s" % e, fg="yellow") click.secho("Warning! %s" % exc, fg="yellow")
# reset cache # reset cache
if did_install: if did_install:

View File

@ -51,8 +51,8 @@ def BoardConfig(env, board=None):
board = board or env.get("BOARD") board = board or env.get("BOARD")
assert board, "BoardConfig: Board is not defined" assert board, "BoardConfig: Board is not defined"
return p.board_config(board) return p.board_config(board)
except (AssertionError, UnknownBoard) as e: except (AssertionError, UnknownBoard) as exc:
sys.stderr.write("Error: %s\n" % str(e)) sys.stderr.write("Error: %s\n" % str(exc))
env.Exit(1) env.Exit(1)
return None return None

View File

@ -109,8 +109,8 @@ def AutodetectUploadPort(*args, **kwargs):
else: else:
try: try:
fs.ensure_udev_rules() fs.ensure_udev_rules()
except exception.InvalidUdevRules as e: except exception.InvalidUdevRules as exc:
sys.stderr.write("\n%s\n\n" % e) sys.stderr.write("\n%s\n\n" % exc)
env.Replace( env.Replace(
UPLOAD_PORT=find_serial_port( UPLOAD_PORT=find_serial_port(
initial_port=initial_port, initial_port=initial_port,

View File

@ -39,8 +39,8 @@ def validate_path(ctx, param, value): # pylint: disable=unused-argument
try: try:
assert invalid_path is None assert invalid_path is None
return value return value
except AssertionError: except AssertionError as exc:
raise click.BadParameter("Found invalid path: %s" % invalid_path) raise click.BadParameter("Found invalid path: %s" % invalid_path) from exc
@click.command("ci", short_help="Continuous Integration") @click.command("ci", short_help="Continuous Integration")

View File

@ -71,9 +71,9 @@ def cli(dev):
click.secho( click.secho(
"Warning! Please restart IDE to affect PIO Home changes", fg="yellow" "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: 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") permission_errors = ("permission denied", "not permitted")
if any(m in r["err"].lower() for m in permission_errors) and not IS_WINDOWS: if any(m in r["err"].lower() for m in permission_errors) and not IS_WINDOWS:
click.secho( click.secho(
@ -127,8 +127,8 @@ def get_latest_version():
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
pass pass
return get_pypi_latest_version() return get_pypi_latest_version()
except: except Exception as exc:
raise exception.GetLatestVersionError() raise exception.GetLatestVersionError() from exc
def get_develop_latest_version(): def get_develop_latest_version():

View File

@ -129,11 +129,11 @@ def _debug_in_project_dir(
try: try:
fs.ensure_udev_rules() fs.ensure_udev_rules()
except exception.InvalidUdevRules as e: except exception.InvalidUdevRules as exc:
click.echo( click.echo(
helpers.escape_gdbmi_stream("~", str(e) + "\n") helpers.escape_gdbmi_stream("~", str(exc) + "\n")
if helpers.is_gdbmi_mode() if helpers.is_gdbmi_mode()
else str(e) + "\n", else str(exc) + "\n",
nl=False, nl=False,
) )

View File

@ -203,8 +203,8 @@ class DebugConfigBase: # pylint: disable=too-many-instance-attributes
def get_init_script(self, debugger): def get_init_script(self, debugger):
try: try:
return getattr(self, "%s_INIT_SCRIPT" % debugger.upper()) return getattr(self, "%s_INIT_SCRIPT" % debugger.upper())
except AttributeError: except AttributeError as exc:
raise NotImplementedError raise NotImplementedError from exc
def reveal_patterns(self, source, recursive=True): def reveal_patterns(self, source, recursive=True):
program_path = self.program_path or "" program_path = self.program_path or ""

View File

@ -28,8 +28,8 @@ def list_serial_ports(filter_hwid=False, as_objects=False):
try: try:
# pylint: disable=import-outside-toplevel # pylint: disable=import-outside-toplevel
from serial.tools.list_ports import comports from serial.tools.list_ports import comports
except ImportError: except ImportError as exc:
raise exception.GetSerialPortsError(os.name) raise exception.GetSerialPortsError(os.name) from exc
if as_objects: if as_objects:
return comports() return comports()

View File

@ -137,9 +137,9 @@ def new_serial_instance(options): # pylint: disable=too-many-branches
if port is None or port == "-": if port is None or port == "-":
try: try:
port = miniterm.ask_for_port() port = miniterm.ask_for_port()
except KeyboardInterrupt: except KeyboardInterrupt as exc:
click.echo("", err=True) 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: else:
if not port: if not port:
raise UserSideException("Port is not given") raise UserSideException("Port is not given")
@ -180,6 +180,6 @@ def new_serial_instance(options): # pylint: disable=too-many-branches
serial_instance.open() serial_instance.open()
except serial.SerialException as exc: except serial.SerialException as exc:
raise UserSideException(exc) raise UserSideException(exc) from exc
return serial_instance return serial_instance

View File

@ -54,8 +54,8 @@ def load_json(file_path):
try: try:
with open(file_path, mode="r", encoding="utf8") as f: with open(file_path, mode="r", encoding="utf8") as f:
return json.load(f) return json.load(f)
except ValueError: except ValueError as exc:
raise exception.InvalidJSONFile(file_path) raise exception.InvalidJSONFile(file_path) from exc
def humanize_file_size(filesize): def humanize_file_size(filesize):
@ -231,9 +231,9 @@ def rmtree(path):
if st_mode & stat.S_IREAD: if st_mode & stat.S_IREAD:
os.chmod(path, st_mode | stat.S_IWRITE) os.chmod(path, st_mode | stat.S_IWRITE)
func(path) func(path)
except Exception as e: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
click.secho( click.secho(
"%s \nPlease manually remove the file `%s`" % (str(e), path), "%s \nPlease manually remove the file `%s`" % (str(exc), path),
fg="red", fg="red",
err=True, err=True,
) )

View File

@ -23,7 +23,7 @@ class AccountRPC:
try: try:
client = AccountClient() client = AccountClient()
return getattr(client, method)(*args, **kwargs) return getattr(client, method)(*args, **kwargs)
except Exception as e: # pylint: disable=bare-except except Exception as exc: # pylint: disable=bare-except
raise JSONRPC20DispatchException( raise JSONRPC20DispatchException(
code=4003, message="PIO Account Call Error", data=str(e) code=4003, message="PIO Account Call Error", data=str(exc)
) ) from exc

View File

@ -94,10 +94,10 @@ class PIOCoreRPC:
# fall-back to subprocess method # fall-back to subprocess method
result = await PIOCoreRPC._call_subprocess(args, options) result = await PIOCoreRPC._call_subprocess(args, options)
return PIOCoreRPC._process_result(result, to_json) 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( 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 @staticmethod
async def _call_subprocess(args, options): async def _call_subprocess(args, options):
@ -139,8 +139,8 @@ class PIOCoreRPC:
return text return text
try: try:
return json.loads(out) return json.loads(out)
except ValueError as e: except ValueError as exc:
click.secho("%s => `%s`" % (e, out), fg="red", err=True) click.secho("%s => `%s`" % (exc, out), fg="red", err=True)
# if PIO Core prints unhandled warnings # if PIO Core prints unhandled warnings
for line in out.split("\n"): for line in out.split("\n"):
line = line.strip() line = line.strip()
@ -150,4 +150,4 @@ class PIOCoreRPC:
return json.loads(line) return json.loads(line)
except ValueError: except ValueError:
pass pass
raise e raise exc

View File

@ -132,11 +132,11 @@ class HTTPClient(object):
except ( except (
requests.exceptions.ConnectionError, requests.exceptions.ConnectionError,
requests.exceptions.Timeout, requests.exceptions.Timeout,
) as e: ) as exc:
try: try:
self._next_session() self._next_session()
except: # pylint: disable=bare-except except Exception as exc2:
raise HTTPClientError(str(e)) raise HTTPClientError(str(exc2)) from exc
def fetch_json_data(self, method, path, **kwargs): def fetch_json_data(self, method, path, **kwargs):
if method not in ("get", "head", "options"): if method not in ("get", "head", "options"):

View File

@ -67,7 +67,7 @@ def package_exec_cmd(obj, package, call, args):
if force_click_stream: if force_click_stream:
click.echo(result.stdout.decode().strip(), err=result.returncode != 0) click.echo(result.stdout.decode().strip(), err=result.returncode != 0)
except Exception as exc: except Exception as exc:
raise UserSideException(exc) raise UserSideException(exc) from exc
if result and result.returncode != 0: if result and result.returncode != 0:
raise ReturnErrorCode(result.returncode) raise ReturnErrorCode(result.returncode)

View File

@ -39,7 +39,7 @@ def package_pack_cmd(package, output):
ManifestSchema().load_manifest( ManifestSchema().load_manifest(
ManifestParserFactory.new_from_archive(archive_path).as_dict() ManifestParserFactory.new_from_archive(archive_path).as_dict()
) )
except ManifestValidationError as e: except ManifestValidationError as exc:
os.remove(archive_path) os.remove(archive_path)
raise e raise exc
click.secho('Wrote a tarball to "%s"' % archive_path, fg="green") click.secho('Wrote a tarball to "%s"' % archive_path, fg="green")

View File

@ -36,8 +36,8 @@ def validate_datetime(ctx, param, value): # pylint: disable=unused-argument
return value return value
try: try:
datetime.strptime(value, "%Y-%m-%d %H:%M:%S") datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
except ValueError as e: except ValueError as exc:
raise click.BadParameter(e) raise click.BadParameter(exc)
return value return value

View File

@ -72,10 +72,10 @@ class LockFile(object):
msvcrt.locking( # pylint: disable=used-before-assignment msvcrt.locking( # pylint: disable=used-before-assignment
self._fp.fileno(), msvcrt.LK_NBLCK, 1 self._fp.fileno(), msvcrt.LK_NBLCK, 1
) )
except (BlockingIOError, IOError): except (BlockingIOError, IOError) as exc:
self._fp.close() self._fp.close()
self._fp = None self._fp = None
raise LockFileExists raise LockFileExists from exc
return True return True
def _unlock(self): def _unlock(self):

View File

@ -70,7 +70,7 @@ class PackageManagerDownloadMixin(object):
fd = FileDownloader(url) fd = FileDownloader(url)
fd.set_destination(tmp_path) fd.set_destination(tmp_path)
fd.start(with_progress=with_progress, silent=silent) fd.start(with_progress=with_progress, silent=silent)
except IOError as e: except IOError as exc:
raise_error = not with_progress raise_error = not with_progress
if with_progress: if with_progress:
try: try:
@ -86,7 +86,7 @@ class PackageManagerDownloadMixin(object):
fg="red", fg="red",
) )
) )
raise e raise exc
if checksum: if checksum:
fd.verify(checksum) fd.verify(checksum)
os.close(tmp_fd) os.close(tmp_fd)

View File

@ -36,9 +36,9 @@ class PackageManagerInstallMixin(object):
try: try:
with FileUnpacker(src) as fu: with FileUnpacker(src) as fu:
return fu.unpack(dst, with_progress=with_progress) return fu.unpack(dst, with_progress=with_progress)
except IOError as e: except IOError as exc:
if not with_progress: if not with_progress:
raise e raise exc
with FileUnpacker(src) as fu: with FileUnpacker(src) as fu:
return fu.unpack(dst, with_progress=False) return fu.unpack(dst, with_progress=False)

View File

@ -56,9 +56,9 @@ class PackageManagerRegistryMixin(object):
), ),
checksum or pkgfile["checksum"]["sha256"], checksum or pkgfile["checksum"]["sha256"],
) )
except Exception as e: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
self.log.warning( self.log.warning(
click.style("Warning! Package Mirror: %s" % e, fg="yellow") click.style("Warning! Package Mirror: %s" % exc, fg="yellow")
) )
self.log.warning( self.log.warning(
click.style("Looking for another mirror...", fg="yellow") click.style("Looking for another mirror...", fg="yellow")

View File

@ -187,9 +187,9 @@ class BasePackageManager( # pylint: disable=too-many-public-methods,too-many-in
result = ManifestParserFactory.new_from_file(item).as_dict() result = ManifestParserFactory.new_from_file(item).as_dict()
self.memcache_set(cache_key, result) self.memcache_set(cache_key, result)
return result return result
except ManifestException as e: except ManifestException as exc:
if not PlatformioCLI.in_silence(): 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)) raise MissingPackageManifestError(", ".join(self.manifest_names))
@staticmethod @staticmethod

View File

@ -156,7 +156,7 @@ def build_contrib_pysite_package(target_dir, with_metadata=True):
raise UserSideException( raise UserSideException(
"\n\nPlease ensure that the next packages are installed:\n\n" "\n\nPlease ensure that the next packages are installed:\n\n"
"sudo apt install python3-dev libffi-dev libssl-dev\n" "sudo apt install python3-dev libffi-dev libssl-dev\n"
) ) from exc
raise exc raise exc
# build manifests # build manifests

View File

@ -53,9 +53,9 @@ class PlatformPackageManager(BasePackageManager): # pylint: disable=too-many-an
# set logging level for underlying tool manager # set logging level for underlying tool manager
p.pm.set_log_level(self.log.getEffectiveLevel()) p.pm.set_log_level(self.log.getEffectiveLevel())
p.ensure_engine_compatible() p.ensure_engine_compatible()
except IncompatiblePlatform as e: except IncompatiblePlatform as exc:
super().uninstall(pkg, skip_dependencies=True) super().uninstall(pkg, skip_dependencies=True)
raise e raise exc
if project_env: if project_env:
p.configure_project_packages(project_env, project_targets) p.configure_project_packages(project_env, project_targets)
if not skip_dependencies: if not skip_dependencies:

View File

@ -61,9 +61,9 @@ class ManifestParserFactory(object):
try: try:
with io.open(path, encoding=encoding) as fp: with io.open(path, encoding=encoding) as fp:
return fp.read() return fp.read()
except UnicodeDecodeError as e: except UnicodeDecodeError as exc:
last_err = e last_err = exc
raise last_err # pylint: disable=raising-bad-type raise last_err
@classmethod @classmethod
def new_from_file(cls, path, remote_url=False): def new_from_file(cls, path, remote_url=False):
@ -145,8 +145,8 @@ class BaseManifestParser(object):
self.package_dir = package_dir self.package_dir = package_dir
try: try:
self._data = self.parse(contents) self._data = self.parse(contents)
except Exception as e: except Exception as exc:
raise ManifestParserError("Could not parse manifest -> %s" % e) raise ManifestParserError("Could not parse manifest -> %s" % exc) from exc
self._data = self.normalize_repository(self._data) self._data = self.normalize_repository(self._data)
self._data = self.parse_examples(self._data) self._data = self.parse_examples(self._data)

View File

@ -243,17 +243,17 @@ class ManifestSchema(BaseSchema):
if "Invalid leading zero" in str(exc): if "Invalid leading zero" in str(exc):
raise exc raise exc
semantic_version.Version.coerce(value) semantic_version.Version.coerce(value)
except (AssertionError, ValueError): except (AssertionError, ValueError) as exc:
raise ValidationError( raise ValidationError(
"Invalid semantic versioning format, see https://semver.org/" "Invalid semantic versioning format, see https://semver.org/"
) ) from exc
@validates("license") @validates("license")
def validate_license(self, value): def validate_license(self, value):
try: try:
spdx = self.load_spdx_licenses() spdx = self.load_spdx_licenses()
except requests.exceptions.RequestException: except requests.exceptions.RequestException as exc:
raise ValidationError("Could not load SPDX licenses for validation") raise ValidationError("Could not load SPDX licenses for validation") from exc
known_ids = set(item.get("licenseId") for item in spdx.get("licenses", [])) known_ids = set(item.get("licenseId") for item in spdx.get("licenses", []))
if value in known_ids: if value in known_ids:
return True return True

View File

@ -51,8 +51,8 @@ class VCSClientFactory(object):
) )
assert isinstance(obj, VCSClientBase) assert isinstance(obj, VCSClientBase)
return obj return obj
except (KeyError, AssertionError): except (KeyError, AssertionError) as exc:
raise VCSBaseException("VCS: Unknown repository type %s" % remote_url) raise VCSBaseException("VCS: Unknown repository type %s" % remote_url) from exc
class VCSClientBase(object): class VCSClientBase(object):
@ -73,10 +73,10 @@ class VCSClientBase(object):
self.get_cmd_output(["--version"]) self.get_cmd_output(["--version"])
else: else:
assert self.run_cmd(["--version"]) assert self.run_cmd(["--version"])
except (AssertionError, OSError, PlatformioException): except (AssertionError, OSError, PlatformioException) as exc:
raise UserSideException( raise UserSideException(
"VCS: `%s` client is not installed in your system" % self.command "VCS: `%s` client is not installed in your system" % self.command
) ) from exc
return True return True
@property @property
@ -108,8 +108,8 @@ class VCSClientBase(object):
try: try:
subprocess.check_call(args, **kwargs) subprocess.check_call(args, **kwargs)
return True return True
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as exc:
raise VCSBaseException("VCS: Could not process command %s" % e.cmd) raise VCSBaseException("VCS: Could not process command %s" % exc.cmd) from exc
def get_cmd_output(self, args, **kwargs): def get_cmd_output(self, args, **kwargs):
args = [self.command] + args args = [self.command] + args
@ -152,10 +152,10 @@ class GitClient(VCSClientBase):
def check_client(self): def check_client(self):
try: try:
return VCSClientBase.check_client(self) return VCSClientBase.check_client(self)
except UserSideException: except UserSideException as exc:
raise UserSideException( raise UserSideException(
"Please install Git client from https://git-scm.com/downloads" "Please install Git client from https://git-scm.com/downloads"
) ) from exc
def get_branches(self): def get_branches(self):
output = self.get_cmd_output(["branch"]) output = self.get_cmd_output(["branch"])

View File

@ -28,8 +28,8 @@ class PlatformBoardConfig(object):
self.manifest_path = manifest_path self.manifest_path = manifest_path
try: try:
self._manifest = fs.load_json(manifest_path) self._manifest = fs.load_json(manifest_path)
except ValueError: except ValueError as exc:
raise InvalidBoardManifest(manifest_path) raise InvalidBoardManifest(manifest_path) from exc
if not set(["name", "url", "vendor"]) <= set(self._manifest): if not set(["name", "url", "vendor"]) <= set(self._manifest):
raise UserSideException( raise UserSideException(
"Please specify name, url and vendor fields for " + manifest_path "Please specify name, url and vendor fields for " + manifest_path

View File

@ -35,8 +35,8 @@ class PlatformFactory(object):
sys.modules["platformio.managers.platform"] = base sys.modules["platformio.managers.platform"] = base
try: try:
return load_python_module("platformio.platform.%s" % name, path) return load_python_module("platformio.platform.%s" % name, path)
except ImportError: except ImportError as exc:
raise UnknownPlatform(name) raise UnknownPlatform(name) from exc
@classmethod @classmethod
def new(cls, pkg_or_spec, autoinstall=False) -> base.PlatformBase: def new(cls, pkg_or_spec, autoinstall=False) -> base.PlatformBase:

View File

@ -115,8 +115,8 @@ def exec_command(*args, **kwargs):
try: try:
result["out"], result["err"] = p.communicate() result["out"], result["err"] = p.communicate()
result["returncode"] = p.returncode result["returncode"] = p.returncode
except KeyboardInterrupt: except KeyboardInterrupt as exc:
raise exception.AbortedByUser() raise exception.AbortedByUser() from exc
finally: finally:
for s in ("stdout", "stderr"): for s in ("stdout", "stderr"):
if isinstance(kwargs[s], AsyncPipeBase): if isinstance(kwargs[s], AsyncPipeBase):

View File

@ -34,11 +34,11 @@ def validate_boards(ctx, param, value): # pylint: disable=W0613
for id_ in value: for id_ in value:
try: try:
pm.board_config(id_) pm.board_config(id_)
except UnknownBoard: except UnknownBoard as exc:
raise click.BadParameter( raise click.BadParameter(
"`%s`. Please search for board ID using `platformio boards` " "`%s`. Please search for board ID using `platformio boards` "
"command" % id_ "command" % id_
) ) from exc
return value return value

View File

@ -97,8 +97,8 @@ class ProjectConfigBase(object):
self._parsed.append(path) self._parsed.append(path)
try: try:
self._parser.read(path, "utf-8") self._parser.read(path, "utf-8")
except configparser.Error as e: except configparser.Error as exc:
raise exception.InvalidProjectConfError(path, str(e)) raise exception.InvalidProjectConfError(path, str(exc))
if not parse_extra: if not parse_extra:
return return
@ -324,10 +324,10 @@ class ProjectConfigBase(object):
# handle nested calls # handle nested calls
try: try:
value = self.get(section, option) value = self.get(section, option)
except RecursionError: except RecursionError as exc:
raise exception.ProjectOptionValueError( raise exception.ProjectOptionValueError(
"Infinite recursion has been detected", option, section "Infinite recursion has been detected", option, section
) ) from exc
if isinstance(value, list): if isinstance(value, list):
return "\n".join(value) return "\n".join(value)
return str(value) return str(value)
@ -336,8 +336,8 @@ class ProjectConfigBase(object):
value = None value = None
try: try:
value = self.getraw(section, option, default) value = self.getraw(section, option, default)
except configparser.Error as e: except configparser.Error as exc:
raise exception.InvalidProjectConfError(self.path, str(e)) raise exception.InvalidProjectConfError(self.path, str(exc))
option_meta = self.find_option_meta(section, option) option_meta = self.find_option_meta(section, option)
if not option_meta: if not option_meta:
@ -349,10 +349,10 @@ class ProjectConfigBase(object):
value = self.parse_multi_values(value or []) value = self.parse_multi_values(value or [])
try: try:
return self.cast_to(value, option_meta.type) return self.cast_to(value, option_meta.type)
except click.BadParameter as e: except click.BadParameter as exc:
if not self.expand_interpolations: if not self.expand_interpolations:
return value return value
raise exception.ProjectOptionValueError(e.format_message(), option, section) raise exception.ProjectOptionValueError(exc.format_message(), option, section)
@staticmethod @staticmethod
def cast_to(value, to_type): def cast_to(value, to_type):

View File

@ -153,7 +153,7 @@ class RegistryClient(HTTPClient):
x_cache_valid="1h", x_cache_valid="1h",
x_with_authorization=self.allowed_private_packages(), x_with_authorization=self.allowed_private_packages(),
) )
except HTTPClientError as e: except HTTPClientError as exc:
if e.response is not None and e.response.status_code == 404: if exc.response is not None and exc.response.status_code == 404:
return None return None
raise e raise exc

View File

@ -30,8 +30,8 @@ class AsyncCommandBase(object):
try: try:
self.start() self.start()
except Exception as e: except Exception as exc:
raise pb.Error(str(e)) raise pb.Error(str(exc)) from exc
@property @property
def id(self): def id(self):

View File

@ -164,8 +164,8 @@ class RemoteAgentService(RemoteClientBase):
origin_pio_ini, origin_pio_ini,
(os.path.getatime(back_pio_ini), os.path.getmtime(back_pio_ini)), (os.path.getatime(back_pio_ini), os.path.getmtime(back_pio_ini)),
) )
except NotPlatformIOProjectError as e: except NotPlatformIOProjectError as exc:
raise pb.Error(str(e)) raise pb.Error(str(exc)) from exc
cmd_args = ["platformio", "--force", command, "-d", project_dir] cmd_args = ["platformio", "--force", command, "-d", project_dir]
for env in options.get("environment", []): for env in options.get("environment", []):

View File

@ -38,10 +38,10 @@ class RemoteClientFactory(pb.PBClientFactory, protocol.ReconnectingClientFactory
auth_token = None auth_token = None
try: try:
auth_token = AccountClient().fetch_authentication_token() 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 = defer.Deferred()
d.addErrback(self.clientAuthorizationFailed) d.addErrback(self.clientAuthorizationFailed)
d.errback(pb.Error(e)) d.errback(pb.Error(exc))
return d return d
d = self.login( d = self.login(

View File

@ -274,11 +274,11 @@ class MPDataPusher(object):
) )
r.raise_for_status() r.raise_for_status()
return True return True
except requests.exceptions.HTTPError as e: except requests.exceptions.HTTPError as exc:
# skip Bad Request # skip Bad Request
if 400 >= e.response.status_code < 500: if 400 >= exc.response.status_code < 500:
return True return True
except: # pylint: disable=W0702 except: # pylint: disable=bare-except
pass pass
self._http_offline = True self._http_offline = True
return False return False

View File

@ -128,11 +128,11 @@ class TestRunnerBase:
targets.append("checkprogsize") targets.append("checkprogsize")
try: try:
return self.run_project_targets(targets) return self.run_project_targets(targets)
except ReturnErrorCode: except ReturnErrorCode as exc:
raise UnitTestSuiteError( raise UnitTestSuiteError(
"Building stage has failed, see errors above. " "Building stage has failed, see errors above. "
"Use `pio test -vvv` option to enable verbose output." "Use `pio test -vvv` option to enable verbose output."
) ) from exc
def stage_uploading(self): def stage_uploading(self):
is_embedded = self.platform.is_embedded() is_embedded = self.platform.is_embedded()
@ -150,11 +150,11 @@ class TestRunnerBase:
targets.append("__debug") targets.append("__debug")
try: try:
return self.run_project_targets(targets) return self.run_project_targets(targets)
except ReturnErrorCode: except ReturnErrorCode as exc:
raise UnitTestSuiteError( raise UnitTestSuiteError(
"Uploading stage has failed, see errors above. " "Uploading stage has failed, see errors above. "
"Use `pio test -vvv` option to enable verbose output." "Use `pio test -vvv` option to enable verbose output."
) ) from exc
def stage_testing(self): def stage_testing(self):
if self.options.without_testing: if self.options.without_testing:

View File

@ -56,11 +56,11 @@ class TestRunnerFactory(object):
try: try:
mod = load_python_module(module_name, custom_runner_path) mod = load_python_module(module_name, custom_runner_path)
except (FileNotFoundError, ImportError): except (FileNotFoundError, ImportError) as exc:
raise UserSideException( raise UserSideException(
"Could not find custom test runner " "Could not find custom test runner "
f"by this path -> {custom_runner_path}" f"by this path -> {custom_runner_path}"
) ) from exc
else: else:
mod = importlib.import_module(module_name) mod = importlib.import_module(module_name)
runner_cls = getattr(mod, cls.get_clsname(test_framework)) runner_cls = getattr(mod, cls.get_clsname(test_framework))

View File

@ -108,8 +108,8 @@ class ProgramTestOutputReader:
raise UnitTestError( raise UnitTestError(
f"Program received signal {sig.name} ({signal_description})" f"Program received signal {sig.name} ({signal_description})"
) )
except ValueError: except ValueError as exc:
raise UnitTestError("Program errored with %d code" % return_code) raise UnitTestError("Program errored with %d code" % return_code) from exc
def begin(self): def begin(self):
try: try:

View File

@ -45,8 +45,8 @@ class SerialTestOutputReader:
ser.rts = self.test_runner.options.monitor_rts ser.rts = self.test_runner.options.monitor_rts
ser.dtr = self.test_runner.options.monitor_dtr ser.dtr = self.test_runner.options.monitor_dtr
ser.open() ser.open()
except serial.SerialException as e: except serial.SerialException as exc:
click.secho(str(e), fg="red", err=True) click.secho(str(exc), fg="red", err=True)
return None return None
if not self.test_runner.options.no_reset: if not self.test_runner.options.no_reset:

View File

@ -531,9 +531,9 @@ includes=MozziGuts.h
errors = None errors = None
try: try:
ManifestSchema().load_manifest(raw_data) ManifestSchema().load_manifest(raw_data)
except ManifestValidationError as e: except ManifestValidationError as exc:
data = e.valid_data data = exc.valid_data
errors = e.messages errors = exc.messages
assert errors["authors"] assert errors["authors"]