Plain is headed towards 1.0! Subscribe for development updates →

  1from __future__ import annotations
  2
  3import subprocess
  4import sys
  5import tomllib
  6from pathlib import Path
  7from typing import Any
  8
  9import click
 10
 11from plain.cli import register_cli
 12from plain.cli.print import print_event
 13from plain.cli.runtime import common_command, without_runtime_setup
 14
 15from .biome import Biome
 16
 17DEFAULT_RUFF_CONFIG = Path(__file__).parent / "ruff_defaults.toml"
 18
 19
 20@without_runtime_setup
 21@register_cli("code")
 22@click.group()
 23def cli() -> None:
 24    """Code formatting and linting"""
 25    pass
 26
 27
 28@without_runtime_setup
 29@cli.command()
 30@click.option("--force", is_flag=True, help="Reinstall even if up to date")
 31@click.pass_context
 32def install(ctx: click.Context, force: bool) -> None:
 33    """Install or update Biome binary"""
 34    config = get_code_config()
 35
 36    if not config.get("biome", {}).get("enabled", True):
 37        click.secho("Biome is disabled in configuration", fg="yellow")
 38        return
 39
 40    biome = Biome()
 41
 42    if force or not biome.is_installed() or biome.needs_update():
 43        version_to_install = config.get("biome", {}).get("version", "")
 44        if version_to_install:
 45            click.secho(
 46                f"Installing Biome standalone version {version_to_install}...",
 47                bold=True,
 48                nl=False,
 49            )
 50            installed = biome.install(version_to_install)
 51            click.secho(f"Biome {installed} installed", fg="green")
 52        else:
 53            ctx.invoke(update)
 54    else:
 55        click.secho("Biome already installed", fg="green")
 56
 57
 58@without_runtime_setup
 59@cli.command()
 60def update() -> None:
 61    """Update Biome to latest version"""
 62    config = get_code_config()
 63
 64    if not config.get("biome", {}).get("enabled", True):
 65        click.secho("Biome is disabled in configuration", fg="yellow")
 66        return
 67
 68    biome = Biome()
 69    click.secho("Updating Biome standalone...", bold=True)
 70    version = biome.install()
 71    click.secho(f"Biome {version} installed", fg="green")
 72
 73
 74@without_runtime_setup
 75@cli.command()
 76@click.pass_context
 77@click.argument("path", default=".")
 78@click.option("--skip-ruff", is_flag=True, help="Skip Ruff checks")
 79@click.option("--skip-ty", is_flag=True, help="Skip ty type checks")
 80@click.option("--skip-biome", is_flag=True, help="Skip Biome checks")
 81def check(
 82    ctx: click.Context,
 83    path: str,
 84    skip_ruff: bool,
 85    skip_ty: bool,
 86    skip_biome: bool,
 87) -> None:
 88    """Check for formatting and linting issues"""
 89    ruff_args = ["--config", str(DEFAULT_RUFF_CONFIG)]
 90    config = get_code_config()
 91
 92    for e in config.get("exclude", []):
 93        ruff_args.extend(["--exclude", e])
 94
 95    def maybe_exit(return_code: int) -> None:
 96        if return_code != 0:
 97            click.secho(
 98                "\nCode check failed. Run `plain fix` and/or fix issues manually.",
 99                fg="red",
100                err=True,
101            )
102            sys.exit(return_code)
103
104    if not skip_ruff:
105        print_event("ruff check...", newline=False)
106        result = subprocess.run(["ruff", "check", path, *ruff_args])
107        maybe_exit(result.returncode)
108
109        print_event("ruff format --check...", newline=False)
110        result = subprocess.run(["ruff", "format", path, "--check", *ruff_args])
111        maybe_exit(result.returncode)
112
113    if not skip_ty and config.get("ty", {}).get("enabled", True):
114        print_event("ty check...", newline=False)
115        result = subprocess.run(["ty", "check", path, "--no-progress"])
116        maybe_exit(result.returncode)
117
118    if not skip_biome and config.get("biome", {}).get("enabled", True):
119        biome = Biome()
120
121        if biome.needs_update():
122            ctx.invoke(install)
123
124        print_event("biome check...", newline=False)
125        result = biome.invoke("check", path)
126        maybe_exit(result.returncode)
127
128
129@common_command
130@without_runtime_setup
131@register_cli("fix", shortcut_for="code fix")
132@cli.command()
133@click.pass_context
134@click.argument("path", default=".")
135@click.option("--unsafe-fixes", is_flag=True, help="Apply ruff unsafe fixes")
136@click.option("--add-noqa", is_flag=True, help="Add noqa comments to suppress errors")
137def fix(ctx: click.Context, path: str, unsafe_fixes: bool, add_noqa: bool) -> None:
138    """Fix formatting and linting issues"""
139    ruff_args = ["--config", str(DEFAULT_RUFF_CONFIG)]
140    config = get_code_config()
141
142    for e in config.get("exclude", []):
143        ruff_args.extend(["--exclude", e])
144
145    if unsafe_fixes and add_noqa:
146        raise click.UsageError("Cannot use both --unsafe-fixes and --add-noqa")
147
148    if unsafe_fixes:
149        print_event("ruff check --fix --unsafe-fixes...", newline=False)
150        result = subprocess.run(
151            ["ruff", "check", path, "--fix", "--unsafe-fixes", *ruff_args]
152        )
153    elif add_noqa:
154        print_event("ruff check --add-noqa...", newline=False)
155        result = subprocess.run(["ruff", "check", path, "--add-noqa", *ruff_args])
156    else:
157        print_event("ruff check --fix...", newline=False)
158        result = subprocess.run(["ruff", "check", path, "--fix", *ruff_args])
159
160    if result.returncode != 0:
161        sys.exit(result.returncode)
162
163    print_event("ruff format...", newline=False)
164    result = subprocess.run(["ruff", "format", path, *ruff_args])
165    if result.returncode != 0:
166        sys.exit(result.returncode)
167
168    if config.get("biome", {}).get("enabled", True):
169        biome = Biome()
170
171        if biome.needs_update():
172            ctx.invoke(install)
173
174        args = ["check", path, "--write"]
175
176        if unsafe_fixes:
177            args.append("--unsafe")
178            print_event("biome check --write --unsafe...", newline=False)
179        else:
180            print_event("biome check --write...", newline=False)
181
182        result = biome.invoke(*args)
183
184        if result.returncode != 0:
185            sys.exit(result.returncode)
186
187
188def get_code_config() -> dict[str, Any]:
189    pyproject = Path("pyproject.toml")
190    if not pyproject.exists():
191        return {}
192    with pyproject.open("rb") as f:
193        return tomllib.load(f).get("tool", {}).get("plain", {}).get("code", {})