plzplz 0.0.19

A simple cross-platform task runner with helpful defaults
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
use crate::config::{self, PlzConfig};
use crate::settings;
use anyhow::{Result, bail};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use toml_edit::DocumentMut;

const MANAGED_MARKER: &str = "# plz:managed - do not edit";
const HOOKS_VERSION: u32 = 3;

pub fn find_git_hooks_dir(base_dir: &Path) -> Result<PathBuf> {
    let mut dir = base_dir;
    loop {
        let git_dir = dir.join(".git");
        if git_dir.is_dir() {
            return Ok(git_dir.join("hooks"));
        }
        match dir.parent() {
            Some(parent) => dir = parent,
            None => bail!("Not a git repository (no .git directory found)"),
        }
    }
}

/// Group tasks by their git_hook stage. Returns sorted map for deterministic output.
/// Group tasks are stored as "group:task" format.
pub fn tasks_by_stage(config: &PlzConfig) -> BTreeMap<String, Vec<String>> {
    let mut stages: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut task_names: Vec<&String> = config.tasks.keys().collect();
    task_names.sort();
    for name in task_names {
        let task = &config.tasks[name];
        if let Some(ref hook) = task.git_hook {
            stages.entry(hook.clone()).or_default().push(name.clone());
        }
    }
    if let Some(ref groups) = config.taskgroup {
        let mut group_names: Vec<&String> = groups.keys().collect();
        group_names.sort();
        for gname in group_names {
            let group = &groups[gname];
            let mut gtask_names: Vec<&String> = group.tasks.keys().collect();
            gtask_names.sort();
            for tname in gtask_names {
                if let Some(ref hook) = group.tasks[tname].git_hook {
                    stages
                        .entry(hook.clone())
                        .or_default()
                        .push(format!("{gname}:{tname}"));
                }
            }
        }
    }
    stages
}

fn generate_hook_script(stage: &str) -> String {
    format!(
        "#!/bin/sh\n\
         {MANAGED_MARKER}\n\
         # plz:hooks_version={HOOKS_VERSION}\n\
         [ \"${{PLZ_SKIP_HOOKS}}\" = \"1\" ] && exit 0\n\
         command -v plz >/dev/null 2>&1 || {{ echo \"plz not found in PATH, skipping {stage} hook\" >&2; exit 0; }}\n\
         if [ ! -f plz.toml ] && [ ! -f .plz.toml ]; then\n\
           echo \"plz: no plz.toml found, skipping {stage} hook\" >&2\n\
           echo \"plz: to remove this hook, delete .git/hooks/{stage}\" >&2\n\
           exit 0\n\
         fi\n\
         plz --no-interactive hooks run {stage}\n"
    )
}

fn installed_hook_version(path: &Path) -> Option<u32> {
    let content = fs::read_to_string(path).ok()?;
    for line in content.lines() {
        if let Some(v) = line.strip_prefix("# plz:hooks_version=") {
            return v.trim().parse().ok();
        }
    }
    // Managed hook without a version tag is v1
    if content.contains(MANAGED_MARKER) {
        return Some(1);
    }
    None
}

fn is_plz_managed(path: &Path) -> bool {
    fs::read_to_string(path)
        .map(|content| content.contains(MANAGED_MARKER))
        .unwrap_or(false)
}

pub fn install(config: &PlzConfig, base_dir: &Path, force: bool, interactive: bool) -> Result<()> {
    let stages = tasks_by_stage(config);
    if stages.is_empty() {
        eprintln!("No tasks have git_hook configured in plz.toml");
        return Ok(());
    }

    let hooks_dir = find_git_hooks_dir(base_dir)?;
    fs::create_dir_all(&hooks_dir)?;

    for (stage, task_names) in &stages {
        let hook_path = hooks_dir.join(stage);

        if hook_path.exists() && !is_plz_managed(&hook_path) {
            if force {
                eprintln!("\x1b[33mOverwriting\x1b[0m existing {stage} hook");
            } else if interactive {
                let should_overwrite: bool = cliclack::confirm(format!(
                    "{stage} hook exists and is not plz-managed. Overwrite it?"
                ))
                .initial_value(false)
                .interact()?;
                if !should_overwrite {
                    eprintln!("\x1b[2mSkipping {stage}\x1b[0m");
                    continue;
                }
                eprintln!("\x1b[33mOverwriting\x1b[0m existing {stage} hook");
            } else {
                eprintln!(
                    "\x1b[33mWarning:\x1b[0m Skipping {stage} — existing hook is not plz-managed (use `plz hooks install --force` to overwrite)"
                );
                continue;
            }
        }

        let script = generate_hook_script(stage);
        fs::write(&hook_path, &script)?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&hook_path, fs::Permissions::from_mode(0o755))?;
        }

        let names = task_names.join(", ");
        eprintln!("\x1b[32m✓\x1b[0m Installed {stage} hook (tasks: {names})");
    }

    Ok(())
}

pub fn uninstall(config: &PlzConfig, base_dir: &Path) -> Result<()> {
    let stages = tasks_by_stage(config);
    if stages.is_empty() {
        eprintln!("No tasks have git_hook configured in plz.toml");
        return Ok(());
    }

    let hooks_dir = find_git_hooks_dir(base_dir)?;

    for stage in stages.keys() {
        let hook_path = hooks_dir.join(stage);
        if !hook_path.exists() {
            continue;
        }
        if !is_plz_managed(&hook_path) {
            eprintln!("\x1b[33mWarning:\x1b[0m Skipping {stage} — not plz-managed");
            continue;
        }
        fs::remove_file(&hook_path)?;
        eprintln!("\x1b[32m✓\x1b[0m Removed {stage} hook");
    }

    Ok(())
}

/// Run all tasks for a given git hook stage (called by the hook script itself).
pub fn run_stage(
    config: &PlzConfig,
    stage: &str,
    base_dir: &Path,
    interactive: bool,
) -> Result<()> {
    let stages = tasks_by_stage(config);
    let task_names = match stages.get(stage) {
        Some(names) => names,
        None => return Ok(()),
    };

    let names = task_names.join(", ");
    eprintln!("\x1b[36m🙏 Running {stage} hook ({names})\x1b[0m");

    for name in task_names {
        if let Some((group, task)) = name.split_once(':') {
            crate::runner::run_group_task(config, group, task, base_dir, interactive)?;
        } else {
            crate::runner::run_task(config, name, base_dir, interactive)?;
        }
    }
    eprintln!("\x1b[32m✓ {stage} hook passed\x1b[0m");
    Ok(())
}

pub fn status(config: &PlzConfig, base_dir: &Path) -> Result<()> {
    let stages = tasks_by_stage(config);
    if stages.is_empty() {
        eprintln!("No tasks have git_hook configured in plz.toml");
        return Ok(());
    }

    let hooks_dir = find_git_hooks_dir(base_dir).ok();

    for (stage, task_names) in &stages {
        let names = task_names.join(", ");
        let (status_icon, suffix) = match hooks_dir.as_ref() {
            Some(d) => {
                let p = d.join(stage);
                if !p.exists() || !is_plz_managed(&p) {
                    ("\x1b[2m·\x1b[0m", "")
                } else if installed_hook_version(&p).unwrap_or(0) < HOOKS_VERSION {
                    ("\x1b[33m↑\x1b[0m", " \x1b[33m(outdated)\x1b[0m")
                } else {
                    ("\x1b[32m✓\x1b[0m", "")
                }
            }
            None => ("\x1b[2m·\x1b[0m", ""),
        };
        eprintln!("{status_icon} {stage}: {names}{suffix}");
    }

    Ok(())
}

fn hook_needs_install(path: &Path) -> bool {
    if !path.exists() || !is_plz_managed(path) {
        return true;
    }
    installed_hook_version(path).unwrap_or(0) < HOOKS_VERSION
}

fn has_uninstalled_hooks(config: &PlzConfig, base_dir: &Path) -> bool {
    let stages = tasks_by_stage(config);
    if stages.is_empty() {
        return false;
    }
    let Ok(hooks_dir) = find_git_hooks_dir(base_dir) else {
        return false;
    };
    stages
        .keys()
        .any(|stage| hook_needs_install(&hooks_dir.join(stage)))
}

/// Show a grey tip if hooks are configured but not installed.
/// If ~/.plz doesn't exist yet, suggest running `plz plz` first.
pub fn hint_uninstalled_hooks(config: &PlzConfig, base_dir: &Path) {
    if std::env::var_os("PLZ_COMMAND").is_some() {
        return;
    }
    if !settings::config_dir_exists() {
        eprintln!("\x1b[2mRun `plz plz` to set up custom settings and templates.\x1b[0m");
        return;
    }
    if !settings::load().show_hints {
        return;
    }
    if has_uninstalled_hooks(config, base_dir) {
        eprintln!(
            "\x1b[2mYour plz.toml has git hooks that need to be installed or updated. Run `plz hooks` to install them.\x1b[0m"
        );
    }
}

/// Returns true if no tasks have git_hook configured.
pub fn has_no_hooks(config: &PlzConfig) -> bool {
    tasks_by_stage(config).is_empty()
}

/// Interactive hook install prompt (for `plz hooks` with no subcommand).
/// Shows status, then offers yes/no install.
pub fn interactive_install(config: &PlzConfig, base_dir: &Path, interactive: bool) -> Result<()> {
    status(config, base_dir)?;

    if !has_uninstalled_hooks(config, base_dir) {
        return Ok(());
    }

    if !interactive {
        return Ok(());
    }

    let should_install: bool = cliclack::confirm("Install hooks?")
        .initial_value(true)
        .interact()?;

    if should_install {
        install(config, base_dir, false, interactive)?;
    }

    Ok(())
}

/// Interactive flow: pick tasks, pick a stage, write git_hook into plz.toml.
pub fn add_hook(config: &PlzConfig, config_path: &Path) -> Result<()> {
    // Collect tasks without a git_hook: (label, is_group_task)
    let mut candidates: Vec<String> = Vec::new();
    let mut task_names: Vec<&String> = config.tasks.keys().collect();
    task_names.sort();
    for name in task_names {
        if config.tasks[name].git_hook.is_none() {
            candidates.push(name.clone());
        }
    }
    if let Some(ref groups) = config.taskgroup {
        let mut group_names: Vec<&String> = groups.keys().collect();
        group_names.sort();
        for gname in group_names {
            let group = &groups[gname];
            let mut gtask_names: Vec<&String> = group.tasks.keys().collect();
            gtask_names.sort();
            for tname in gtask_names {
                if group.tasks[tname].git_hook.is_none() {
                    candidates.push(format!("{gname}:{tname}"));
                }
            }
        }
    }

    if candidates.is_empty() {
        eprintln!("All tasks already have a git_hook configured.");
        return Ok(());
    }

    let mut ms_items: Vec<crate::utils::MultiSelectItem> = candidates
        .iter()
        .map(|name| crate::utils::MultiSelectItem {
            label: name.clone(),
            hint: String::new(),
            selected: false,
        })
        .collect();

    let selected: Vec<&str> = match crate::utils::multiselect(
        "Which tasks should run as a git hook?",
        &mut ms_items,
        true,
    )? {
        Some(indices) => indices.iter().map(|&i| candidates[i].as_str()).collect(),
        None => {
            eprintln!("\x1b[2m✕  Cancelled\x1b[0m");
            return Ok(());
        }
    };

    if selected.is_empty() {
        eprintln!("\x1b[2m✕  Cancelled\x1b[0m");
        return Ok(());
    }

    // Pick a stage
    let common_stages = &[
        "pre-commit",
        "commit-msg",
        "pre-push",
        "prepare-commit-msg",
        "post-commit",
        "post-merge",
        "post-checkout",
        "pre-rebase",
    ];
    let stage_items: Vec<(&str, &str, &str)> = common_stages.iter().map(|s| (*s, *s, "")).collect();

    let stage: &str = cliclack::select("Which git hook stage?")
        .items(&stage_items)
        .initial_value("pre-commit")
        .interact()?;

    // Read and edit the TOML document in-place
    let content = fs::read_to_string(config_path)?;
    let mut doc: DocumentMut = content.parse()?;

    for name in &selected {
        if let Some((group, task)) = name.split_once(':') {
            // Group task: [taskgroup.GROUP.TASK]
            if let Some(taskgroup) = doc.get_mut("taskgroup")
                && let Some(group_table) = taskgroup.get_mut(group)
                && let Some(task_table) = group_table.get_mut(task)
                && let Some(t) = task_table.as_table_like_mut()
            {
                t.insert("git_hook", toml_edit::value(stage));
            }
        } else {
            // Top-level task: [tasks.NAME]
            if let Some(tasks) = doc.get_mut("tasks")
                && let Some(task_table) = tasks.get_mut(*name)
                && let Some(t) = task_table.as_table_like_mut()
            {
                t.insert("git_hook", toml_edit::value(stage));
            }
        }
    }

    fs::write(config_path, doc.to_string())?;

    for name in &selected {
        eprintln!("\x1b[32m✓\x1b[0m Added {stage} hook to \x1b[1m{name}\x1b[0m");
    }

    // Offer to install hooks
    let base_dir = config_path.parent().unwrap().to_path_buf();
    let updated_config = config::load(config_path)?;
    if has_uninstalled_hooks(&updated_config, &base_dir) {
        let should_install: bool = cliclack::confirm("Install hooks now?")
            .initial_value(true)
            .interact()?;
        if should_install {
            install(&updated_config, &base_dir, false, true)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_hook_script() {
        let script = generate_hook_script("pre-commit");
        assert!(script.starts_with("#!/bin/sh\n"));
        assert!(script.contains(MANAGED_MARKER));
        assert!(script.contains(&format!("# plz:hooks_version={HOOKS_VERSION}")));
        assert!(script.contains("plz --no-interactive hooks run pre-commit"));
        assert!(script.contains("PLZ_SKIP_HOOKS"));
        assert!(script.contains("command -v plz"));
        assert!(script.contains("no plz.toml found"));
        assert!(script.contains("delete .git/hooks/pre-commit"));
    }

    #[test]
    fn test_generate_hook_script_commit_msg() {
        let script = generate_hook_script("commit-msg");
        assert!(script.contains("plz --no-interactive hooks run commit-msg"));
    }

    #[test]
    fn test_installed_hook_version_current() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("pre-commit");
        fs::write(&path, generate_hook_script("pre-commit")).unwrap();
        assert_eq!(installed_hook_version(&path), Some(HOOKS_VERSION));
    }

    #[test]
    fn test_installed_hook_version_v1() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("pre-commit");
        fs::write(
            &path,
            format!("#!/bin/sh\n{MANAGED_MARKER}\nplz hooks run pre-commit \"$@\"\n"),
        )
        .unwrap();
        assert_eq!(installed_hook_version(&path), Some(1));
    }

    #[test]
    fn test_installed_hook_version_not_managed() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("pre-commit");
        fs::write(&path, "#!/bin/sh\necho custom\n").unwrap();
        assert_eq!(installed_hook_version(&path), None);
    }

    #[test]
    fn test_installed_hook_version_missing() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("nonexistent");
        assert_eq!(installed_hook_version(&path), None);
    }

    #[test]
    fn test_is_plz_managed_true() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("pre-commit");
        fs::write(
            &path,
            format!("#!/bin/sh\n{MANAGED_MARKER}\nplz hooks run pre-commit\n"),
        )
        .unwrap();
        assert!(is_plz_managed(&path));
    }

    #[test]
    fn test_is_plz_managed_false() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("pre-commit");
        fs::write(&path, "#!/bin/sh\necho custom hook\n").unwrap();
        assert!(!is_plz_managed(&path));
    }

    #[test]
    fn test_is_plz_managed_missing() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("nonexistent");
        assert!(!is_plz_managed(&path));
    }
}