Skip to content
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
13 changes: 10 additions & 3 deletions src/fixit/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,16 @@ def format(self, module: Module, path: Path) -> FileContent:
import ufmt.util

mode = ufmt.util.make_black_config(path)
content = black.format_file_contents(
module.bytes.decode("utf-8"), fast=False, mode=mode
)
try:
content = black.format_file_contents(
module.bytes.decode("utf-8"), fast=False, mode=mode
)
except black.NothingChanged:
# black signals "this is already formatted" by raising rather than
# by returning the content unchanged. That is a successful no-op,
# and letting it propagate discards the autofix that produced this
# module.
return module.bytes
return content.encode("utf-8")


Expand Down
1 change: 1 addition & 0 deletions src/fixit/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from fixit.testing import add_lint_rule_tests_to_module
from .config import ConfigTest
from .engine import EngineTest
from .format import FormatTest
from .ftypes import TypesTest
from .rule import RuleTest, RunnerTest
from .smoke import SmokeTest
Expand Down
34 changes: 34 additions & 0 deletions src/fixit/tests/format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from pathlib import Path
from unittest import TestCase

import libcst

from ..format import format_module
from ..ftypes import Config

FAKE_PATH = Path("fake.py")


class FormatTest(TestCase):
def test_black_already_formatted(self) -> None:
# black reports "already formatted" by raising rather than by returning
# the content unchanged. Letting that escape loses the autofix that
# produced the module, so the formatter has to treat it as a no-op.
config = Config(path=FAKE_PATH, formatter="black")
for content, expected in (
(b"x = 1\n", b"x = 1\n"),
(b"x=1\n", b"x = 1\n"),
):
with self.subTest(content=content):
module = libcst.parse_module(content)
self.assertEqual(expected, format_module(module, FAKE_PATH, config))

def test_no_formatter_returns_module_bytes(self) -> None:
config = Config(path=FAKE_PATH)
module = libcst.parse_module(b"x=1\n")
self.assertEqual(b"x=1\n", format_module(module, FAKE_PATH, config))