Instagram / Fixit

Advanced Python linting framework with auto-fixes and hierarchical configuration that makes it easy to write custom in-repo lint rules.
https://fixit.rtfd.io/en/latest/
Other
659 stars 62 forks source link

lsp: tracking issue for code actions features #445

Open llllvvuu opened 3 months ago

llllvvuu commented 3 months ago

There are a couple of LSP features that I found harder than I expected to implement (and I am not a heavy user of these features), but if anyone happens to read this and enjoy the challenge, they are:

  1. Quickfix: Fix only the selected lint. Here's a template for how one might edit lsp.py (the TODO is the hard part):
    
    def diagnostic_generator(
    self, uri: str, autofix: bool = False
    ) -> Optional[Generator[Result, bool, Optional[FileContent]]]:
    # ... existing code ...
    for result in generator:
        violation = result.violation
        if not violation:
            continue
        diagnostic = Diagnostic(
            # ... existing fields ...
            code=violation.rule_name,
            source="fixit",
            data={
                "fix": # TODO: convert violation.replacement, a CSTNode, to a replacement string
            },
        )
        diagnostics.append(diagnostic)
    # ... existing code ...

def code_action(self, params: CodeActionParams) -> List[CodeAction]: uri = params.text_document.uri diagnostics = params.context.diagnostics actions = []

for diagnostic in diagnostics:
    if "fix" in diagnostic.data:
        fix = diagnostic.data["fix"]

        action = CodeAction(
            title=f"Fix: {diagnostic.code}",
            kind=CodeActionKind.QuickFix,
            edit=WorkspaceEdit(
                changes={
                    uri: [
                        TextEdit(
                            range=diagnostic.range,
                            new_text=fix,
                        )
                    ]
                }
            ),
        )
        actions.append(action)

return actions

2. Insert ignore comment: The hard part here is figuring out where to insert the comment.

For context, the code actions menu is the menu that comes from a light bulb next to the yellow squiggly under a lint issue. A good example of an extension that has this is the ESLint extension (built-in to VSCode I believe). Ruff also has these features, although I'm sure their model is very different so I'm not sure how easy it is to take inspiration.