Skip to content

Commit 9c0b46c

Browse files
author
KOBAYASHI Shinji
committed
Add OSError handling in find_imports_in_file
1 parent 78c30dc commit 9c0b46c

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

isort/api.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -588,15 +588,18 @@ def find_imports_in_file(
588588
- **top_only**: If True, only return imports that occur before the first function or class.
589589
- ****config_kwargs**: Any config modifications.
590590
"""
591-
with io.File.read(filename) as source_file:
592-
yield from find_imports_in_stream(
593-
input_stream=source_file.stream,
594-
config=config,
595-
file_path=file_path or source_file.path,
596-
unique=unique,
597-
top_only=top_only,
598-
**config_kwargs,
599-
)
591+
try:
592+
with io.File.read(filename) as source_file:
593+
yield from find_imports_in_stream(
594+
input_stream=source_file.stream,
595+
config=config,
596+
file_path=file_path or source_file.path,
597+
unique=unique,
598+
top_only=top_only,
599+
**config_kwargs,
600+
)
601+
except OSError as error:
602+
warn(f"Unable to parse file {filename} due to {error}")
600603

601604

602605
def find_imports_in_paths(

tests/unit/test_api.py

+7
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,13 @@ def test_find_imports_in_file(imperfect):
9494
assert "b" in [found_import.module for found_import in found_imports]
9595

9696

97+
def test_find_imports_in_file_error(tmpdir):
98+
broken_link = tmpdir.join("broken_link.py")
99+
broken_link.mksymlinkto("not-exist")
100+
with pytest.warns(UserWarning):
101+
assert not list(api.find_imports_in_file(broken_link))
102+
103+
97104
def test_find_imports_in_code():
98105
code = """
99106
from x.y import z as a

0 commit comments

Comments
 (0)