Skip to content

Instantly share code, notes, and snippets.

@jbwhit
Last active October 31, 2024 07:22
Show Gist options
  • Save jbwhit/eecdd1cac2756df85ad165f437445b0b to your computer and use it in GitHub Desktop.
Save jbwhit/eecdd1cac2756df85ad165f437445b0b to your computer and use it in GitHub Desktop.
Steps to use `ruff` in JupyterLab with the `jupyterlab_code_formatter` plugin.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@brurucy
Copy link

brurucy commented Jul 17, 2024

If you guys also want it to run check before format, then use this:

    @handle_line_ending_and_magic
    def format_code(
        self, code: str, notebook: bool, args: List[str] = [], **options
    ) -> str:
        # Lint
        linting = subprocess.run(
            [self.ruff_bin, "check", "--fix", "--exit-zero", "-"],
            input=code,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            encoding="utf-8",
        )
        
        # Format
        linted_code = linting.stdout
        process = subprocess.run(
            [self.ruff_bin, "format", "-"],
            input=linted_code,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            encoding="utf-8",
        )

        if process.stderr:
            logger.info(process.stderr)
            return code
        else:
            return process.stdout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment