v0.166.0
  1import json
  2import subprocess
  3import sys
  4import tomllib
  5from pathlib import Path
  6from typing import Any
  7
  8import click
  9from plain.cli import register_cli
 10from plain.cli.print import print_event
 11from plain.cli.runtime import common_command, without_runtime_setup
 12
 13from .annotations import AnnotationResult, check_annotations
 14from .oxc import OxcTool, install_oxc
 15
 16DEFAULT_RUFF_CONFIG = Path(__file__).parent / "ruff_defaults.toml"
 17
 18
 19@without_runtime_setup
 20@register_cli("code")
 21@click.group()
 22def cli() -> None:
 23    """Code formatting and linting"""
 24
 25
 26@without_runtime_setup
 27@cli.command()
 28@click.option("--force", is_flag=True, help="Reinstall even if up to date")
 29@click.pass_context
 30def install(ctx: click.Context, force: bool) -> None:
 31    """Install or update oxlint and oxfmt binaries"""
 32    config = get_code_config()
 33
 34    if not config.get("oxc", {}).get("enabled", True):
 35        click.secho("Oxc is disabled in configuration", fg="yellow")
 36        return
 37
 38    oxlint = OxcTool("oxlint")
 39    oxfmt = OxcTool("oxfmt")
 40
 41    if force or not (oxlint.is_installed() and oxfmt.is_installed()):
 42        version_to_install = config.get("oxc", {}).get("version", "")
 43        if version_to_install:
 44            click.secho(
 45                f"Installing oxlint and oxfmt {version_to_install}...",
 46                bold=True,
 47                nl=False,
 48            )
 49            installed = install_oxc(version_to_install)
 50            click.secho(f"oxlint and oxfmt {installed} installed", fg="green")
 51        else:
 52            ctx.invoke(update)
 53    else:
 54        click.secho("oxlint and oxfmt already installed", fg="green")
 55
 56
 57@without_runtime_setup
 58@cli.command()
 59def update() -> None:
 60    """Update oxlint and oxfmt to latest version"""
 61    config = get_code_config()
 62
 63    if not config.get("oxc", {}).get("enabled", True):
 64        click.secho("Oxc is disabled in configuration", fg="yellow")
 65        return
 66
 67    click.secho("Updating oxlint and oxfmt...", bold=True)
 68    version = install_oxc()
 69    click.secho(f"oxlint and oxfmt {version} installed", fg="green")
 70
 71
 72def _partition_paths(paths: tuple[str, ...]) -> tuple[tuple[str, ...], tuple[str, ...]]:
 73    """Split paths into (python_paths, other_paths).
 74
 75    Directories go into both groups. Files are routed by extension.
 76    """
 77    python_paths: list[str] = []
 78    other_paths: list[str] = []
 79    for p in paths:
 80        if Path(p).is_dir():
 81            python_paths.append(p)
 82            other_paths.append(p)
 83        elif Path(p).suffix == ".py":
 84            python_paths.append(p)
 85        else:
 86            other_paths.append(p)
 87    return tuple(python_paths), tuple(other_paths)
 88
 89
 90@without_runtime_setup
 91@cli.command()
 92@click.pass_context
 93@click.argument("paths", nargs=-1)
 94@click.option("--skip-ruff", is_flag=True, help="Skip Ruff checks")
 95@click.option("--skip-ty", is_flag=True, help="Skip ty type checks")
 96@click.option("--skip-oxc", is_flag=True, help="Skip oxlint and oxfmt checks")
 97@click.option("--skip-annotations", is_flag=True, help="Skip type annotation checks")
 98def check(
 99    ctx: click.Context,
100    paths: tuple[str, ...],
101    skip_ruff: bool,
102    skip_ty: bool,
103    skip_oxc: bool,
104    skip_annotations: bool,
105) -> None:
106    """Check for formatting and linting issues"""
107    if not paths:
108        paths = (".",)
109
110    python_paths, other_paths = _partition_paths(paths)
111    ruff_args = ["--config", str(DEFAULT_RUFF_CONFIG)]
112    config = get_code_config()
113
114    for e in config.get("exclude", []):
115        ruff_args.extend(["--exclude", e])
116
117    def maybe_exit(return_code: int) -> None:
118        if return_code != 0:
119            click.secho(
120                "\nCode check failed. Run `plain fix` and/or fix issues manually.",
121                fg="red",
122                err=True,
123            )
124            sys.exit(return_code)
125
126    if not skip_ruff and python_paths:
127        print_event("ruff check...", newline=False)
128        result = subprocess.run(
129            ["ruff", "check", *python_paths, *ruff_args], check=False
130        )
131        maybe_exit(result.returncode)
132
133        print_event("ruff format --check...", newline=False)
134        result = subprocess.run(
135            ["ruff", "format", *python_paths, "--check", *ruff_args], check=False
136        )
137        maybe_exit(result.returncode)
138
139    if not skip_ty and python_paths and config.get("ty", {}).get("enabled", True):
140        print_event("ty check...", newline=False)
141        ty_args = ["ty", "check", *python_paths, "--no-progress"]
142        ty_args.extend(_tests_directory_search_path())
143        for e in config.get("exclude", []):
144            ty_args.extend(["--exclude", e])
145        result = subprocess.run(ty_args, check=False)
146        maybe_exit(result.returncode)
147
148    if not skip_oxc and other_paths and config.get("oxc", {}).get("enabled", True):
149        oxlint = OxcTool("oxlint")
150        oxfmt = OxcTool("oxfmt")
151
152        if not (oxlint.is_installed() and oxfmt.is_installed()):
153            ctx.invoke(install)
154
155        print_event("oxlint...", newline=False)
156        result = oxlint.invoke(*other_paths)
157        maybe_exit(result.returncode)
158
159        print_event("oxfmt --check...", newline=False)
160        result = oxfmt.invoke("--check", *other_paths)
161        maybe_exit(result.returncode)
162
163    if (
164        not skip_annotations
165        and python_paths
166        and config.get("annotations", {}).get("enabled", True)
167    ):
168        print_event("annotations...", newline=False)
169        # Combine top-level exclude with annotation-specific exclude
170        exclude_patterns = list(config.get("exclude", []))
171        exclude_patterns.extend(config.get("annotations", {}).get("exclude", []))
172        ann_result = check_annotations(
173            *python_paths, exclude_patterns=exclude_patterns or None
174        )
175        if ann_result.missing_count > 0:
176            click.secho(
177                f"{ann_result.missing_count} functions are untyped",
178                fg="red",
179            )
180            click.secho("Run 'plain code annotations --details' for details")
181            maybe_exit(1)
182        else:
183            click.secho("All functions typed!", fg="green")
184
185
186@without_runtime_setup
187@cli.command()
188@click.argument("paths", nargs=-1)
189@click.option("--details", is_flag=True, help="List untyped functions")
190@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
191def annotations(paths: tuple[str, ...], details: bool, as_json: bool) -> None:
192    """Check type annotation status"""
193    if not paths:
194        paths = (".",)
195    config = get_code_config()
196    # Combine top-level exclude with annotation-specific exclude
197    exclude_patterns = list(config.get("exclude", []))
198    exclude_patterns.extend(config.get("annotations", {}).get("exclude", []))
199    result = check_annotations(*paths, exclude_patterns=exclude_patterns or None)
200    if as_json:
201        _print_annotations_json(result)
202    else:
203        _print_annotations_report(result, show_details=details)
204
205
206def _print_annotations_report(
207    result: AnnotationResult,
208    show_details: bool = False,
209) -> None:
210    """Print the annotation report with colors."""
211    if result.total_functions == 0:
212        click.echo("No functions found")
213        return
214
215    # Detailed output first (if enabled and there are untyped functions)
216    if show_details and result.missing_count > 0:
217        # Collect all untyped functions with full paths
218        untyped_items: list[tuple[str, str, int, list[str]]] = []
219
220        for stats in result.file_stats:
221            for func in stats.functions:
222                if not func.is_fully_typed:
223                    issues = []
224                    if not func.has_return_type:
225                        issues.append("return type")
226                    missing_params = func.total_params - func.typed_params
227                    if missing_params > 0:
228                        param_word = "param" if missing_params == 1 else "params"
229                        issues.append(f"{missing_params} {param_word}")
230                    untyped_items.append((stats.path, func.name, func.line, issues))
231
232        # Sort by file path, then line number
233        untyped_items.sort(key=lambda x: (x[0], x[2]))
234
235        # Print each untyped function
236        for file_path, func_name, line, issues in untyped_items:
237            location = click.style(f"{file_path}:{line}", fg="cyan")
238            issue_str = click.style(f"({', '.join(issues)})", dim=True)
239            click.echo(f"{location}  {func_name}  {issue_str}")
240
241        click.echo()
242
243    # Summary line
244    pct = result.coverage_percentage
245    color = "green" if result.missing_count == 0 else "red"
246    click.secho(
247        f"{pct:.1f}% typed ({result.fully_typed_functions}/{result.total_functions} functions)",
248        fg=color,
249    )
250
251    # Code smell indicators (only if present)
252    smells = []
253    if result.total_ignores > 0:
254        smells.append(f"{result.total_ignores} ignore")
255    if result.total_casts > 0:
256        smells.append(f"{result.total_casts} cast")
257    if result.total_asserts > 0:
258        smells.append(f"{result.total_asserts} assert")
259    if smells:
260        click.secho(f"{', '.join(smells)}", fg="yellow")
261
262
263def _print_annotations_json(result: AnnotationResult) -> None:
264    """Print the annotation report as JSON."""
265    output = {
266        "overall_coverage": result.coverage_percentage,
267        "total_functions": result.total_functions,
268        "fully_typed_functions": result.fully_typed_functions,
269        "total_ignores": result.total_ignores,
270        "total_casts": result.total_casts,
271        "total_asserts": result.total_asserts,
272    }
273    click.echo(json.dumps(output))
274
275
276@common_command
277@without_runtime_setup
278@register_cli("fix", shortcut_for="code fix")
279@cli.command()
280@click.pass_context
281@click.argument("paths", nargs=-1)
282@click.option("--unsafe-fixes", is_flag=True, help="Apply ruff unsafe fixes")
283@click.option("--add-noqa", is_flag=True, help="Add noqa comments to suppress errors")
284@click.option("--skip-oxc", is_flag=True, help="Skip oxlint and oxfmt")
285def fix(
286    ctx: click.Context,
287    paths: tuple[str, ...],
288    unsafe_fixes: bool,
289    add_noqa: bool,
290    skip_oxc: bool,
291) -> None:
292    """Fix formatting and linting issues"""
293    if not paths:
294        paths = (".",)
295
296    python_paths, other_paths = _partition_paths(paths)
297    ruff_args = ["--config", str(DEFAULT_RUFF_CONFIG)]
298    config = get_code_config()
299
300    for e in config.get("exclude", []):
301        ruff_args.extend(["--exclude", e])
302
303    if unsafe_fixes and add_noqa:
304        raise click.UsageError("Cannot use both --unsafe-fixes and --add-noqa")
305
306    if python_paths:
307        if unsafe_fixes:
308            print_event("ruff check --fix --unsafe-fixes...", newline=False)
309            result = subprocess.run(
310                ["ruff", "check", *python_paths, "--fix", "--unsafe-fixes", *ruff_args],
311                check=False,
312            )
313        elif add_noqa:
314            print_event("ruff check --add-noqa...", newline=False)
315            result = subprocess.run(
316                ["ruff", "check", *python_paths, "--add-noqa", *ruff_args], check=False
317            )
318        else:
319            print_event("ruff check --fix...", newline=False)
320            result = subprocess.run(
321                ["ruff", "check", *python_paths, "--fix", *ruff_args], check=False
322            )
323
324        if result.returncode != 0:
325            sys.exit(result.returncode)
326
327        print_event("ruff format...", newline=False)
328        result = subprocess.run(
329            ["ruff", "format", *python_paths, *ruff_args], check=False
330        )
331        if result.returncode != 0:
332            sys.exit(result.returncode)
333
334    if not skip_oxc and other_paths and config.get("oxc", {}).get("enabled", True):
335        oxlint = OxcTool("oxlint")
336        oxfmt = OxcTool("oxfmt")
337
338        if not (oxlint.is_installed() and oxfmt.is_installed()):
339            ctx.invoke(install)
340
341        if unsafe_fixes:
342            print_event("oxlint --fix-dangerously...", newline=False)
343            result = oxlint.invoke(*other_paths, "--fix-dangerously")
344        else:
345            print_event("oxlint --fix...", newline=False)
346            result = oxlint.invoke(*other_paths, "--fix")
347
348        if result.returncode != 0:
349            sys.exit(result.returncode)
350
351        print_event("oxfmt...", newline=False)
352        result = oxfmt.invoke(*other_paths)
353
354        if result.returncode != 0:
355            sys.exit(result.returncode)
356
357
358def _tests_directory_search_path() -> list[str]:
359    """
360    The ty arguments that let a test file find the helper modules beside it.
361
362    `plain test` puts a project's `tests/` directory on the import path, so a
363    test file imports a helper module by its path from there
364    (`from helpers import create_user`). The type checker has to look in the
365    same place. It finds `tests/` by itself only when the directory isn't a
366    package, and with a `tests/__init__.py` in it every one of those imports
367    is reported as unresolved. This adds to any `extra-paths` the project's
368    own ty configuration lists.
369    """
370    if Path("tests").is_dir():
371        return ["--extra-search-path", "tests"]
372    return []
373
374
375def get_code_config() -> dict[str, Any]:
376    pyproject = Path("pyproject.toml")
377    if not pyproject.exists():
378        return {}
379    with pyproject.open("rb") as f:
380        return tomllib.load(f).get("tool", {}).get("plain", {}).get("code", {})