|
| 1 | +import re |
| 2 | +import subprocess |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import click |
| 7 | + |
| 8 | +DEFAULT_RUFF_CONFIG = Path(__file__).parent / "ruff_defaults.toml" |
| 9 | + |
| 10 | + |
| 11 | +@click.group() |
| 12 | +def cli(): |
| 13 | + """Standard code formatting and linting.""" |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +@cli.command() |
| 18 | +@click.argument("path", default=".") |
| 19 | +@click.option("--fix/--no-fix", "do_fix", default=False) |
| 20 | +def lint(path, do_fix): |
| 21 | + ruff_args = [] |
| 22 | + |
| 23 | + if not user_has_ruff_config(): |
| 24 | + click.secho("Using default bolt.code ruff config", italic=True, bold=True) |
| 25 | + ruff_args.extend(["--config", str(DEFAULT_RUFF_CONFIG)]) |
| 26 | + |
| 27 | + if do_fix: |
| 28 | + ruff_args.append("--fix") |
| 29 | + |
| 30 | + click.secho("Ruff check", bold=True) |
| 31 | + result = subprocess.run(["ruff", "check", path, *ruff_args]) |
| 32 | + |
| 33 | + if result.returncode != 0: |
| 34 | + sys.exit(result.returncode) |
| 35 | + |
| 36 | + |
| 37 | +@cli.command() |
| 38 | +@click.argument("path", default=".") |
| 39 | +def format(path): |
| 40 | + ruff_args = [] |
| 41 | + |
| 42 | + if not user_has_ruff_config(): |
| 43 | + click.secho("Using default bolt.code ruff config", italic=True, bold=True) |
| 44 | + ruff_args.extend(["--config", str(DEFAULT_RUFF_CONFIG)]) |
| 45 | + |
| 46 | + click.secho("Ruff format", bold=True) |
| 47 | + result = subprocess.run(["ruff", "format", path, *ruff_args]) |
| 48 | + |
| 49 | + if result.returncode != 0: |
| 50 | + sys.exit(result.returncode) |
| 51 | + |
| 52 | + |
| 53 | +@cli.command() |
| 54 | +@click.argument("path", default=".") |
| 55 | +def fix(path): |
| 56 | + """Lint and format the given path.""" |
| 57 | + ruff_args = [] |
| 58 | + |
| 59 | + if not user_has_ruff_config(): |
| 60 | + click.secho("Using default bolt.code ruff config", italic=True, bold=True) |
| 61 | + ruff_args.extend(["--config", str(DEFAULT_RUFF_CONFIG)]) |
| 62 | + |
| 63 | + click.secho("Ruff check", bold=True) |
| 64 | + result = subprocess.run(["ruff", "check", path, "--fix", *ruff_args]) |
| 65 | + |
| 66 | + if result.returncode != 0: |
| 67 | + sys.exit(result.returncode) |
| 68 | + |
| 69 | + click.secho("Ruff format", bold=True) |
| 70 | + result = subprocess.run(["ruff", "format", path, *ruff_args]) |
| 71 | + |
| 72 | + if result.returncode != 0: |
| 73 | + sys.exit(result.returncode) |
| 74 | + |
| 75 | + |
| 76 | +def user_has_ruff_config(): |
| 77 | + try: |
| 78 | + output = subprocess.check_output(["ruff", "check", ".", "--show-settings"]) |
| 79 | + except subprocess.CalledProcessError: |
| 80 | + return False |
| 81 | + |
| 82 | + if re.search("Settings path: (.+)", output.decode("utf-8")): |
| 83 | + return True |
| 84 | + else: |
| 85 | + return False |
0 commit comments