Skip to content

Commit

Permalink
Fix ruff/bugbear issues (B904)
Browse files Browse the repository at this point in the history
B904 Within an `except` clause, raise exceptions with `raise ... from err` or
     `raise ... from None` to distinguish them from errors in exception handling

https://docs.astral.sh/ruff/rules/raise-without-from-inside-except/
  • Loading branch information
DimitriPapadopoulos committed Apr 13, 2024
1 parent 4d3ab16 commit 8c61766
Show file tree
Hide file tree
Showing 26 changed files with 103 additions and 91 deletions.
16 changes: 8 additions & 8 deletions distutils/_msvccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def _get_vc_env(plat_spec):
).decode('utf-16le', errors='replace')
except subprocess.CalledProcessError as exc:
log.error(exc.output)
raise DistutilsPlatformError(f"Error executing {exc.cmd}")
raise DistutilsPlatformError(f"Error executing {exc.cmd}") from exc

env = {
key.lower(): value
Expand Down Expand Up @@ -358,7 +358,7 @@ def compile( # noqa: C901
for obj in objects:
try:
src, ext = build[obj]
except KeyError:
except KeyError as e:
continue
if debug:
# pass the full pathname to MSVC in debug mode,
Expand All @@ -378,7 +378,7 @@ def compile( # noqa: C901
try:
self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg
continue
elif ext in self._mc_extensions:
# Compile .MC to .RC file to .RES file.
Expand All @@ -403,11 +403,11 @@ def compile( # noqa: C901
self.spawn([self.rc, "/fo" + obj, rc_file])

except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg
continue
else:
# how to handle this file?
raise CompileError(f"Don't know how to compile {src} to {obj}")
raise CompileError(f"Don't know how to compile {src} to {obj}") from e

args = [self.cc] + compile_opts + pp_opts
if add_cpp_opts:
Expand All @@ -418,7 +418,7 @@ def compile( # noqa: C901
try:
self.spawn(args)
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg

return objects

Expand All @@ -438,7 +438,7 @@ def create_static_lib(
log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
self.spawn([self.lib] + lib_args)
except DistutilsExecError as msg:
raise LibError(msg)
raise LibError(msg) from msg
else:
log.debug("skipping %s (up-to-date)", output_filename)

Expand Down Expand Up @@ -507,7 +507,7 @@ def link(
log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
self.spawn([self.linker] + ld_args)
except DistutilsExecError as msg:
raise LinkError(msg)
raise LinkError(msg) from msg
else:
log.debug("skipping %s (up-to-date)", output_filename)

Expand Down
8 changes: 4 additions & 4 deletions distutils/archive_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): # noqa: C901

try:
spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
except DistutilsExecError:
except DistutilsExecError as e:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise DistutilsExecError(
Expand All @@ -166,7 +166,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): # noqa: C901
"find a standalone zip utility"
)
% zip_filename
)
) from e

else:
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
Expand Down Expand Up @@ -259,8 +259,8 @@ def make_archive(

try:
format_info = ARCHIVE_FORMATS[format]
except KeyError:
raise ValueError("unknown archive format '%s'" % format)
except KeyError as e:
raise ValueError("unknown archive format '%s'" % format) from e

func = format_info[0]
for arg, val in format_info[1]:
Expand Down
10 changes: 5 additions & 5 deletions distutils/bcppcompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def compile( # noqa: C901
try:
self.spawn(["brcc32", "-fo", obj, src])
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg
continue # the 'for' loop

# The next two are both for the real compiler.
Expand Down Expand Up @@ -154,7 +154,7 @@ def compile( # noqa: C901
+ [src]
)
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg

return objects

Expand All @@ -173,7 +173,7 @@ def create_static_lib(
try:
self.spawn([self.lib] + lib_args)
except DistutilsExecError as msg:
raise LibError(msg)
raise LibError(msg) from msg
else:
log.debug("skipping %s (up-to-date)", output_filename)

Expand Down Expand Up @@ -304,7 +304,7 @@ def link( # noqa: C901
try:
self.spawn([self.linker] + ld_args)
except DistutilsExecError as msg:
raise LinkError(msg)
raise LinkError(msg) from msg

else:
log.debug("skipping %s (up-to-date)", output_filename)
Expand Down Expand Up @@ -392,6 +392,6 @@ def preprocess(
self.spawn(pp_args)
except DistutilsExecError as msg:
print(msg)
raise CompileError(msg)
raise CompileError(msg) from msg

# preprocess()
16 changes: 9 additions & 7 deletions distutils/ccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -969,8 +969,10 @@ def _make_out_path(self, output_dir, strip_dir, src_name):
base = self._make_relative(base)
try:
new_ext = self.out_extensions[ext]
except LookupError:
raise UnknownFileError(f"unknown file type '{ext}' (from '{src_name}')")
except LookupError as e:
raise UnknownFileError(
f"unknown file type '{ext}' (from '{src_name}')"
) from e
if strip_dir:
base = os.path.basename(base)
return os.path.join(output_dir, base + new_ext)
Expand Down Expand Up @@ -1144,22 +1146,22 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
compiler = get_default_compiler(plat)

(module_name, class_name, long_description) = compiler_class[compiler]
except KeyError:
except KeyError as e:
msg = "don't know how to compile C/C++ code on platform '%s'" % plat
if compiler is not None:
msg = msg + " with '%s' compiler" % compiler
raise DistutilsPlatformError(msg)
raise DistutilsPlatformError(msg) from e

try:
module_name = "distutils." + module_name
__import__(module_name)
module = sys.modules[module_name]
klass = vars(module)[class_name]
except ImportError:
except ImportError as e:
raise DistutilsModuleError(
"can't compile C/C++ code: unable to load module '%s'" % module_name
)
except KeyError:
) from e
except KeyError as e:
raise DistutilsModuleError(
f"can't compile C/C++ code: unable to find class '{class_name}' "
f"in module '{module_name}'"
Expand Down
8 changes: 4 additions & 4 deletions distutils/command/bdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ def finalize_options(self):
if self.formats is None:
try:
self.formats = [self.default_format[os.name]]
except KeyError:
except KeyError as e:
raise DistutilsPlatformError(
"don't know how to create built distributions "
"on platform %s" % os.name
)
) from e

if self.dist_dir is None:
self.dist_dir = "dist"
Expand All @@ -132,8 +132,8 @@ def run(self):
for format in self.formats:
try:
commands.append(self.format_commands[format][0])
except KeyError:
raise DistutilsOptionError("invalid format '%s'" % format)
except KeyError as e:
raise DistutilsOptionError("invalid format '%s'" % format) from e

# Reinitialize and run each command.
for i in range(len(self.formats)):
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/bdist_dumb.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ def finalize_options(self):
if self.format is None:
try:
self.format = self.default_format[os.name]
except KeyError:
except KeyError as e:
raise DistutilsPlatformError(
"don't know how to create dumb built distributions "
"on platform %s" % os.name
)
) from e

self.set_undefined_options(
'bdist',
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ def finalize_options(self): # noqa: C901
if isinstance(self.parallel, str):
try:
self.parallel = int(self.parallel)
except ValueError:
raise DistutilsOptionError("parallel should be an integer")
except ValueError as e:
raise DistutilsOptionError("parallel should be an integer") from e

def run(self):
# Run all relevant sub-commands. This will be some subset of:
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/build_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,8 @@ def finalize_options(self): # noqa: C901
if isinstance(self.parallel, str):
try:
self.parallel = int(self.parallel)
except ValueError:
raise DistutilsOptionError("parallel should be an integer")
except ValueError as e:
raise DistutilsOptionError("parallel should be an integer") from e

def run(self): # noqa: C901
from ..ccompiler import new_compiler
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/build_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ def finalize_options(self):
try:
self.optimize = int(self.optimize)
assert 0 <= self.optimize <= 2
except (ValueError, AssertionError):
raise DistutilsOptionError("optimize must be 0, 1, or 2")
except (ValueError, AssertionError) as e:
raise DistutilsOptionError("optimize must be 0, 1, or 2") from e

def run(self):
# XXX copy_file by default preserves atime and mtime. IMHO this is
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/build_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def _validate_shebang(shebang, encoding):
# the script encoding too.
try:
shebang.encode(encoding)
except UnicodeEncodeError:
except UnicodeEncodeError as e:
raise ValueError(
f"The shebang ({shebang!r}) is not encodable "
f"to the script encoding ({encoding})"
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def run(self):
try:
self.check_restructuredtext()
except TypeError as exc:
raise DistutilsSetupError(str(exc))
raise DistutilsSetupError(str(exc)) from exc
elif self.strict:
raise DistutilsSetupError('The docutils package is needed.')

Expand Down
4 changes: 2 additions & 2 deletions distutils/command/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,10 +598,10 @@ def finalize_other(self):
self.install_base = self.install_platbase = self.prefix
try:
self.select_scheme(os.name)
except KeyError:
except KeyError as e:
raise DistutilsPlatformError(
"I don't know how to install stuff on '%s'" % os.name
)
) from e

def select_scheme(self, name):
_select_scheme(self, name)
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/install_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ def finalize_options(self):
self.optimize = int(self.optimize)
if self.optimize not in (0, 1, 2):
raise AssertionError
except (ValueError, AssertionError):
raise DistutilsOptionError("optimize must be 0, 1, or 2")
except (ValueError, AssertionError) as e:
raise DistutilsOptionError("optimize must be 0, 1, or 2") from e

def run(self):
# Make sure we have built everything we need first
Expand Down
12 changes: 7 additions & 5 deletions distutils/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,11 @@ class found in 'cmdclass' is used in place of the default, which is
_setup_distribution = dist = klass(attrs)
except DistutilsSetupError as msg:
if 'name' not in attrs:
raise SystemExit("error in setup command: %s" % msg)
raise SystemExit("error in setup command: %s" % msg) from msg
else:
raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg))
raise SystemExit(
"error in {} setup command: {}".format(attrs['name'], msg)
) from msg

if _setup_stop_after == "init":
return dist
Expand All @@ -170,7 +172,7 @@ class found in 'cmdclass' is used in place of the default, which is
try:
ok = dist.parse_command_line()
except DistutilsArgError as msg:
raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg)
raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg) from msg

if DEBUG:
print("options (after parsing command line):")
Expand Down Expand Up @@ -205,13 +207,13 @@ def run_commands(dist):
sys.stderr.write(f"error: {exc}\n")
raise
else:
raise SystemExit(f"error: {exc}")
raise SystemExit(f"error: {exc}") from exc

except (DistutilsError, CCompilerError) as msg:
if DEBUG:
raise
else:
raise SystemExit("error: " + str(msg))
raise SystemExit("error: " + str(msg)) from msg

return dist

Expand Down
8 changes: 4 additions & 4 deletions distutils/cygwinccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def get_msvcr():
return
try:
return _msvcr_lookup[msc_ver]
except KeyError:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
except KeyError as e:
raise ValueError("Unknown MS Compiler version %s " % msc_ver) from e


_runtime_library_dirs_msg = (
Expand Down Expand Up @@ -135,14 +135,14 @@ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
try:
self.spawn(["windres", "-i", src, "-o", obj])
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg
else: # for other files use the C-compiler
try:
self.spawn(
self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
)
except DistutilsExecError as msg:
raise CompileError(msg)
raise CompileError(msg) from msg

def link(
self,
Expand Down
6 changes: 4 additions & 2 deletions distutils/dir_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901
if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
raise DistutilsFileError(
f"could not create '{head}': {exc.args[-1]}"
)
) from exc
created_dirs.append(head)

_path_created[abs_head] = 1
Expand Down Expand Up @@ -142,7 +142,9 @@ def copy_tree( # noqa: C901
if dry_run:
names = []
else:
raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
raise DistutilsFileError(
f"error listing files in '{src}': {e.strerror}"
) from e

if not dry_run:
mkpath(dst, verbose=verbose)
Expand Down
Loading

0 comments on commit 8c61766

Please sign in to comment.