Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ParsingError exception #2107

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions isort/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
FileSkipComment,
FileSkipSetting,
IntroducedSyntaxErrors,
ParsingError,
)
from .format import ask_whether_to_apply_changes_to_file, create_terminal_printer, show_unified_diff
from .io import Empty, File
Expand Down Expand Up @@ -217,6 +218,9 @@ def sort_stream(
except FileSkipComment:
raise FileSkipComment(content_source)

except ParsingError:
raise ParsingError(file_path)

if config.atomic:
_internal_output.seek(0)
try:
Expand Down
10 changes: 7 additions & 3 deletions isort/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from isort.settings import DEFAULT_CONFIG, Config

from . import output, parse
from .exceptions import ExistingSyntaxErrors, FileSkipComment
from .exceptions import ExistingSyntaxErrors, FileSkipComment, ISortError, ParsingError
from .format import format_natural, remove_whitespace
from .settings import FILE_SKIP_COMMENTS

Expand Down Expand Up @@ -417,8 +417,12 @@ def process(
import_section = "".join(
line[len(indent) :] for line in import_section.splitlines(keepends=True)
)

parsed_content = parse.file_contents(import_section, config=config)
try:
parsed_content = parse.file_contents(import_section, config=config)
except ISortError as error:
raise error
except Exception:
raise ParsingError(file_path=None)
verbose_output += parsed_content.verbose_output

sorted_import_section = output.sorted_imports(
Expand Down
10 changes: 9 additions & 1 deletion isort/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""All isort specific exception classes should be defined here"""
from functools import partial
from pathlib import Path
from typing import Any, Dict, List, Type, Union
from typing import Any, Dict, List, Optional, Type, Union

from .profiles import profiles

Expand Down Expand Up @@ -195,3 +195,11 @@ def __init__(self, import_module: str, section: str):
"See https://pycqa.github.io/isort/#custom-sections-and-ordering "
"for more info."
)


class ParsingError(ISortError):
"""Raised when there's a failure with parsing the imports"""

def __init__(self, file_path: Optional[Path]):
super().__init__(f"isort couldn't parse imports for {file_path}")
self.file_path = file_path
8 changes: 8 additions & 0 deletions tests/unit/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,11 @@ def setup_class(self):

def test_variables(self):
assert self.instance.filename == "file.py"


class TestParsingError(TestISortError):
def setup_class(self):
self.instance: exceptions.ParsingError = exceptions.ParsingError(file_path=None)

def test_variables(self):
assert self.instance.file_path is None
15 changes: 14 additions & 1 deletion tests/unit/test_isort.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import isort
from isort import api, files, sections
from isort.exceptions import ExistingSyntaxErrors, FileSkipped, MissingSection
from isort.exceptions import ExistingSyntaxErrors, FileSkipped, MissingSection, ParsingError
from isort.settings import Config
from isort.utils import exists_case_sensitive

Expand Down Expand Up @@ -5671,3 +5671,16 @@ def test_reexport_not_last_line() -> None:
meme = "rickroll"
"""
assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output


def test_doesnot_break_for_syntax_error() -> None:
"""Test to ensure that isort doesn't break for syntax error while parsing import"""
test_input = """
from pathlib import Path
from typing import Optional, Union
import numpy as np

from os.path.import Path
"""
with pytest.raises(ParsingError):
isort.code(test_input)