|
| 1 | +"""check-language command — scan Markdown artifacts for disallowed Unicode scripts.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +from pathlib import Path |
| 5 | +from typing import List |
| 6 | + |
| 7 | +from ..utils import error_codes as EC |
| 8 | +from ..utils.ui import ui |
| 9 | + |
| 10 | + |
| 11 | +def cmd_check_language(argv: List[str]) -> int: |
| 12 | + """Scan Markdown files for characters outside the allowed language set. |
| 13 | +
|
| 14 | + Exit codes: |
| 15 | + 0 — all files pass |
| 16 | + 1 — configuration / path error |
| 17 | + 2 — one or more language violations found |
| 18 | + """ |
| 19 | + p = argparse.ArgumentParser( |
| 20 | + prog="check-language", |
| 21 | + description=( |
| 22 | + "Scan Markdown artifacts for characters outside the allowed Unicode " |
| 23 | + "script set. Language policy is read from workspace config " |
| 24 | + "([validation] allowed_content_languages) or set via --languages." |
| 25 | + ), |
| 26 | + ) |
| 27 | + p.add_argument( |
| 28 | + "paths", |
| 29 | + nargs="*", |
| 30 | + metavar="path", |
| 31 | + help="Files or directories to scan (default: project architecture/ folder)", |
| 32 | + ) |
| 33 | + p.add_argument( |
| 34 | + "--languages", |
| 35 | + default=None, |
| 36 | + metavar="CODES", |
| 37 | + help="Comma-separated language codes to allow, e.g. 'en' or 'en,ru'. " |
| 38 | + "Overrides workspace config.", |
| 39 | + ) |
| 40 | + p.add_argument( |
| 41 | + "--exclude", |
| 42 | + action="append", |
| 43 | + default=[], |
| 44 | + metavar="GLOB", |
| 45 | + dest="exclude", |
| 46 | + help=( |
| 47 | + "Glob pattern for paths to skip (relative to each scan root). " |
| 48 | + "Repeatable: --exclude 'translations/**' --exclude 'specs/i18n/*.md'. " |
| 49 | + "Merged with check_language_ignore_paths from workspace config." |
| 50 | + ), |
| 51 | + ) |
| 52 | + p.add_argument( |
| 53 | + "--quiet", |
| 54 | + "-q", |
| 55 | + action="store_true", |
| 56 | + help="Suppress summary header; show violations only.", |
| 57 | + ) |
| 58 | + args = p.parse_args(argv) |
| 59 | + |
| 60 | + from ..utils.content_language import ( |
| 61 | + SUPPORTED_LANGUAGES, |
| 62 | + build_allowed_ranges, |
| 63 | + scan_paths, |
| 64 | + ) |
| 65 | + |
| 66 | + # ── Resolve allowed languages ──────────────────────────────────────────── |
| 67 | + if args.languages is not None: |
| 68 | + raw_langs = [lang_code.strip().lower() for lang_code in args.languages.split(",") if lang_code.strip()] |
| 69 | + unknown = [lang_code for lang_code in raw_langs if lang_code not in SUPPORTED_LANGUAGES] |
| 70 | + if unknown: |
| 71 | + ui.result({ |
| 72 | + "status": "ERROR", |
| 73 | + "message": ( |
| 74 | + f"Unknown language code(s): {', '.join(unknown)}. " |
| 75 | + f"Supported: {', '.join(SUPPORTED_LANGUAGES)}" |
| 76 | + ), |
| 77 | + }) |
| 78 | + return 1 |
| 79 | + allowed_langs = raw_langs |
| 80 | + else: |
| 81 | + allowed_langs = _read_config_languages() |
| 82 | + |
| 83 | + # ── Resolve ignore globs ───────────────────────────────────────────────── |
| 84 | + ignore_globs: List[str] = list(args.exclude) + _read_config_ignore_paths() |
| 85 | + |
| 86 | + # ── Resolve scan roots ─────────────────────────────────────────────────── |
| 87 | + if args.paths: |
| 88 | + roots = [Path(pth) for pth in args.paths] |
| 89 | + else: |
| 90 | + roots = _default_roots() |
| 91 | + |
| 92 | + missing = [str(r) for r in roots if not r.exists()] |
| 93 | + if missing: |
| 94 | + ui.result({ |
| 95 | + "status": "ERROR", |
| 96 | + "message": f"Path(s) not found: {', '.join(missing)}", |
| 97 | + }) |
| 98 | + return 1 |
| 99 | + |
| 100 | + # ── Scan ───────────────────────────────────────────────────────────────── |
| 101 | + allowed_ranges = build_allowed_ranges(allowed_langs) |
| 102 | + from ..utils.content_language import LangScanError |
| 103 | + try: |
| 104 | + violations = scan_paths(roots, allowed_ranges, ignore_globs=ignore_globs or None) |
| 105 | + except LangScanError as exc: |
| 106 | + ui.result({ |
| 107 | + "status": "ERROR", |
| 108 | + "message": str(exc), |
| 109 | + }) |
| 110 | + return 1 |
| 111 | + |
| 112 | + files_scanned = _count_md_files(roots) |
| 113 | + |
| 114 | + if not violations: |
| 115 | + result = { |
| 116 | + "status": "PASS", |
| 117 | + "allowed_languages": allowed_langs, |
| 118 | + "files_scanned": files_scanned, |
| 119 | + "violation_count": 0, |
| 120 | + } |
| 121 | + if ignore_globs: |
| 122 | + result["ignore_globs"] = ignore_globs |
| 123 | + ui.result(result, human_fn=lambda d: _human_result(d, quiet=args.quiet)) |
| 124 | + return 0 |
| 125 | + |
| 126 | + # Group violations by file for reporting |
| 127 | + by_file: dict = {} |
| 128 | + for v in violations: |
| 129 | + by_file.setdefault(str(v.path), []).append(v) |
| 130 | + |
| 131 | + violation_items = [] |
| 132 | + for file_path, file_violations in by_file.items(): |
| 133 | + for v in file_violations: |
| 134 | + violation_items.append({ |
| 135 | + "path": file_path, |
| 136 | + "line": v.lineno, |
| 137 | + "chars": v.bad_chars_preview(), |
| 138 | + "preview": v.line_preview(), |
| 139 | + "code": EC.CONTENT_LANGUAGE_VIOLATION, |
| 140 | + }) |
| 141 | + |
| 142 | + result = { |
| 143 | + "status": "FAIL", |
| 144 | + "allowed_languages": allowed_langs, |
| 145 | + "files_scanned": files_scanned, |
| 146 | + "violation_count": len(violations), |
| 147 | + "file_count": len(by_file), |
| 148 | + "violations": violation_items, |
| 149 | + } |
| 150 | + if ignore_globs: |
| 151 | + result["ignore_globs"] = ignore_globs |
| 152 | + ui.result(result, human_fn=lambda d: _human_result(d, quiet=args.quiet)) |
| 153 | + return 2 |
| 154 | + |
| 155 | + |
| 156 | +# --------------------------------------------------------------------------- |
| 157 | +# Helpers |
| 158 | +# --------------------------------------------------------------------------- |
| 159 | + |
| 160 | +def _read_config_languages() -> List[str]: |
| 161 | + """Read allowed_content_languages from workspace config; fall back to ['en'].""" |
| 162 | + try: |
| 163 | + from ..utils.context import get_context |
| 164 | + from ..utils.workspace import find_workspace_config |
| 165 | + |
| 166 | + ctx = get_context() |
| 167 | + if ctx is None: |
| 168 | + return ["en"] |
| 169 | + _ws_cfg, _ = find_workspace_config(ctx.project_root) |
| 170 | + if _ws_cfg is not None and _ws_cfg.validation is not None: # type: ignore[union-attr] |
| 171 | + langs = _ws_cfg.validation.allowed_content_languages # type: ignore[union-attr] |
| 172 | + if langs: |
| 173 | + return langs |
| 174 | + except Exception: |
| 175 | + pass |
| 176 | + return ["en"] |
| 177 | + |
| 178 | + |
| 179 | +def _read_config_ignore_paths() -> List[str]: |
| 180 | + """Read check_language_ignore_paths from workspace config; fall back to [].""" |
| 181 | + try: |
| 182 | + from ..utils.context import get_context |
| 183 | + from ..utils.workspace import find_workspace_config |
| 184 | + |
| 185 | + ctx = get_context() |
| 186 | + if ctx is None: |
| 187 | + return [] |
| 188 | + _ws_cfg, _ = find_workspace_config(ctx.project_root) |
| 189 | + if _ws_cfg is not None and _ws_cfg.validation is not None: # type: ignore[union-attr] |
| 190 | + paths = _ws_cfg.validation.check_language_ignore_paths # type: ignore[union-attr] |
| 191 | + if paths: |
| 192 | + return list(paths) |
| 193 | + except Exception: |
| 194 | + pass |
| 195 | + return [] |
| 196 | + |
| 197 | + |
| 198 | +def _default_roots() -> List[Path]: |
| 199 | + """Return the default scan root (architecture/ under project root).""" |
| 200 | + try: |
| 201 | + from ..utils.context import get_context |
| 202 | + |
| 203 | + ctx = get_context() |
| 204 | + if ctx is not None: |
| 205 | + return [ctx.project_root / "architecture"] |
| 206 | + except (ImportError, AttributeError): |
| 207 | + pass |
| 208 | + return [Path.cwd() / "architecture"] |
| 209 | + |
| 210 | + |
| 211 | +def _count_md_files(roots: List[Path]) -> int: |
| 212 | + count = 0 |
| 213 | + for root in roots: |
| 214 | + if root.is_file(): |
| 215 | + if root.suffix.lower() == ".md": |
| 216 | + count += 1 |
| 217 | + elif root.is_dir(): |
| 218 | + count += sum(1 for _ in root.rglob("*.md")) |
| 219 | + return count |
| 220 | + |
| 221 | + |
| 222 | +# --------------------------------------------------------------------------- |
| 223 | +# Human formatter |
| 224 | +# --------------------------------------------------------------------------- |
| 225 | + |
| 226 | +def _human_result(data: dict, quiet: bool = False) -> None: |
| 227 | + status = data.get("status", "") |
| 228 | + allowed = data.get("allowed_languages", []) |
| 229 | + |
| 230 | + if not quiet: |
| 231 | + ui.header("check-language") |
| 232 | + ui.detail("Allowed languages", ", ".join(allowed)) |
| 233 | + n_files = data.get("files_scanned", 0) |
| 234 | + ui.detail("Files scanned", str(n_files)) |
| 235 | + ui.blank() |
| 236 | + |
| 237 | + if status == "PASS": |
| 238 | + ui.success("No language violations found.") |
| 239 | + ui.blank() |
| 240 | + return |
| 241 | + |
| 242 | + if status == "ERROR": |
| 243 | + ui.error(str(data.get("message", "Unknown error"))) |
| 244 | + ui.blank() |
| 245 | + return |
| 246 | + |
| 247 | + n_viol = data.get("violation_count", 0) |
| 248 | + n_file_count = data.get("file_count", 0) |
| 249 | + ui.warn(f"FAIL {n_viol} violation(s) in {n_file_count} file(s)") |
| 250 | + ui.blank() |
| 251 | + |
| 252 | + violations = data.get("violations", []) |
| 253 | + by_file: dict = {} |
| 254 | + for v in violations: |
| 255 | + by_file.setdefault(v["path"], []).append(v) |
| 256 | + |
| 257 | + for file_path, file_violations in by_file.items(): |
| 258 | + ui.substep(f" {ui.relpath(file_path)} ({len(file_violations)} line(s))") |
| 259 | + for v in file_violations: |
| 260 | + ui.substep(f" line {v['line']:>4} [{v['chars']}] {v['preview']}") |
| 261 | + ui.blank() |
| 262 | + |
| 263 | + ui.hint("Fix: rewrite flagged content in the allowed language(s).") |
| 264 | + ui.hint( |
| 265 | + "To allow additional scripts, add to .cypilot-workspace.toml:\n" |
| 266 | + " [validation]\n" |
| 267 | + " allowed_content_languages = [\"en\", \"ru\"]" |
| 268 | + ) |
| 269 | + ui.hint( |
| 270 | + "To ignore specific paths (e.g. translation specs), use --exclude or add to config:\n" |
| 271 | + " [validation]\n" |
| 272 | + " check_language_ignore_paths = [\"translations/**\", \"specs/i18n/*.md\"]\n" |
| 273 | + "To ignore a single file, add <!-- cpt-lang: ignore --> anywhere in the file." |
| 274 | + ) |
| 275 | + if data.get("ignore_globs"): |
| 276 | + ui.detail("Active ignore globs", ", ".join(data["ignore_globs"])) |
| 277 | + ui.blank() |
0 commit comments