import argparse import os import tempfile import sys import ruff import pathlib import subprocess import json class PythonRuff: def lint(self, target_path: str | pathlib.Path, fix: bool = False) -> list[dict]: resolved_path = pathlib.Path(target_path).resolve() ruff_bin = str(ruff.find_ruff_bin()) args = [ruff_bin, "check", str(resolved_path), "--output-format=json"] if fix: args.append("--fix") result = subprocess.run(args, capture_output=True, text=True) stdout = result.stdout.strip() if stdout: parsed = json.loads(stdout) # Ensure return type is a list of dicts return parsed if isinstance(parsed, list) else [] return [] def compress_violations( self, violations: list[dict] | str, target_path: str | pathlib.Path ) -> dict[str, list[dict]]: # Handle cases where raw JSON string was passed instead of parsed list if isinstance(violations, str): violations = json.loads(violations) if violations.strip() else [] target_dir = pathlib.Path(target_path).resolve() if target_dir.is_file(): target_dir = target_dir.parent compressed: dict[str, list[dict]] = {} for violation in violations: full_path = pathlib.Path(violation["filename"]).resolve() try: rel_path = str(full_path.relative_to(target_dir)) except ValueError: rel_path = str(full_path) if rel_path not in compressed: compressed[rel_path] = [] compressed[rel_path].append( { "line": violation["location"]["row"], "column": violation["location"]["column"], "code": violation["code"], "message": violation["message"], } ) return compressed def format_violations( self, violations: list[dict] | dict[str, list[dict]] | str, target_path: str | pathlib.Path ) -> str: target_dir = pathlib.Path(target_path).resolve() # Reuse compressed dict if already compressed, otherwise compress if isinstance(violations, dict): compressed = violations else: compressed = self.compress_violations(violations, target_path) if not compressed: return f"Ruff Violations\nTARGET: {target_dir}\nNo violations found." # First pass: Collect rule definitions and calculate summary metrics rule_definitions: dict[str, str] = {} total_violations = 0 for file_violations in compressed.values(): total_violations += len(file_violations) for v in file_violations: if v["code"] not in rule_definitions: rule_definitions[v["code"]] = v["message"] file_count = len(compressed) # Build output buffer lines = [ "Ruff Violations", f"TARGET: {target_dir}", "", "Definitions:", ] for code in sorted(rule_definitions.keys()): lines.append(f" - {code}: {rule_definitions[code]}") lines.append("") for rel_file, file_violations in compressed.items(): lines.append(f"- FILE: {rel_file}") for v in file_violations: lines.append(f" - {v['line']}:{v['column']} {v['code']}") lines.append("") lines.append("- SUMMARY:") lines.append(f" - Total files with violations: {file_count}") lines.append(f" - Total violations: {total_violations}") return "\n".join(lines) def check_ruff(self, target_dir: str): raw_json = self.lint(target_dir) compressed_violations = self.compress_violations(raw_json, target_dir) return self.format_violations(compressed_violations, target_dir) def main(): """Command-line interface for the MDoctor tool.""" parser = argparse.ArgumentParser( description="python-ruff description" ) subparsers = parser.add_subparsers(dest="subcommand", help="Available subcommands") # chklint subcommand chklint_parser = subparsers.add_parser("chklint", help="") chklint_parser.add_argument( "directory", nargs="?", default=".", help="" ) args = parser.parse_args() pruff = PythonRuff() if args.subcommand is None: # Default to list with current directory args.subcommand = "chklint" args.directory = "." if args.subcommand == "chklint": violations = pruff.check_ruff(args.directory) print(violations) if __name__ == "__main__": main()