linthis 0.19.6

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
// 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 configuration: create_hook_config, resolve_hook_override, and related helpers.

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

use super::metadata::save_installed_hook;
use super::script::{build_hook_command, build_thin_wrapper_script, hook_action};
use super::{find_git_root, is_command_available, write_hook_script};
use crate::cli::commands::{HookEvent, HookTool};

/// Format a `HookSource` as a TOML inline-table string, e.g. `{ plugin = "lt", file = "..." }`.
pub(crate) fn format_hook_source(source: &linthis::config::HookSource) -> String {
    use linthis::config::HookSource;
    match source {
        HookSource::Plugin { plugin, file } => {
            format!("{{ plugin = \"{}\", file = \"{}\" }}", plugin, file)
        }
        HookSource::File { file } => {
            format!("{{ file = \"{}\" }}", file)
        }
        HookSource::Url { url } => {
            format!("{{ url = \"{}\" }}", url)
        }
        HookSource::Git { git, git_ref, path } => {
            if let Some(r) = git_ref {
                format!(
                    "{{ git = \"{}\", ref = \"{}\", path = \"{}\" }}",
                    git, r, path
                )
            } else {
                format!("{{ git = \"{}\", path = \"{}\" }}", git, path)
            }
        }
        HookSource::Marketplace {
            marketplace,
            plugin,
            file,
        } => {
            format!(
                "{{ marketplace = \"{}\", plugin = \"{}\", file = \"{}\" }}",
                marketplace, plugin, file
            )
        }
    }
}

/// Describe where the hook behavior comes from (Tier 1/2/3) as a human-readable string.
///
/// - Tier 1 (fixed path): `"hooks/git-with-agent/pre-push (fixed path)"`
/// - Tier 2 (TOML entry): `"[hook.git-with-agent]\npre-push = { source = { ... } }"`
/// - Tier 3 (built-in):   `"built-in → linthis --hook-event=pre-push"`
pub(crate) fn describe_hook_source(tool: &HookTool, hook_event: &HookEvent) -> String {
    use linthis::config::Config;
    use linthis::hooks::resolver;

    let dir = match tool_type_dir(tool) {
        Some(d) => d,
        None => return "built-in (agent)".to_string(),
    };

    let project_root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));

    if resolver::fixed_git_hook_path(&project_root, dir, hook_event.hook_filename()).is_some() {
        return format!("hooks/{}/{} (fixed path)", dir, hook_event.hook_filename());
    }

    let config = Config::load_merged(&project_root);
    let event_key = hook_event.hook_filename();

    if let Some(entry) = lookup_hook_config_entry(&config.hook, tool, event_key) {
        let section = format!("[hook.{}]", dir);
        let source_str = format_hook_source(&entry.source);
        return format!("{}\n{} = {{ source = {} }}", section, event_key, source_str);
    }

    let cmd = build_hook_command(hook_event, &None);
    format!("built-in → {}", cmd)
}

/// Map a HookTool to its directory name for hook override lookups.
/// Returns None for Agent (handled separately).
pub(crate) fn tool_type_dir(tool: &HookTool) -> Option<&'static str> {
    match tool {
        HookTool::Git => Some("git"),
        HookTool::GitWithAgent => Some("git-with-agent"),
        HookTool::Prek => Some("prek"),
        HookTool::PrekWithAgent => Some("prek-with-agent"),
        HookTool::Agent => None,
    }
}

/// Look up the TOML hook config entry for a given tool and event key.
pub(crate) fn lookup_hook_config_entry<'a>(
    hook_cfg: &'a linthis::config::HookConfig,
    tool: &HookTool,
    event_key: &str,
) -> Option<&'a linthis::config::HookSourceEntry> {
    match tool {
        HookTool::Git => hook_cfg.git.get(event_key),
        HookTool::GitWithAgent => hook_cfg.git_with_agent.get(event_key),
        HookTool::Prek => hook_cfg.prek.get(event_key),
        HookTool::PrekWithAgent => hook_cfg.prek_with_agent.get(event_key),
        HookTool::Agent => None,
    }
}

/// Resolve hook script content from Tier-1 (fixed path) or Tier-2 (TOML config),
/// returning `Ok(Some(content))` if an override is found, `Ok(None)` to fall through
/// to the built-in generator, or `Err(ExitCode)` for a hard resolution error.
pub(crate) fn resolve_hook_override(
    tool: &HookTool,
    hook_event: &HookEvent,
) -> Result<Option<String>, ExitCode> {
    use linthis::config::Config;
    use linthis::hooks::resolver;

    let dir = match tool_type_dir(tool) {
        Some(d) => d,
        None => return Ok(None),
    };

    let project_root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));

    // Tier 1: fixed-path auto-discovery
    if let Some(fixed) =
        resolver::fixed_git_hook_path(&project_root, dir, hook_event.hook_filename())
    {
        match std::fs::read_to_string(fixed.as_path()) {
            Ok(content) => return Ok(Some(content)),
            Err(e) => {
                eprintln!(
                    "{}: Failed to read fixed-path override '{}': {}",
                    "Error".red(),
                    fixed.display(),
                    e
                );
                return Err(ExitCode::from(2));
            }
        }
    }

    // Tier 2: TOML source mapping
    let config = Config::load_merged(&project_root);
    let event_key = hook_event.hook_filename();
    if let Some(entry) = lookup_hook_config_entry(&config.hook, tool, event_key) {
        match resolver::resolve_to_string(&entry.source, &project_root, &config.hook.marketplaces) {
            Ok(content) => return Ok(Some(content)),
            Err(e) => {
                eprintln!(
                    "{}: Failed to resolve hook override for '{}/{}': {}",
                    "Error".red(),
                    dir,
                    event_key,
                    e
                );
                return Err(ExitCode::from(2));
            }
        }
    }

    Ok(None)
}

/// Create prek/pre-commit config file for a hook event.
fn create_prek_config(
    tool: &HookTool,
    hook_event: &HookEvent,
    force: bool,
    args: &Option<String>,
) -> Result<(), ExitCode> {
    let config_path = std::path::PathBuf::from(".pre-commit-config.yaml");
    let hook_filename = hook_event.hook_filename();

    if config_path.exists() && !force {
        eprintln!(
            "{}: {} already exists, skipping",
            "Warning".yellow(),
            config_path.display()
        );
        return Ok(());
    }

    if let Some(override_content) = resolve_hook_override(tool, hook_event)? {
        std::fs::write(&config_path, override_content).map_err(|e| {
            eprintln!(
                "{}: Failed to write '{}': {}",
                "Error".red(),
                config_path.display(),
                e
            );
            ExitCode::from(2)
        })?;
        println!(
            "{} Created {} [override]",
            "".green(),
            config_path.display()
        );
        return Ok(());
    }

    let hook_cmd = build_hook_command(hook_event, args);
    let stage = hook_event.hook_filename();
    let content = format!(
        "repos:\n  - repo: local\n    hooks:\n      - id: linthis-{}\n        name: linthis ({})\n        entry: {}\n        language: system\n        stages: [{}]\n        pass_filenames: false\n",
        hook_filename, hook_event.description(), hook_cmd, stage
    );

    std::fs::write(&config_path, content).map_err(|e| {
        eprintln!(
            "{}: Failed to create {}: {}",
            "Error".red(),
            config_path.display(),
            e
        );
        ExitCode::from(2)
    })?;

    let tool_name = "prek";
    println!(
        "{} Created {} ({}/pre-commit compatible)",
        "".green(),
        config_path.display(),
        tool_name
    );
    print_prek_next_steps(tool, hook_event, hook_filename);
    Ok(())
}

/// Print next steps after prek config creation (auto-install or manual instructions).
fn print_prek_next_steps(tool: &HookTool, hook_event: &HookEvent, hook_filename: &str) {
    let tool_name = "prek";
    if is_command_available(tool_name) {
        println!("\n{} Detected installed", tool_name.cyan());
        print!("{} Installing hooks... ", "".cyan());
        std::io::Write::flush(&mut std::io::stdout()).ok();
        match install_hooks(tool, hook_event) {
            Ok(_) => {
                println!("{}", "".green());
                println!(
                    "\n{} {} hooks are ready!",
                    "".green().bold(),
                    hook_filename
                );
                println!(
                    "  Hooks will run automatically on {}",
                    format!("git {}", hook_action(hook_event)).cyan()
                );
            }
            Err(e) => {
                println!("{}", "".red());
                eprintln!("{}: {}", "Warning".yellow(), e);
                println!(
                    "\nPlease run manually: {}",
                    format!("{} install --hook-type {}", tool_name, hook_filename).cyan()
                );
            }
        }
    } else {
        println!("\nNext steps:");
        if matches!(tool, HookTool::Prek) {
            let prek_cmd = linthis::python_tool_install_hint("prek").replace("Install: ", "");
            println!("  1. Install prek: {}", prek_cmd.cyan());
            println!(
                "  2. Set up hooks: {}",
                format!("prek install --hook-type {}", hook_filename).cyan()
            );
        } else {
            let precommit_cmd =
                linthis::python_tool_install_hint("pre-commit").replace("Install: ", "");
            println!("  1. Install pre-commit: {}", precommit_cmd.cyan());
            println!(
                "  2. Set up hooks: {}",
                format!("pre-commit install --hook-type {}", hook_filename).cyan()
            );
        }
    }
}

/// Install hooks using the specified tool
fn install_hooks(tool: &HookTool, hook_event: &HookEvent) -> Result<(), String> {
    use std::process::Command;

    let (cmd, tool_name) = match tool {
        HookTool::Prek => ("prek", "prek"),
        HookTool::Git | HookTool::Agent | HookTool::GitWithAgent | HookTool::PrekWithAgent => {
            return Ok(()); // handled separately
        }
    };

    let hook_type_arg = hook_event.hook_filename();

    let output = Command::new(cmd)
        .arg("install")
        .arg("--hook-type")
        .arg(hook_type_arg)
        .output()
        .map_err(|e| format!("Failed to execute {} install: {}", tool_name, e))?;

    if output.status.success() {
        Ok(())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(format!("{} install failed: {}", tool_name, stderr))
    }
}

/// Create a git hook file (thin wrapper or append to existing).
fn create_git_hook_config(
    tool: &HookTool,
    hook_event: &HookEvent,
    force: bool,
    args: &Option<String>,
) -> Result<(), ExitCode> {
    use std::fs;

    let hook_filename = hook_event.hook_filename();
    let git_root = match find_git_root() {
        Some(root) => root,
        None => {
            eprintln!(
                "{}: Not in a git repository, cannot create .git/hooks/{}",
                "Error".red(),
                hook_filename
            );
            return Err(ExitCode::from(1));
        }
    };

    let git_hooks_dir = git_root.join(".git/hooks");
    let hook_path = git_hooks_dir.join(hook_filename);

    if !git_hooks_dir.exists() {
        fs::create_dir_all(&git_hooks_dir).map_err(|e| {
            eprintln!(
                "{}: Failed to create hooks directory {}: {}",
                "Error".red(),
                git_hooks_dir.display(),
                e
            );
            ExitCode::from(2)
        })?;
    }

    // Tier-1/2 override check
    if let Some(override_content) = resolve_hook_override(tool, hook_event)? {
        return write_git_hook_override(&hook_path, &override_content, force);
    }

    let linthis_hook_line = build_hook_command(hook_event, args);

    if hook_path.exists() {
        return append_linthis_to_existing_hook(&hook_path, &linthis_hook_line);
    }

    // Create new hook file as thin wrapper
    let content = build_thin_wrapper_script(hook_event, &HookTool::Git, None, false, None);
    write_hook_script(&hook_path, &content)?;

    println!("{} Created {} [project]", "".green(), hook_path.display());
    println!(
        "  {} Thin wrapper: hook logic auto-updates with linthis",
        "".dimmed()
    );
    #[cfg(not(unix))]
    {
        println!("\nNext steps:");
        println!("  Make sure the hook is executable:");
        println!(
            "    {}",
            format!("chmod +x .git/hooks/{}", hook_filename).cyan()
        );
    }
    let project = git_root.to_str().unwrap_or("").to_string();
    save_installed_hook("local", &project, hook_event, &HookTool::Git, None, None);
    Ok(())
}

/// Write an override hook script, optionally appending to existing content.
fn write_git_hook_override(
    hook_path: &std::path::Path,
    override_content: &str,
    force: bool,
) -> Result<(), ExitCode> {
    let content = if hook_path.exists() && !force {
        let mut existing = std::fs::read_to_string(hook_path).unwrap_or_default();
        if !existing.ends_with('\n') {
            existing.push('\n');
        }
        existing.push_str("\n# linthis-hook (override)\n");
        existing.push_str(override_content);
        existing
    } else {
        override_content.to_string()
    };
    write_hook_script(hook_path, &content)?;
    println!(
        "{} Created {} [project, override]",
        "".green(),
        hook_path.display()
    );
    Ok(())
}

/// Append linthis to an existing hook file, or report if already present.
fn append_linthis_to_existing_hook(
    hook_path: &std::path::Path,
    linthis_hook_line: &str,
) -> Result<(), ExitCode> {
    let existing_content = std::fs::read_to_string(hook_path).map_err(|e| {
        eprintln!(
            "{}: Failed to read existing hook file: {}",
            "Error".red(),
            e
        );
        ExitCode::from(2)
    })?;

    if existing_content.contains(linthis_hook_line) || existing_content.contains("linthis hook run")
    {
        println!(
            "{}: linthis hook already exists in {}",
            "Info".cyan(),
            hook_path.display()
        );
        return Ok(());
    }

    let mut new_content = existing_content;
    if !new_content.ends_with('\n') {
        new_content.push('\n');
    }
    new_content.push_str("\n# linthis-hook\n");
    new_content.push_str(linthis_hook_line);
    new_content.push('\n');

    std::fs::write(hook_path, new_content).map_err(|e| {
        eprintln!(
            "{}: Failed to update {}: {}",
            "Error".red(),
            hook_path.display(),
            e
        );
        ExitCode::from(2)
    })?;
    println!(
        "{} Added linthis to existing {} {} [project]",
        "".green(),
        hook_path.display(),
        "(appended)".dimmed()
    );
    Ok(())
}

pub(crate) fn create_hook_config(
    tool: &HookTool,
    hook_event: &HookEvent,
    force: bool,
    args: &Option<String>,
) -> Result<(), ExitCode> {
    match tool {
        HookTool::Agent | HookTool::GitWithAgent | HookTool::PrekWithAgent => Ok(()),
        HookTool::Prek => create_prek_config(tool, hook_event, force, args),
        HookTool::Git => create_git_hook_config(tool, hook_event, force, args),
    }
}