Skip to content

Commit

Permalink
Pass project root to ruff-api.isort_string() (#232)
Browse files Browse the repository at this point in the history
This helps ensure that ruff can correctly discover first party
imports when sorting in memory. If none, it falls back to CWD.
  • Loading branch information
amyreese authored Aug 23, 2024
1 parent 6907c29 commit d75b22a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ lsp = [
"pygls >= 1.3",
]
ruff = [
"ruff-api>=0.0.5",
"ruff-api>=0.0.8",
]
dev = [
"attribution==1.8.0",
Expand Down
9 changes: 8 additions & 1 deletion ufmt/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,14 @@ def ufmt_bytes(
],
)
content_str = ruff_api.isort_string(
path.as_posix(), content.decode(encoding), options=ruff_isort_options
path.as_posix(),
content.decode(encoding),
options=ruff_isort_options,
root=(
ufmt_config.project_root.as_posix()
if ufmt_config.project_root
else None
),
)
content = content_str.encode(encoding)
elif ufmt_config.sorter == Sorter.skip:
Expand Down
11 changes: 8 additions & 3 deletions ufmt/tests/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import call, Mock, patch
from unittest.mock import ANY, call, Mock, patch

import black
import ruff_api
Expand Down Expand Up @@ -250,7 +250,10 @@ def test_ufmt_bytes_alternate_sorter(
usort_config=usort_config,
)
self.assertEqual(CORRECTLY_FORMATTED_CODE.encode(), result)
usort_mock.assert_called_once()
usort_mock.assert_called_with(
POORLY_FORMATTED_CODE.encode(), usort_config, Path("foo.py")
)
ruff_mock.assert_not_called()

with self.subTest("ruff-api"):
usort_mock.reset_mock()
Expand All @@ -263,7 +266,9 @@ def test_ufmt_bytes_alternate_sorter(
)
self.assertEqual(CORRECTLY_FORMATTED_CODE.encode(), result)
usort_mock.assert_not_called()
ruff_mock.assert_called_once()
ruff_mock.assert_called_with(
"foo.py", POORLY_FORMATTED_CODE, options=ANY, root=None
)

with self.subTest("skip"):
usort_mock.reset_mock()
Expand Down

0 comments on commit d75b22a

Please sign in to comment.