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

Compatibility with isort 5.x #15

Closed
wants to merge 4 commits into from
Closed
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
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- Feature: Add support for ``-l``/``--line-length`` and ``-S``/``--skip-string-normalization``
- Feature: ``--diff`` outputs a diff for each file on standard output
- Feature: Allow to configure ``isort`` through pyproject.toml
- Feature: Require ``isort`` >= 5.0.1 and be compatible with it.


0.2.0 / 2020-03-11
Expand Down
3 changes: 2 additions & 1 deletion pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ doctest_optionflags = NORMALIZE_WHITESPACE
show_capture = no
addopts =
--black
--isort
## Disable pytest-isort until it is fixed to work with isort 5.x
# --isort
--mypy
--doctest-modules
5 changes: 3 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ console_scripts =

[options.extras_require]
isort =
isort<5
isort>=5.0.1
test =
pytest
pytest-black
pytest-isort
## Disable pytest-isort until it is fixed to work with isort 5.x
#pytest-isort
pytest-mypy
4 changes: 2 additions & 2 deletions src/darker/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
opcodes_to_edit_linenums,
)
from darker.git import git_diff_name_only, git_get_unmodified_content
from darker.import_sorting import SortImports, apply_isort
from darker.import_sorting import sort_code_string, apply_isort
from darker.utils import get_common_root, joinlines
from darker.verification import NotEquivalentError, verify_ast_unchanged
from darker.version import __version__
Expand Down Expand Up @@ -174,7 +174,7 @@ def main(argv: List[str] = None) -> None:
if args.version:
print(__version__)

if args.isort and not SortImports:
if args.isort and not sort_code_string:
logger.error(f"{ISORT_INSTRUCTION} to use the `--isort` option.")
exit(1)

Expand Down
21 changes: 11 additions & 10 deletions src/darker/import_sorting.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import logging
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union, cast
from typing import Dict, List, Optional, Tuple, Union

from black import find_project_root

try:
from isort import SortImports
from isort.api import sort_code_string
import isort.settings as isort_settings
except ImportError:
SortImports = None
sort_code_string = None
isort_settings = None

logger = logging.getLogger(__name__)
Expand All @@ -19,13 +19,14 @@
def get_isort_settings(src: Optional[Path], config: Optional[str]) -> IsortSettings:
if src and config is None:
project_root = find_project_root((str(src),))
settings: IsortSettings = isort_settings.from_path(str(project_root))
settings: IsortSettings
_, settings = isort_settings._find_config(str(project_root))
return settings

computed_settings: IsortSettings = isort_settings.default.copy()
computed_settings: IsortSettings = {}
if config:
isort_settings._update_with_config_file(
config, ('tool.isort',), computed_settings
computed_settings.update(
isort_settings._get_config_data(config, ('tool.isort',))
)
return computed_settings

Expand All @@ -41,9 +42,9 @@ def apply_isort(
isort_settings["line_length"] = line_length

logger.debug(
"SortImports(file_contents=..., check=True, {})".format(
"sort_code_string(file_contents=..., check=True, {})".format(
", ".join(f"{k}={v}" for k, v in isort_settings.items())
)
)
result = SortImports(file_contents=content, check=True, **isort_settings)
return cast(str, result.output)
output: str = sort_code_string(content, **isort_settings)
return output
39 changes: 12 additions & 27 deletions src/darker/tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

def test_isort_option_without_isort(tmpdir, without_isort, caplog):
check_call(["git", "init"], cwd=tmpdir)
with patch.object(darker.__main__, "SortImports", None), pytest.raises(SystemExit):
with patch.object(darker.__main__, "sort_code_string", None), pytest.raises(
SystemExit
):

darker.__main__.main(["--isort", str(tmpdir)])

Expand All @@ -28,10 +30,10 @@ def run_isort(git_repo, monkeypatch, caplog):
paths['test1.py'].write('changed')
with patch.multiple(
darker.__main__, run_black=Mock(return_value=[]), verify_ast_unchanged=Mock(),
), patch("darker.import_sorting.SortImports"):
), patch("darker.import_sorting.sort_code_string"):
darker.__main__.main(["--isort", "./test1.py"])
return SimpleNamespace(
SortImports=darker.import_sorting.SortImports, caplog=caplog
sort_code_string=darker.import_sorting.sort_code_string, caplog=caplog
)


Expand All @@ -40,19 +42,14 @@ def test_isort_option_with_isort(run_isort):


def test_isort_option_with_isort_calls_sortimports(run_isort):
run_isort.SortImports.assert_called_once_with(
file_contents="changed",
check=True,
**darker.import_sorting.isort_settings.default
)
run_isort.sort_code_string.assert_called_once()
assert run_isort.sort_code_string.call_args[0] == ("changed",)


def test_isort_option_with_config(isort_config, run_isort):
isort_args = darker.import_sorting.isort_settings.default.copy()
isort_args["line_length"] = 120
run_isort.SortImports.assert_called_once_with(
file_contents="changed", check=True, **isort_args
)
run_isort.sort_code_string.assert_called_once()
assert run_isort.sort_code_string.call_args[0] == ("changed",)
assert run_isort.sort_code_string.call_args[1]["line_length"] == 120


def test_format_edited_parts_empty():
Expand Down Expand Up @@ -110,13 +107,7 @@ def test_format_edited_parts_empty():
'isort, black_args, print_diff, expect_stdout, expect_a_py',
[
(False, {}, True, A_PY_DIFF_BLACK, A_PY),
(
True,
{},
False,
['ERROR: Imports are incorrectly sorted.', ''],
A_PY_BLACK_ISORT,
),
(True, {}, False, [''], A_PY_BLACK_ISORT,),
(
False,
{'skip_string_normalization': True},
Expand All @@ -125,13 +116,7 @@ def test_format_edited_parts_empty():
A_PY,
),
(False, {}, False, [''], A_PY_BLACK),
(
True,
{},
True,
['ERROR: Imports are incorrectly sorted.'] + A_PY_DIFF_BLACK_ISORT,
A_PY,
),
(True, {}, True, A_PY_DIFF_BLACK_ISORT, A_PY,),
],
)
def test_format_edited_parts(
Expand Down