astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.88k stars 1.1k forks source link

Support configuration to skip formatting for certain lines. #10506

Open zen-xu opened 8 months ago

zen-xu commented 8 months ago

Ruff formatter is awesome, and I have completely migrated my project from Black.

In addition, I am very eager for it to support the configuration to not format certain matching lines, rather than manually specifying in the code. Because I have some DSLs implemented in Python, I don't want Ruff to format those related codes. It would be great if Ruff had a related configuration to set this globally.

zen-xu commented 8 months ago

for example, I have a pytest BDD plugin (It hasn't been maintained for a long time 😅), its DSL is similar to a table.

import pytest

@pytest.mark.spock("maximum of {first} and {second} is {ret}")
def test_maximum():
    def expect(first, second, ret):
        assert max(first, second) == ret

    def where(_, first, second, ret):
        _ | first | second | ret
        _ | 3     | 7      | 7
        _ | 5     | 4      | 5
        _ | 9     | 9      | 9

ruff will format these code into

import pytest

@pytest.mark.spock("maximum of {first} and {second} is {ret}")
def test_maximum():
    def expect(first, second, ret):
        assert max(first, second) == ret

    def where(_, first, second, ret):
        _ | first | second | ret
        _ | 3 | 7 | 7
        _ | 5 | 4 | 5
        _ | 9 | 9 | 9
zen-xu commented 8 months ago

Additionally, it is also necessary to turn off lint for certain lines.

MichaReiser commented 8 months ago

Ruff formatter is awesome, and I have completely migrated my project from Black.

Thank you!

I can see the need for a configuration option to exclude certain code patterns from linting and formatting, and AST Grep (or GritIo) patterns could be a nice way of specifying that. I would rather not do a string-based search because that is error-prone and imposes the challenge that Ruff would need to map string offsets back to AST nodes (it's unclear what should happen if the start doesn't match the node offsets directly).

I'm afraid that this is probably a more distant feature because it requires building some infrastructure to support this and a very stable AST representation (changes to the AST would become breaking changes)