linthis 0.23.0

A fast, cross-platform multi-language linter and formatter
Documentation
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
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! Hook status, list, and check commands.

use colored::Colorize;
use std::path::PathBuf;
use std::process::ExitCode;

use super::agent::{
    agent_is_installed, agent_skill_path, agent_stop_hook_settings_path, ALL_AGENT_PROVIDERS,
};
use super::metadata::{load_installed_hooks, InstalledHooksFile};
use super::{find_git_root, global_hooks_dir, is_linthis_hook_file};
use crate::cli::commands::HookEvent;

/// Print project-level hook status for each event. Returns true if any hook is installed.
fn print_project_hook_status(git_root: &std::path::Path, hook_events: &[HookEvent]) -> bool {
    let mut any_installed = false;
    println!("{}", "Project Hooks (.git/hooks/):".bold());
    for event in hook_events {
        let hook_path = git_root.join(".git/hooks").join(event.hook_filename());
        if hook_path.exists() {
            any_installed = true;
            println!("{} {} [project]", "".green(), hook_path.display());
            println!("    {}", event.description().dimmed());
            print_hook_content_analysis(&hook_path);
        } else {
            println!("{} {} (not installed)", "".red(), event.hook_filename());
        }
    }
    any_installed
}

/// Print analysis of detected tools in a hook file (linthis, prek, pre-commit, husky).
fn print_hook_content_analysis(hook_path: &std::path::Path) {
    if let Ok(content) = std::fs::read_to_string(hook_path) {
        let has_linthis = content.contains("linthis");
        let has_prek = content.contains("prek");
        let has_precommit = content.contains("pre-commit");
        let has_husky = content.contains("husky");

        if has_linthis {
            println!("    {} linthis", "".green());
        }
        if has_prek {
            println!("    {} prek", "".cyan());
        }
        if has_precommit {
            println!("    {} pre-commit", "".cyan());
        }
        if has_husky {
            println!("    {} husky", "".cyan());
        }
        if !has_linthis && !has_prek && !has_precommit && !has_husky {
            println!("    {} Custom hook", "".cyan());
        }
    }
}

/// Print global hook status section.
fn print_global_hook_status(hook_events: &[HookEvent]) {
    println!();
    println!("{}", "Global Hooks (~/.config/git/hooks/):".bold());
    let core_hooks_path = std::process::Command::new("git")
        .args(["config", "--global", "core.hooksPath"])
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
            } else {
                None
            }
        });

    if let Some(ref path_str) = core_hooks_path {
        println!("  {} = {}", "core.hooksPath".cyan(), path_str);
    } else {
        println!("  {} (core.hooksPath not set)", "".cyan());
    }

    let mut any_global_hook = false;
    if let Some(ref ghooks_dir) = global_hooks_dir() {
        for event in hook_events {
            let hook_path = ghooks_dir.join(event.hook_filename());
            if hook_path.exists() {
                any_global_hook = true;
                let has_linthis = is_linthis_hook_file(&hook_path);
                if has_linthis {
                    println!("{} {} [global]", "".green(), hook_path.display());
                    println!("    {} Strategy: local hook takes priority", "".dimmed());
                } else {
                    println!(
                        "{} {} [global, not by linthis]",
                        "".yellow(),
                        hook_path.display()
                    );
                }
            }
        }
    }
    if !any_global_hook {
        println!("  {} No global linthis hooks installed", "".cyan());
    }
}

/// Print agent integration status for a single scope. Returns true if any
/// agent is installed under that scope.
fn print_agent_status_for_scope(
    base: &std::path::Path,
    global: bool,
    skill_names: Option<&linthis::config::AgentSkillNamesConfig>,
) -> bool {
    let title = if global {
        "Agent Integration (Global skills)"
    } else {
        "Agent Integration (Project skills)"
    };
    println!("\n{}", title.bold());
    let events = [
        HookEvent::PreCommit,
        HookEvent::CommitMsg,
        HookEvent::PrePush,
    ];
    let mut any_installed = false;
    for p in ALL_AGENT_PROVIDERS {
        if agent_is_installed(base, p, global, skill_names) {
            any_installed = true;
            println!("{} {}", "".green(), p);
            for event in &events {
                let path = agent_skill_path(base, p, global, event, skill_names);
                if path.exists() {
                    println!(
                        "  {} {} ({})",
                        "".green().dimmed(),
                        path.display(),
                        event.hook_filename()
                    );
                }
            }
            if let Some(settings_path) = agent_stop_hook_settings_path(base, p) {
                let has_stop_hook = settings_path.exists()
                    && std::fs::read_to_string(&settings_path)
                        .map(|c| c.contains("linthis"))
                        .unwrap_or(false);
                if has_stop_hook {
                    println!(
                        "  {} Stop Hook ({})",
                        "".green().dimmed(),
                        settings_path.display()
                    );
                }
            }
        } else {
            println!("{} {} (not installed)", "".red(), p);
        }
    }
    any_installed
}

/// Show git hook status
pub(crate) fn handle_hook_status() -> ExitCode {
    let git_root = match find_git_root() {
        Some(root) => root,
        None => {
            eprintln!("{}: Not in a git repository", "Error".red());
            return ExitCode::from(1);
        }
    };

    let prek_config = std::path::Path::new(".pre-commit-config.yaml");

    println!("{}", "Git Hook Status".bold());
    println!("Repository: {}", git_root.display());
    println!();

    let hook_events = [
        HookEvent::PreCommit,
        HookEvent::PrePush,
        HookEvent::CommitMsg,
    ];

    let any_hook_installed = print_project_hook_status(&git_root, &hook_events);
    print_global_hook_status(&hook_events);

    // Check for prek/pre-commit config
    if prek_config.exists() {
        println!("\n{} {}", "".green(), prek_config.display());
        if let Ok(content) = std::fs::read_to_string(prek_config) {
            if content.contains("linthis") {
                println!("  {} Contains linthis configuration", "".green());
            } else {
                println!("  {} No linthis configuration found", "".yellow());
            }
        }
    }

    println!("\n{}", "Available hooks:".bold());
    println!("  {} - runs before each commit", "pre-commit".cyan());
    println!("  {} - runs before push to remote", "pre-push".cyan());
    println!(
        "  {} - validates commit message format",
        "commit-msg".cyan()
    );

    let skill_names_cfg = linthis::config::Config::load_merged(&git_root)
        .hook
        .agent
        .skill_names;
    let any_agent_project = print_agent_status_for_scope(&git_root, false, Some(&skill_names_cfg));
    let any_agent_global = match linthis::utils::home_dir() {
        Some(ref home) => print_agent_status_for_scope(home, true, Some(&skill_names_cfg)),
        None => {
            println!("\n{}", "Agent Integration (Global skills)".bold());
            println!(
                "  {} HOME / USERPROFILE not set — cannot check global skills",
                "".cyan()
            );
            false
        }
    };
    let any_agent_installed = any_agent_project || any_agent_global;

    println!("\n{}", "Commands:".bold());
    if !any_hook_installed {
        println!("  Install pre-commit:  {}", "linthis hook install".cyan());
        println!(
            "  Install pre-push:    {}",
            "linthis hook install --event pre-push".cyan()
        );
        println!(
            "  Install commit-msg:  {}",
            "linthis hook install --event commit-msg".cyan()
        );
    } else {
        println!(
            "  Install hook:   {}",
            "linthis hook install --event <event>".cyan()
        );
        println!(
            "  Uninstall hook: {}",
            "linthis hook uninstall --event <event>".cyan()
        );
        println!(
            "  Uninstall all:  {}",
            "linthis hook uninstall --all".cyan()
        );
    }
    if !any_agent_installed {
        println!(
            "  Install agent:  {}",
            "linthis hook install --type agent".cyan()
        );
    } else {
        println!(
            "  Install agent:  {}",
            "linthis hook install --type agent --provider <name>".cyan()
        );
        println!(
            "  Uninstall all:  {}",
            "linthis hook uninstall --all".cyan()
        );
    }

    ExitCode::SUCCESS
}

/// Detect the hook type (git, git-with-agent, prek, prek-with-agent) from script content.
///
/// Falls back to the TOML registry if content analysis is inconclusive.
fn detect_hook_type_from_content(
    content: &str,
    toml: &InstalledHooksFile,
    scope: &str,
    project: &std::path::Path,
    event: &HookEvent,
) -> String {
    // Content-based detection
    let has_agent = content.contains("_LINTHIS_AGENT_OK") || content.contains("agent");
    let has_prek = content.contains("prek");

    if has_prek && has_agent {
        return "prek-with-agent".to_string();
    }
    if has_prek {
        return "prek".to_string();
    }
    if has_agent
        && (content.contains("claude")
            || content.contains("codex")
            || content.contains("openclaw")
            || content.contains("gemini")
            || content.contains("codebuddy")
            || content.contains("droid")
            || content.contains("auggie")
            || content.contains("cursor-agent"))
    {
        return "git-with-agent".to_string();
    }

    // Fall back to TOML registry
    let project_str = project.to_string_lossy();
    let event_str = event.hook_filename();
    for hook in &toml.hooks {
        if hook.scope == scope
            && hook.event == event_str
            && (scope == "global" || hook.project == project_str.as_ref())
        {
            return hook.hook_type.clone();
        }
    }

    "git".to_string()
}

/// Detect the provider name from script content or TOML registry.
fn detect_provider_from_content(
    content: &str,
    toml: &InstalledHooksFile,
    scope: &str,
    project: &std::path::Path,
    event: &HookEvent,
) -> String {
    // Content-based detection
    let providers = [
        ("claude", "claude"),
        ("codex", "codex"),
        ("gemini", "gemini"),
        ("cursor-agent", "cursor"),
        ("droid", "droid"),
        ("auggie", "auggie"),
        ("codebuddy", "codebuddy"),
        ("openclaw", "openclaw"),
    ];
    for (pattern, name) in &providers {
        if content.contains(pattern)
            && (content.contains("_LINTHIS_AGENT_OK") || content.contains("agent"))
        {
            return name.to_string();
        }
    }

    // Fall back to TOML registry
    let project_str = project.to_string_lossy();
    let event_str = event.hook_filename();
    for hook in &toml.hooks {
        if hook.scope == scope
            && hook.event == event_str
            && (scope == "global" || hook.project == project_str.as_ref())
        {
            return hook.provider.clone();
        }
    }

    String::new()
}

/// List shell hooks in a given hooks directory. Returns the count of hooks found.
fn list_shell_hooks(
    hooks_dir: &std::path::Path,
    scope: &str,
    project: &std::path::Path,
    hook_events: &[HookEvent],
    toml: &InstalledHooksFile,
) -> usize {
    let mut count = 0;
    let mut any = false;
    for event in hook_events {
        let hook_path = hooks_dir.join(event.hook_filename());
        if !hook_path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&hook_path).unwrap_or_default();
        if !content.contains("linthis") {
            continue;
        }
        any = true;
        count += 1;

        let hook_type = detect_hook_type_from_content(&content, toml, scope, project, event);
        let provider = detect_provider_from_content(&content, toml, scope, project, event);

        println!(
            "  {} {} {} {}",
            "".green(),
            event.hook_filename(),
            format!("[{}]", hook_type).dimmed(),
            if provider.is_empty() {
                String::new()
            } else {
                format!("(provider: {})", provider)
            }
        );
    }
    if !any {
        println!("  {} No linthis shell hooks installed", "".dimmed());
    }
    count
}

/// List agent skills for a given base directory. Returns the count of skill entries found.
fn list_agent_skills(
    base: &std::path::Path,
    global: bool,
    hook_events: &[HookEvent],
    skill_names: Option<&linthis::config::AgentSkillNamesConfig>,
) -> usize {
    let mut count = 0;
    let mut any = false;
    for p in ALL_AGENT_PROVIDERS {
        if !agent_is_installed(base, p, global, skill_names) {
            continue;
        }
        any = true;
        let mut event_tags: Vec<&str> = Vec::new();
        for event in hook_events {
            let path = agent_skill_path(base, p, global, event, skill_names);
            if path.exists() {
                count += 1;
                event_tags.push(event.hook_filename());
            }
        }
        let stop_hook = agent_stop_hook_settings_path(base, p)
            .map(|sp| {
                sp.exists()
                    && std::fs::read_to_string(&sp)
                        .map(|c| c.contains("linthis"))
                        .unwrap_or(false)
            })
            .unwrap_or(false);
        println!(
            "  {} {} [{}]{}",
            "".green(),
            p,
            event_tags.join(", "),
            if stop_hook {
                format!(" + {}", "stop-hook".dimmed())
            } else {
                String::new()
            }
        );
    }
    if !any {
        let label = if global {
            "No global agent skills installed"
        } else {
            "No agent skills installed"
        };
        println!("  {} {}", "".dimmed(), label);
    }
    count
}

/// Print the summary footer for `hook list`.
fn print_list_footer(count: usize, global: bool) {
    println!();
    if count == 0 {
        if global {
            println!("No global hooks installed.");
            println!(
                "  Use {} to view project hooks.",
                "linthis hook list".cyan()
            );
        } else {
            println!("No project hooks installed.");
            println!(
                "  Use {} to view global hooks.",
                "linthis hook list -g".cyan()
            );
        }
    } else {
        let hint = if global {
            format!(" (use {} for project hooks)", "linthis hook list".cyan())
        } else {
            format!(" (use {} for global hooks)", "linthis hook list -g".cyan())
        };
        println!("{} {} hook entries found{}", "Total:".bold(), count, hint);
    }
}

/// List all installed linthis hooks.
pub(crate) fn handle_hook_list(global: bool) -> ExitCode {
    let toml = load_installed_hooks();

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let skill_names_cfg = linthis::config::Config::load_merged(&cwd)
        .hook
        .agent
        .skill_names;
    let skill_names = Some(&skill_names_cfg);

    let hook_events = [
        HookEvent::PreCommit,
        HookEvent::PrePush,
        HookEvent::CommitMsg,
    ];
    let scope_label = if global { "Global" } else { "Project" };

    println!("{}", format!("Installed Hooks ({})", scope_label).bold());
    println!();

    let mut count: usize = 0;

    if global {
        println!("{}", "Shell Hooks (~/.config/git/hooks/)".bold());
        if let Some(ref ghooks) = global_hooks_dir() {
            count += list_shell_hooks(ghooks, "global", &PathBuf::new(), &hook_events, &toml);
        } else {
            println!("  {} No global linthis shell hooks installed", "".dimmed());
        }

        println!();
        println!("{}", "Agent Skills (~/)".bold());
        if let Some(ref home_dir) = linthis::utils::home_dir() {
            count += list_agent_skills(home_dir, true, &hook_events, skill_names);
        }
    } else {
        let git_root = find_git_root();
        let project_root_display = git_root
            .as_ref()
            .map(|r| r.display().to_string())
            .unwrap_or_else(|| "(not in a git repository)".to_string());

        println!("{}", "Shell Hooks (.git/hooks/)".bold());
        if let Some(ref root) = git_root {
            count += list_shell_hooks(&root.join(".git/hooks"), "local", root, &hook_events, &toml);
        } else {
            println!("  {} {}", "".dimmed(), project_root_display);
        }

        println!();
        println!("{}", "Agent Skills".bold());
        if let Some(ref root) = git_root {
            count += list_agent_skills(root, false, &hook_events, skill_names);
        } else {
            println!("  {} {}", "".dimmed(), project_root_display);
        }
    }

    print_list_footer(count, global);
    ExitCode::SUCCESS
}

/// Check hook file for multiple tool conflicts. Returns (has_conflicts, warnings).
fn check_hook_tool_conflicts(hook_path: &std::path::Path) -> (bool, Vec<&'static str>) {
    let mut warnings = Vec::new();
    if !hook_path.exists() {
        return (false, warnings);
    }
    if let Ok(content) = std::fs::read_to_string(hook_path) {
        let tools = [
            content.contains("prek"),
            content.contains("pre-commit"),
            content.contains("husky"),
            content.contains("linthis"),
        ];
        let tool_count = tools.iter().filter(|&&x| x).count();
        if tool_count > 1 {
            println!(
                "{} Multiple hook tools detected in {}",
                "".yellow(),
                hook_path.display()
            );
            if content.contains("linthis") {
                println!("  {} linthis", "".green());
            }
            if content.contains("prek") {
                println!("  {} prek", "".yellow());
            }
            if content.contains("pre-commit") {
                println!("  {} pre-commit", "".yellow());
            }
            if content.contains("husky") {
                println!("  {} husky", "".yellow());
            }
            warnings.push("Consider using only one hook management tool");
            return (true, warnings);
        }
    }
    (false, warnings)
}

/// Check for hook conflicts
pub(crate) fn handle_hook_check() -> ExitCode {
    let git_root = match find_git_root() {
        Some(root) => root,
        None => {
            eprintln!("{}: Not in a git repository", "Error".red());
            return ExitCode::from(1);
        }
    };

    let hook_path = git_root.join(".git/hooks/pre-commit");
    let prek_config = std::path::Path::new(".pre-commit-config.yaml");
    let husky_dir = std::path::Path::new(".husky");

    println!("{}", "Checking for hook conflicts...".bold());
    println!();

    let (mut has_conflicts, mut warnings) = check_hook_tool_conflicts(&hook_path);

    if prek_config.exists() {
        if let Ok(content) = std::fs::read_to_string(prek_config) {
            if content.contains("linthis") && !hook_path.exists() {
                has_conflicts = true;
                println!(
                    "{} {} exists but no hook installed",
                    "".yellow(),
                    prek_config.display()
                );
                warnings.push("Run 'prek install' or 'pre-commit install' to activate hooks");
            }
        }
    }

    if husky_dir.exists() && husky_dir.join("pre-commit").exists() {
        println!(
            "{} Husky detected: {}",
            "".cyan(),
            husky_dir.join("pre-commit").display()
        );
        warnings.push("Husky manages its own hooks in .husky/ directory");
        warnings.push("To use linthis with husky, add linthis command to .husky/pre-commit");
    }

    println!();
    if has_conflicts {
        println!("{}", "Conflicts detected:".yellow().bold());
        for warning in warnings {
            println!("{}", warning);
        }
        println!();
        println!("{}", "Recommendations:".bold());
        println!(
            "  • Use {} to see current hook setup",
            "linthis hook status".cyan()
        );
        println!("  • Choose one hook tool and stick with it");
        println!("  • For teams, document hook setup in README");
    } else {
        println!("{} No conflicts detected", "".green().bold());
    }

    ExitCode::SUCCESS
}