Skip to content

Commit 1708f3e

Browse files
committed
Ruff rules B017, B028, and E203
1 parent 1157b58 commit 1708f3e

8 files changed

+52
-35
lines changed

isort/api.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,8 @@ def sort_stream(
199199
raise ExistingSyntaxErrors(content_source)
200200
if config.verbose:
201201
warn(
202-
f"{content_source} Python AST errors found but ignored due to Cython extension"
202+
f"{content_source} Python AST errors found but ignored due to Cython extension",
203+
stacklevel=2,
203204
)
204205
input_stream = StringIO(file_content)
205206

@@ -227,7 +228,8 @@ def sort_stream(
227228
raise IntroducedSyntaxErrors(content_source)
228229
if config.verbose:
229230
warn(
230-
f"{content_source} Python AST errors found but ignored due to Cython extension"
231+
f"{content_source} Python AST errors found but ignored due to Cython extension",
232+
stacklevel=2,
231233
)
232234
if _internal_output != output_stream:
233235
output_stream.write(_internal_output.read())
@@ -494,9 +496,12 @@ def sort_file(
494496
source_file.stream.close()
495497

496498
except ExistingSyntaxErrors:
497-
warn(f"{actual_file_path} unable to sort due to existing syntax errors")
499+
warn(f"{actual_file_path} unable to sort due to existing syntax errors", stacklevel=2)
498500
except IntroducedSyntaxErrors: # pragma: no cover
499-
warn(f"{actual_file_path} unable to sort as isort introduces new syntax errors")
501+
warn(
502+
f"{actual_file_path} unable to sort as isort introduces new syntax errors",
503+
stacklevel=2,
504+
)
500505

501506
return changed
502507

@@ -599,7 +604,7 @@ def find_imports_in_file(
599604
**config_kwargs,
600605
)
601606
except OSError as error:
602-
warn(f"Unable to parse file {filename} due to {error}")
607+
warn(f"Unable to parse file {filename} due to {error}", stacklevel=2)
603608

604609

605610
def find_imports_in_paths(

isort/main.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,11 @@ def sort_imports(
102102
skipped = True
103103
return SortAttempt(incorrectly_sorted, skipped, True)
104104
except (OSError, ValueError) as error:
105-
warn(f"Unable to parse file {file_name} due to {error}")
105+
warn(f"Unable to parse file {file_name} due to {error}", stacklevel=2)
106106
return None
107107
except UnsupportedEncoding:
108108
if config.verbose:
109-
warn(f"Encoding not supported for {file_name}")
109+
warn(f"Encoding not supported for {file_name}", stacklevel=2)
110110
return SortAttempt(incorrectly_sorted, skipped, False)
111111
except ISortError as error:
112112
_print_hard_fail(config, message=str(error))
@@ -1079,7 +1079,7 @@ def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] =
10791079
venv = arguments["virtual_env"]
10801080
arguments["virtual_env"] = os.path.abspath(venv)
10811081
if not os.path.isdir(arguments["virtual_env"]):
1082-
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
1082+
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}", stacklevel=2)
10831083

10841084
file_names = arguments.pop("files", [])
10851085
if not file_names and not show_config:
@@ -1260,7 +1260,9 @@ def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] =
12601260
if num_broken and not config.quiet:
12611261
if config.verbose:
12621262
for was_broken in broken:
1263-
warn(f"{was_broken} was broken path, make sure it exists correctly")
1263+
warn(
1264+
f"{was_broken} was broken path, make sure it exists correctly", stacklevel=2
1265+
)
12641266
print(f"Broken {num_broken} paths")
12651267

12661268
if num_broken > 0 and is_no_attempt:
@@ -1272,16 +1274,19 @@ def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] =
12721274
if remapped_deprecated_args:
12731275
warn(
12741276
"W0502: The following deprecated single dash CLI flags were used and translated: "
1275-
f"{', '.join(remapped_deprecated_args)}!"
1277+
f"{', '.join(remapped_deprecated_args)}!",
1278+
stacklevel=2,
12761279
)
12771280
if deprecated_flags:
12781281
warn(
12791282
"W0501: The following deprecated CLI flags were used and ignored: "
1280-
f"{', '.join(deprecated_flags)}!"
1283+
f"{', '.join(deprecated_flags)}!",
1284+
stacklevel=2,
12811285
)
12821286
warn(
12831287
"W0500: Please see the 5.0.0 Upgrade guide: "
1284-
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html"
1288+
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html",
1289+
stacklevel=2,
12851290
)
12861291

12871292
if wrong_sorted_files:

isort/parse.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,8 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
451451
if placed_module == "":
452452
warn(
453453
f"could not place module {import_from} of line {line} --"
454-
" Do you need to define a default section?"
454+
" Do you need to define a default section?",
455+
stacklevel=2,
455456
)
456457

457458
if placed_module and placed_module not in imports:
@@ -569,7 +570,8 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
569570
if placed_module == "":
570571
warn(
571572
f"could not place module {module} of line {line} --"
572-
" Do you need to define a default section?"
573+
" Do you need to define a default section?",
574+
stacklevel=2,
573575
)
574576
imports.setdefault("", {"straight": OrderedDict(), "from": OrderedDict()})
575577

isort/settings.py

+18-7
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,8 @@ def __init__(
339339
"was found inside. This can happen when [settings] is used as the config "
340340
"header instead of [isort]. "
341341
"See: https://pycqa.github.io/isort/docs/configuration/config_files"
342-
"#custom-config-files for more information."
342+
"#custom-config-files for more information.",
343+
stacklevel=2,
343344
)
344345
elif settings_path:
345346
if not os.path.exists(settings_path):
@@ -407,7 +408,8 @@ def __init__(
407408
f"Default to {section_name} if unsure."
408409
"\n\n"
409410
"See: https://pycqa.github.io/isort/"
410-
"#custom-sections-and-ordering."
411+
"#custom-sections-and-ordering.",
412+
stacklevel=2,
411413
)
412414
else:
413415
combined_config[section_name] = frozenset(value)
@@ -419,7 +421,8 @@ def __init__(
419421
" included in `sections` config option:"
420422
f" {combined_config.get('sections', SECTION_DEFAULTS)}.\n\n"
421423
"See: https://pycqa.github.io/isort/"
422-
"#custom-sections-and-ordering."
424+
"#custom-sections-and-ordering.",
425+
stacklevel=2,
423426
)
424427
if key.startswith(IMPORT_HEADING_PREFIX):
425428
import_headings[key[len(IMPORT_HEADING_PREFIX) :].lower()] = str(value)
@@ -442,7 +445,8 @@ def __init__(
442445
warn(
443446
f"`sections` setting includes {section}, but no known_{section.lower()} "
444447
"is defined. "
445-
f"The following known_SECTION config options are defined: {config_keys}."
448+
f"The following known_SECTION config options are defined: {config_keys}.",
449+
stacklevel=2,
446450
)
447451

448452
if "directory" not in combined_config:
@@ -495,7 +499,8 @@ def __init__(
495499
"W0503: Deprecated config options were used: "
496500
f"{', '.join(deprecated_options_used)}."
497501
"Please see the 5.0.0 upgrade guide: "
498-
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html"
502+
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html",
503+
stacklevel=2,
499504
)
500505

501506
if known_other:
@@ -777,7 +782,10 @@ def _find_config(path: str) -> Tuple[str, Dict[str, Any]]:
777782
potential_config_file, CONFIG_SECTIONS[config_file_name]
778783
)
779784
except Exception:
780-
warn(f"Failed to pull configuration information from {potential_config_file}")
785+
warn(
786+
f"Failed to pull configuration information from {potential_config_file}",
787+
stacklevel=2,
788+
)
781789
config_data = {}
782790
if config_data:
783791
return (current_directory, config_data)
@@ -814,7 +822,10 @@ def find_all_configs(path: str) -> Trie:
814822
potential_config_file, CONFIG_SECTIONS[config_file_name]
815823
)
816824
except Exception:
817-
warn(f"Failed to pull configuration information from {potential_config_file}")
825+
warn(
826+
f"Failed to pull configuration information from {potential_config_file}",
827+
stacklevel=2,
828+
)
818829
config_data = {}
819830

820831
if config_data:

isort/setuptools_commands.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,6 @@ def run(self) -> None:
5757
if not api.check_file(python_file, **arguments):
5858
wrong_sorted_files = True # pragma: no cover
5959
except OSError as error: # pragma: no cover
60-
warn(f"Unable to parse file {python_file} due to {error}")
60+
warn(f"Unable to parse file {python_file} due to {error}", stacklevel=2)
6161
if wrong_sorted_files:
6262
sys.exit(1) # pragma: no cover

pyproject.toml

+1-7
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,7 @@ dev = [
147147
max-line-length = 100
148148
# Ignore non PEP 8 compliant rules as suggested by black
149149
# E203: https://github.com/psf/black/blob/3fab5ade71bccf80ae0a5af76729099869adea56/docs/the_black_code_style/current_style.md#slices
150-
extend-ignore = [
151-
"B017",
152-
"E203",
153-
]
150+
extend-ignore = [ "E203" ]
154151
exclude = "_vendored"
155152
per-file-ignores = [
156153
"tests/unit/example_crlf_file.py:F401",
@@ -190,10 +187,7 @@ lint.select = [
190187
"W",
191188
]
192189
lint.ignore = [
193-
"B017",
194-
"B028",
195190
"B904",
196-
"E203",
197191
"E501",
198192
"PERF203",
199193
"RUF100",

tests/unit/test_io.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pytest
55

66
from isort import io
7+
from isort.exceptions import UnsupportedEncoding
78

89

910
class TestFile:
@@ -15,7 +16,7 @@ def test_read(self, tmpdir):
1516
"""
1617
test_file = tmpdir.join("file.py")
1718
test_file.write(test_file_content)
18-
with pytest.raises(Exception):
19+
with pytest.raises(UnicodeDecodeError):
1920
with io.File.read(str(test_file)) as file_handler:
2021
file_handler.stream.read()
2122

@@ -27,7 +28,7 @@ def test_from_content(self, tmpdir):
2728
assert file_obj.extension == "py"
2829

2930
def test_open(self, tmpdir):
30-
with pytest.raises(Exception):
31+
with pytest.raises(FileNotFoundError):
3132
io.File._open("THISCANTBEAREALFILEὩὩὩὩὩὩὩὩὩὩὩὩ.ὩὩὩὩὩ")
3233

3334
def raise_arbitrary_exception(*args, **kwargs):
@@ -39,5 +40,5 @@ def raise_arbitrary_exception(*args, **kwargs):
3940

4041
# correctly responds to error determining encoding
4142
with patch("tokenize.detect_encoding", raise_arbitrary_exception):
42-
with pytest.raises(Exception):
43+
with pytest.raises(UnsupportedEncoding):
4344
io.File._open(str(test_file))

tests/unit/test_isort.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -4337,9 +4337,8 @@ def test_settings_path_skip_issue_909(tmpdir) -> None:
43374337

43384338
test_run_directory = os.getcwd()
43394339
os.chdir(str(base_dir))
4340-
with pytest.raises(
4341-
Exception
4342-
): # without the settings path provided: the command should not skip & identify errors
4340+
with pytest.raises(subprocess.CalledProcessError):
4341+
# without the settings path provided: the command should not skip & identify errors
43434342
subprocess.run(["isort", ".", "--check-only"], check=True)
43444343
result = subprocess.run(
43454344
["isort", ".", "--check-only", "--settings-path=conf/.isort.cfg"],

0 commit comments

Comments
 (0)