From d75b22a61b8871122e5686f1e3b34886bf56fdfd Mon Sep 17 00:00:00 2001 From: Amethyst Reese Date: Thu, 22 Aug 2024 23:10:03 -0700 Subject: [PATCH] Pass project root to `ruff-api.isort_string()` (#232) This helps ensure that ruff can correctly discover first party imports when sorting in memory. If none, it falls back to CWD. --- pyproject.toml | 2 +- ufmt/core.py | 9 ++++++++- ufmt/tests/core.py | 11 ++++++++--- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1d55f42..0ac9862 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,7 +34,7 @@ lsp = [ "pygls >= 1.3", ] ruff = [ - "ruff-api>=0.0.5", + "ruff-api>=0.0.8", ] dev = [ "attribution==1.8.0", diff --git a/ufmt/core.py b/ufmt/core.py index 5c53da0..548159c 100644 --- a/ufmt/core.py +++ b/ufmt/core.py @@ -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: diff --git a/ufmt/tests/core.py b/ufmt/tests/core.py index 4f79070..7cb75a3 100644 --- a/ufmt/tests/core.py +++ b/ufmt/tests/core.py @@ -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 @@ -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() @@ -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()