cha-cli 1.0.5

Cha — pluggable code smell detection CLI (察)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use std::path::{Path, PathBuf};
use std::process;

mod analyze;
mod deps;
mod diff;
mod hotspot;
mod plugin;
mod tangled;
mod trend;

use cha_core::{Config, Finding, PluginRegistry, SourceFile};
use clap::{CommandFactory, Parser, ValueEnum};
use clap_complete::engine::ArgValueCandidates;

#[derive(Clone, ValueEnum)]
enum Format {
    Terminal,
    Json,
    Llm,
    Sarif,
    Html,
}

#[derive(Clone, ValueEnum, PartialEq, Eq, PartialOrd, Ord)]
enum FailLevel {
    Hint,
    Warning,
    Error,
}

#[derive(Clone, ValueEnum)]
pub(crate) enum DepsFormat {
    Dot,
    Json,
    Mermaid,
    Plantuml,
}

#[derive(Clone, ValueEnum)]
pub(crate) enum DepsDepth {
    File,
    Dir,
}

#[derive(Clone, ValueEnum, Default)]
pub(crate) enum DepsType {
    #[default]
    Imports,
    Classes,
    Calls,
}

#[derive(Clone, ValueEnum, Default)]
pub(crate) enum DepsDirection {
    In,
    Out,
    #[default]
    Both,
}

#[derive(Parser)]
#[command(
    name = "cha",
    version,
    about = "察 — Code quality & architecture analysis engine"
)]
enum Cli {
    /// Analyze source files for code smells
    Analyze {
        /// Files or directories to analyze (defaults to current directory)
        paths: Vec<String>,
        /// Output format
        #[arg(long, default_value = "terminal")]
        format: Format,
        /// Exit with code 1 if findings at this severity or above exist
        #[arg(long)]
        fail_on: Option<FailLevel>,
        /// Only analyze files changed in git diff (unstaged)
        #[arg(long)]
        diff: bool,
        /// Read unified diff from stdin, analyze only changed files/lines
        #[arg(long)]
        stdin_diff: bool,
        /// Only run specific plugins (comma-separated names)
        #[arg(long, value_delimiter = ',', add = ArgValueCandidates::new(plugin_candidates))]
        plugin: Vec<String>,
        /// Disable analysis cache (force full re-analysis)
        #[arg(long)]
        no_cache: bool,
        /// Only report findings not in the baseline file
        #[arg(long)]
        baseline: Option<String>,
        /// Write output to file (used with --format html)
        #[arg(long, short)]
        output: Option<String>,
        /// Strictness level: relaxed (2x), default (1x), strict (0.5x), or a custom float
        #[arg(long)]
        strictness: Option<String>,
    },
    /// Generate a baseline file from current findings (suppresses known issues)
    Baseline {
        /// Files or directories to analyze (defaults to current directory)
        paths: Vec<String>,
        /// Output path for baseline file (default: .cha/baseline.json)
        #[arg(long, short)]
        output: Option<String>,
    },
    /// Parse source files and show structure
    Parse {
        /// Files or directories to parse (defaults to current directory)
        paths: Vec<String>,
    },
    /// Generate a default .cha.toml configuration file
    Init,
    /// Print JSON Schema for the analysis output format
    Schema,
    /// Auto-fix simple issues (naming conventions)
    Fix {
        /// Files or directories to fix (defaults to current directory)
        paths: Vec<String>,
        /// Only fix files changed in git diff (unstaged)
        #[arg(long)]
        diff: bool,
        /// Dry run — show what would be changed without modifying files
        #[arg(long)]
        dry_run: bool,
    },
    /// Manage WASM plugins
    Plugin {
        #[command(subcommand)]
        cmd: PluginCmd,
    },
    /// Show dependency graph (imports, classes, or calls)
    Deps {
        /// Files or directories (defaults to current directory)
        paths: Vec<String>,
        /// Output format
        #[arg(long, default_value = "dot")]
        format: DepsFormat,
        /// Aggregation depth: "file" (default) or "dir" (imports only)
        #[arg(long, default_value = "file")]
        depth: DepsDepth,
        /// Graph type: imports (default), classes, or calls
        #[arg(long, default_value = "imports")]
        r#type: DepsType,
        /// Filter by regex pattern (shows connected subgraph)
        #[arg(long)]
        filter: Option<String>,
        /// Exact match: only show edges directly matching the filter
        #[arg(long)]
        exact: bool,
        /// Show detailed class diagram (fields and methods)
        #[arg(long)]
        detail: bool,
        /// Edge direction when filtering: in (who depends on target), out (target depends on), both
        #[arg(long, default_value = "both")]
        direction: DepsDirection,
    },
    /// Analyze recent git commits to show issue trend
    Trend {
        /// Number of commits to analyze (default: 10)
        #[arg(short, long, default_value = "10")]
        count: usize,
        /// Output format (terminal or json)
        #[arg(long, default_value = "terminal")]
        format: Format,
    },
    /// Show hotspots: files with high change frequency × complexity
    Hotspot {
        /// Number of recent commits to analyze (default: 100)
        #[arg(short, long, default_value = "100")]
        count: usize,
        /// Show top N files (default: 20)
        #[arg(short, long, default_value = "20")]
        top: usize,
        /// Output format (terminal or json)
        #[arg(long, default_value = "terminal")]
        format: Format,
    },
    /// Show builtin language presets and strictness levels
    Preset {
        #[command(subcommand)]
        cmd: PresetCmd,
    },
    /// Generate shell completion scripts (supports dynamic plugin name completion)
    Completions {
        /// Shell to generate completions for (bash, zsh, fish, powershell, elvish)
        shell: Option<clap_complete::Shell>,
    },
    /// Start the Language Server Protocol server
    Lsp,
}

#[derive(clap::Subcommand)]
enum PluginCmd {
    /// Scaffold a new plugin project
    New {
        /// Plugin name
        name: String,
    },
    /// Build the plugin in the current directory
    Build,
    /// List installed plugins
    List,
    /// Install a .wasm file into .cha/plugins/
    Install {
        /// Path to the .wasm file
        path: String,
    },
    /// Remove an installed plugin
    Remove {
        /// Plugin name (with or without .wasm extension)
        name: String,
    },
}

#[derive(clap::Subcommand)]
enum PresetCmd {
    /// List all supported languages and their builtin profiles
    List,
    /// Show plugin rules and thresholds for a specific language
    Show {
        /// Language name (rust, typescript, python, go, c, cpp)
        language: String,
    },
}

impl DiffMode {
    fn from_flags(diff: bool, stdin_diff: bool) -> Self {
        if stdin_diff {
            Self::Stdin
        } else if diff {
            Self::Git
        } else {
            Self::None
        }
    }
}

fn main() {
    clap_complete::CompleteEnv::with_factory(Cli::command).complete();
    let cli = Cli::parse();
    let code = dispatch(cli);
    if code != 0 {
        process::exit(code);
    }
}

fn dispatch(cli: Cli) -> i32 {
    match cli {
        Cli::Analyze {
            paths,
            format,
            fail_on,
            diff,
            stdin_diff,
            plugin,
            no_cache,
            baseline,
            output,
            strictness,
        } => {
            let mode = DiffMode::from_flags(diff, stdin_diff);
            if no_cache {
                let cwd = std::env::current_dir().unwrap_or_default();
                let _ = std::fs::remove_dir_all(cwd.join(".cha/cache"));
            }
            analyze::cmd_analyze(&analyze::AnalyzeOpts {
                paths: &paths,
                format: &format,
                fail_on: fail_on.as_ref(),
                diff_mode: mode,
                plugin_filter: &plugin,
                baseline_path: baseline.as_deref(),
                output_path: output.as_deref(),
                strictness: strictness.as_deref(),
            })
        }
        other => {
            run_other(other);
            0
        }
    }
}

// cha:ignore switch_statement
fn run_other(cli: Cli) {
    match cli {
        Cli::Baseline { paths, output } => cmd_baseline(&paths, output.as_deref()),
        Cli::Parse { paths } => cmd_parse(&paths),
        Cli::Init | Cli::Schema => cmd_init_or_schema(cli),
        Cli::Fix {
            paths,
            diff,
            dry_run,
        } => cmd_fix(&paths, diff, dry_run),
        Cli::Plugin { cmd } => cmd_plugin(cmd),
        Cli::Trend { count, format } => trend::cmd_trend(count, &format),
        Cli::Hotspot { count, top, format } => hotspot::cmd_hotspot(count, top, &format),
        Cli::Deps {
            paths,
            format,
            depth,
            r#type,
            filter,
            exact,
            detail,
            direction,
        } => deps::cmd_deps(
            &paths,
            &format,
            &depth,
            &r#type,
            filter.as_deref(),
            exact,
            detail,
            &direction,
        ),
        Cli::Completions { shell } => cmd_completions(shell),
        Cli::Preset { cmd } => cmd_preset(cmd),
        Cli::Lsp => {
            tokio::runtime::Runtime::new()
                .unwrap()
                .block_on(cha_lsp::run_lsp());
        }
        _ => unreachable!(),
    }
}

fn cmd_completions(shell: Option<clap_complete::Shell>) {
    let Some(shell) = shell else {
        println!("Enable shell completions for cha (with dynamic plugin name support):\n");
        println!("  bash:  eval \"$(cha completions bash)\"");
        println!("  zsh:   eval \"$(cha completions zsh)\"");
        println!("  fish:  cha completions fish | source");
        println!("\nTo make it permanent, add the line to your shell config file:");
        println!("  bash:  ~/.bashrc");
        println!("  zsh:   ~/.zshrc");
        println!("  fish:  ~/.config/fish/config.fish");
        return;
    };
    let shell_name = match shell {
        clap_complete::Shell::Bash => "bash",
        clap_complete::Shell::Zsh => "zsh",
        clap_complete::Shell::Fish => "fish",
        clap_complete::Shell::PowerShell => "powershell",
        clap_complete::Shell::Elvish => "elvish",
        _ => {
            eprintln!("Unsupported shell for dynamic completions, falling back to static");
            let mut cmd = Cli::command();
            clap_complete::generate(shell, &mut cmd, "cha", &mut std::io::stdout());
            return;
        }
    };
    let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("cha"));
    let output = std::process::Command::new(&exe)
        .env("COMPLETE", shell_name)
        .output();
    if let Ok(o) = output {
        use std::io::Write;
        std::io::stdout().write_all(&o.stdout).ok();
    }
}

const SUPPORTED_LANGUAGES: &[&str] = &["rust", "typescript", "python", "go", "c", "cpp"];

fn cmd_preset(cmd: PresetCmd) {
    match cmd {
        PresetCmd::List => {
            println!("Supported languages:\n");
            for lang in SUPPORTED_LANGUAGES {
                let profile = cha_core::builtin_language_profile(lang);
                let disabled = profile
                    .as_ref()
                    .map(|p| p.iter().filter(|(_, e)| !e).count())
                    .unwrap_or(0);
                if disabled > 0 {
                    println!("  {lang:<12} ({disabled} rules disabled by default)");
                } else {
                    println!("  {lang:<12} (all rules enabled)");
                }
            }
            println!("\nUse `cha preset show <language>` for details.");
        }
        PresetCmd::Show { language } => cmd_preset_show(&language),
    }
}

fn cmd_preset_show(language: &str) {
    let lang = language.to_lowercase();
    if !SUPPORTED_LANGUAGES.contains(&lang.as_str()) {
        eprintln!("Unknown language: {language}");
        eprintln!("Supported: {}", SUPPORTED_LANGUAGES.join(", "));
        return;
    }

    let cwd = std::env::current_dir().unwrap_or_default();
    let config = Config::load(&cwd);
    let resolved = config.resolve_for_language(&lang);
    let profile = cha_core::builtin_language_profile(&lang);
    let disabled: std::collections::HashSet<&str> = profile
        .as_ref()
        .map(|p| p.iter().filter(|(_, e)| !e).map(|(n, _)| *n).collect())
        .unwrap_or_default();

    let registry = PluginRegistry::from_config(&resolved, &cwd);
    let factor = resolved.strictness.factor();

    println!("Language: {lang}");
    println!("Strictness: {factor}x\n");
    println!("  {:<28} {:<8} Description", "Plugin", "Status");
    let sep = "".repeat(70);
    println!("  {sep}");

    for p in registry.plugins() {
        let status = "";
        println!("  {:<28} {:<8} {}", p.name(), status, p.description());
    }

    if !disabled.is_empty() {
        println!();
        for name in &disabled {
            println!(
                "  {:<28} {:<8} (disabled by builtin {lang} profile)",
                name, "·"
            );
        }
    }

    println!("\nOverride in .cha.toml:  [languages.{lang}.plugins.<name>]  enabled = true/false");
}

fn cmd_init_or_schema(cli: Cli) {
    match cli {
        Cli::Init => cmd_init(),
        Cli::Schema => println!("{}", cha_core::findings_json_schema()),
        _ => unreachable!(),
    }
}

fn cmd_plugin(cmd: PluginCmd) {
    match cmd {
        PluginCmd::New { name } => plugin::cmd_new(&name),
        PluginCmd::Build => plugin::cmd_build(),
        PluginCmd::List => plugin::cmd_list(),
        PluginCmd::Install { path } => plugin::cmd_install(&path),
        PluginCmd::Remove { name } => plugin::cmd_remove(&name),
    }
}

pub(crate) fn new_progress_bar(len: u64) -> indicatif::ProgressBar {
    let pb = indicatif::ProgressBar::new(len);
    pb.set_style(
        indicatif::ProgressStyle::default_bar()
            .template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len}")
            .unwrap()
            .tick_strings(&["", "", "", "", "", "", "", "", "", "", ""])
            .progress_chars("█▓░"),
    );
    pb.enable_steady_tick(std::time::Duration::from_millis(80));
    pb
}

/// Recursively collect source files, respecting .gitignore and skipping common build dirs.
pub(crate) fn collect_files(paths: &[String]) -> Vec<PathBuf> {
    let targets: Vec<&str> = if paths.is_empty() {
        vec!["."]
    } else {
        paths.iter().map(|s| s.as_str()).collect()
    };

    let mut files = Vec::new();
    for target in targets {
        let path = PathBuf::from(target);
        if path.is_file() {
            files.push(path);
        } else {
            walk_directory(&path, &mut files);
        }
    }
    files
}

// Walk a directory recursively, collecting files while respecting .gitignore.
fn walk_directory(root: &Path, files: &mut Vec<PathBuf>) {
    let walker = ignore::WalkBuilder::new(root)
        .hidden(true)
        .git_ignore(true)
        .git_global(true)
        .filter_entry(|e| {
            let name = e.file_name().to_string_lossy();
            !matches!(name.as_ref(), "target" | "node_modules" | "dist" | "build")
        })
        .build();
    for entry in walker.flatten() {
        if entry.file_type().is_some_and(|ft| ft.is_file()) {
            files.push(entry.into_path());
        }
    }
}

/// Get changed files from git diff.
pub(crate) fn git_diff_files() -> Vec<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["diff", "--name-only", "--diff-filter=ACMR", "HEAD"])
        .output();
    match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .map(PathBuf::from)
            .collect(),
        _ => {
            eprintln!("warning: git diff failed, analyzing all files");
            vec![]
        }
    }
}

/// How to handle diff-based filtering.
enum DiffMode {
    None,
    Git,
    Stdin,
}

fn cmd_baseline(paths: &[String], output: Option<&str>) {
    let cwd = std::env::current_dir().unwrap_or_default();
    let root_config = Config::load(&cwd);
    let files = analyze::filter_excluded(collect_files(paths), &root_config.exclude, &cwd);
    let findings = analyze::run_analysis(&files, &cwd, &[]);
    let baseline = cha_core::Baseline::from_findings(&findings, &cwd);
    let out = Path::new(output.unwrap_or(".cha/baseline.json"));
    match baseline.save(out) {
        Ok(()) => println!(
            "Baseline saved to {} ({} findings)",
            out.display(),
            baseline.fingerprints.len()
        ),
        Err(e) => eprintln!("Failed to save baseline: {e}"),
    }
}

fn cmd_parse(paths: &[String]) {
    let files = collect_files(paths);
    for path in &files {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("error reading {}: {}", path.display(), e);
                continue;
            }
        };
        let file = SourceFile::new(path.clone(), content);
        if let Some(model) = cha_parser::parse_file(&file) {
            print_model(&path.to_string_lossy(), &model);
        }
    }
}

fn print_model(path: &str, model: &cha_parser::SourceModel) {
    println!("=== {} ({}) ===", path, model.language);
    println!("  lines: {}", model.total_lines);
    println!("  functions: {}", model.functions.len());
    for f in &model.functions {
        println!(
            "    - {} (L{}-L{}, {} lines, complexity {})",
            f.name, f.start_line, f.end_line, f.line_count, f.complexity
        );
    }
    println!("  classes: {}", model.classes.len());
    for c in &model.classes {
        println!(
            "    - {} (L{}-L{}, {} methods, {} lines)",
            c.name, c.start_line, c.end_line, c.method_count, c.line_count
        );
    }
    println!("  imports: {}", model.imports.len());
    for i in &model.imports {
        println!("    - {} (L{})", i.source, i.line);
    }
}

fn cmd_init() {
    let path = Path::new(".cha.toml");
    if path.exists() {
        eprintln!(".cha.toml already exists");
        process::exit(1);
    }
    std::fs::write(path, include_str!("../../static/default.cha.toml"))
        .expect("failed to write .cha.toml");
    println!("Created .cha.toml");
}

fn cmd_fix(paths: &[String], diff: bool, dry_run: bool) {
    let files = analyze::resolve_files(paths, diff);
    if files.is_empty() {
        println!("No files to fix.");
        return;
    }
    let project_root = std::env::current_dir().unwrap_or_default();
    let filter = vec!["naming".to_string()];
    let findings = analyze::run_analysis(&files, &project_root, &filter);

    let fixable: Vec<&Finding> = findings
        .iter()
        .filter(|f| f.smell_name == "naming_convention")
        .collect();

    if fixable.is_empty() {
        println!("Nothing to fix.");
        return;
    }

    let fixed: usize = fixable.iter().filter_map(|f| apply_fix(f, dry_run)).count();
    let label = if dry_run {
        "would be applied"
    } else {
        "applied"
    };
    println!("{fixed} fix(es) {label}.");
}

/// Apply a single naming convention fix. Returns Some(()) if applied.
fn apply_fix(finding: &Finding, dry_run: bool) -> Option<()> {
    let name = finding.location.name.as_ref()?;
    let new_name = to_pascal_case(name);
    if new_name == *name {
        return None;
    }
    let path = &finding.location.path;
    let content = std::fs::read_to_string(path).ok()?;
    let replaced = content.replace(name.as_str(), &new_name);
    if replaced == content {
        return None;
    }
    if dry_run {
        println!("  {name}{new_name} in {}", path.display());
    } else {
        std::fs::write(path, &replaced).ok()?;
        println!("  Fixed: {name}{new_name} in {}", path.display());
    }
    Some(())
}

/// Convert a name to PascalCase by uppercasing the first character.
fn to_pascal_case(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().to_string() + chars.as_str(),
    }
}

fn plugin_candidates() -> Vec<clap_complete::CompletionCandidate> {
    let cwd = std::env::current_dir().unwrap_or_default();
    let config = Config::load(&cwd);
    let registry = PluginRegistry::from_config(&config, &cwd);
    let mut candidates: Vec<_> = registry
        .plugin_info()
        .into_iter()
        .map(|(name, desc)| {
            let c = clap_complete::CompletionCandidate::new(name);
            if desc.is_empty() {
                c
            } else {
                c.help(Some(desc.into()))
            }
        })
        .collect();
    for &(name, desc) in analyze::POST_ANALYSIS_PASSES {
        let c = clap_complete::CompletionCandidate::new(name);
        candidates.push(if desc.is_empty() {
            c
        } else {
            c.help(Some(desc.into()))
        });
    }
    candidates
}