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
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
use crate::config;
use crate::hooks;
use crate::settings;
use crate::templates::{self, Snippet, TemplateMeta};
use anyhow::{Result, bail};
use std::env;
use std::fmt::Write as _;
use std::io::IsTerminal;
use std::path::PathBuf;
use toml_edit::DocumentMut;

const PREAMBLE: &str = "\
# Run tasks with: plz [taskname]
# Docs: https://plzplz.org/reference.html
# Show the schema for this file: plz plz schema
";

fn config_dir() -> Option<PathBuf> {
    settings::config_dir()
}

pub fn extract_tasks(doc: &DocumentMut) -> Vec<(String, Option<String>)> {
    let Some(tasks_table) = doc.get("tasks").and_then(|t| t.as_table()) else {
        return Vec::new();
    };
    tasks_table
        .iter()
        .map(|(key, item)| {
            let desc = item
                .as_table()
                .and_then(|t| t.decor().prefix())
                .and_then(|p| p.as_str())
                .and_then(config::extract_comment);
            (key.to_string(), desc)
        })
        .collect()
}

pub fn parse_default(toml: &str) -> Option<(DocumentMut, Vec<(String, Option<String>)>)> {
    let doc: DocumentMut = toml.parse().ok()?;
    doc.get("tasks").and_then(|t| t.as_table())?;
    let tasks = extract_tasks(&doc);
    Some((doc, tasks))
}

#[allow(dead_code)]
pub fn add_suffix_to_toml(
    toml: &str,
    suffix: &str,
    task_names: &[(String, Option<String>)],
) -> String {
    let mut result = toml.to_string();
    for (name, _) in task_names {
        result = result.replace(
            &format!("[tasks.{name}]"),
            &format!("[tasks.{name}-{suffix}]"),
        );
        result = result.replace(
            &format!("\"plz:{name}\""),
            &format!("\"plz:{name}-{suffix}\""),
        );
        result = result.replace(
            &format!("\"plz {name}\""),
            &format!("\"plz {name}-{suffix}\""),
        );
    }
    result
}

pub fn convert_to_taskgroup(
    content: &str,
    group_name: &str,
    task_names: &[(String, Option<String>)],
    template_env: &str,
) -> String {
    let mut result = content.to_string();

    // Replace [tasks.X] with [taskgroup.GROUP.X]
    for (name, _) in task_names {
        result = result.replace(
            &format!("[tasks.{name}]"),
            &format!("[taskgroup.{group_name}.{name}]"),
        );
    }

    // Update plz references: plz:task โ†’ plz:group:task, plz task โ†’ plz group task
    for (name, _) in task_names {
        result = result.replace(
            &format!("\"plz:{name}\""),
            &format!("\"plz:{group_name}:{name}\""),
        );
        result = result.replace(
            &format!("\"plz {name}\""),
            &format!("\"plz {group_name} {name}\""),
        );
    }

    // Extract common env into [taskgroup.GROUP.extends] if tasks use a shared env
    let env_line = format!("env = \"{template_env}\"");
    if result.lines().any(|l| l.trim() == env_line) {
        // Remove per-task env lines that match the template env
        let lines: Vec<&str> = result.lines().collect();
        let filtered: Vec<&str> = lines.into_iter().filter(|l| l.trim() != env_line).collect();
        result = filtered.join("\n");

        // Prepend extends section
        result = format!(
            "[taskgroup.{group_name}.extends]\n{env_line}\n\n{}",
            result.trim_start()
        );
    }

    result
}

pub fn run() -> Result<()> {
    let cwd = env::current_dir()?;
    let config_path = cwd.join("plz.toml");

    if config_path.exists() {
        // If plz.toml already exists, check for git hooks to install
        let in_git_repo = hooks::find_git_hooks_dir(&cwd).is_ok();
        let content = std::fs::read_to_string(&config_path)?;
        let has_git_hooks = content.contains("git_hook");

        if in_git_repo && has_git_hooks {
            cliclack::intro("plz init")?;
            let install_hooks: bool = cliclack::confirm("Install git hooks?")
                .initial_value(true)
                .interact()?;
            if install_hooks {
                if let Ok(ref cfg) = config::load(&config_path) {
                    hooks::install(cfg, &cwd, false, true)?;
                    cliclack::outro("Installed git hooks")?;
                }
            } else {
                cliclack::outro("Skipped git hook installation")?;
            }
        } else {
            cliclack::log::info(
                "plz.toml already exists. Run \x1b[1mplz\x1b[0m to see all commands.",
            )?;
        }
        return Ok(());
    }

    let cfg_dir = config_dir();
    let interactive = std::io::stdin().is_terminal() && !is_ci::cached();

    // Load environments and detect which ones match
    let environments = templates::load_environments();
    let detected = templates::detect_environments(&cwd, &environments);

    // Determine which envs are "alternatives" (detected but superseded)
    let alternative_envs: Vec<String> = detected
        .iter()
        .flat_map(|d| environments[d].alternative_to.clone())
        .collect();

    // Load all templates
    let all_templates = templates::load_templates(cfg_dir.as_deref());

    if !interactive {
        let output = format!("{PREAMBLE}\n[tasks.hello]\nrun = \"echo 'hello world'\"");
        std::fs::write(&config_path, output)?;
        eprintln!("Created plz.toml with a starter task");
        return Ok(());
    }

    cliclack::intro("plz init")?;

    if !detected.is_empty() {
        cliclack::log::info(format!("Detected: {}", detected.join(", ")))?;
    }

    // Sort templates: detected envs first (user templates before embedded), then alternatives, then others
    let mut sorted_templates: Vec<&TemplateMeta> = Vec::new();
    let env_detected = |t: &TemplateMeta| t.env.as_ref().is_some_and(|e| detected.contains(e));
    let env_alternative =
        |t: &TemplateMeta| t.env.as_ref().is_some_and(|e| alternative_envs.contains(e));
    // Detected first โ€” user templates before embedded for the same env
    for t in &all_templates {
        if env_detected(t) && t.is_user {
            sorted_templates.push(t);
        }
    }
    for t in &all_templates {
        if env_detected(t) && !t.is_user {
            sorted_templates.push(t);
        }
    }
    // Alternatives (detected but superseded)
    for t in &all_templates {
        if env_alternative(t) && !env_detected(t) {
            sorted_templates.push(t);
        }
    }
    // Everything else
    for t in &all_templates {
        if !env_detected(t) && !env_alternative(t) {
            sorted_templates.push(t);
        }
    }

    if sorted_templates.is_empty() {
        let output = format!("{PREAMBLE}\n[tasks.hello]\nrun = \"echo 'hello world'\"");
        std::fs::write(&config_path, output)?;
        cliclack::outro("Created plz.toml with a starter task")?;
        return Ok(());
    }

    // Build multiselect items
    let max_name_len = sorted_templates
        .iter()
        .map(|t| t.name.len())
        .max()
        .unwrap_or(0);

    // Pre-select: prefer detected env template, else fall back to env-agnostic templates
    let initial: Vec<&str> = sorted_templates
        .iter()
        .find(|t| env_detected(t) && !env_alternative(t))
        .or_else(|| sorted_templates.iter().find(|t| t.env.is_none()))
        .map(|t| vec![t.name.as_str()])
        .unwrap_or_default();

    let mut ms_items: Vec<crate::utils::MultiSelectItem> = sorted_templates
        .iter()
        .map(|t| {
            let padding = " ".repeat(max_name_len - t.name.len() + 2);
            crate::utils::MultiSelectItem {
                label: format!("{}{padding}{}", t.name, t.description),
                hint: String::new(),
                selected: initial.contains(&t.name.as_str()),
            }
        })
        .collect();

    let selected: Vec<&str> =
        match crate::utils::multiselect("Which templates?", &mut ms_items, false)? {
            Some(indices) => indices
                .iter()
                .map(|&i| sorted_templates[i].name.as_str())
                .collect(),
            None => {
                print_templates_hint(&cfg_dir);
                return Ok(());
            }
        };

    let selected = if selected.is_empty() {
        vec!["general"]
    } else {
        selected
    };

    // Build output from selected templates
    let mut output = String::new();
    let use_taskgroups = selected.len() > 1;

    for template_name in &selected {
        let template = sorted_templates
            .iter()
            .find(|t| t.name.as_str() == *template_name)
            .unwrap();

        let content = templates::strip_template_section(&template.content);

        if use_taskgroups {
            if let Some((_, tasks)) = parse_default(&content) {
                let grouped = convert_to_taskgroup(
                    &content,
                    template_name,
                    &tasks,
                    template.env.as_deref().unwrap_or(""),
                );
                write!(output, "{}", grouped.trim())?;
            } else {
                write!(output, "{}", content.trim())?;
            }
        } else {
            write!(output, "{}", content.trim())?;
        }
        writeln!(output)?;
        writeln!(output)?;
    }

    if output.is_empty() {
        cliclack::outro("No tasks selected, skipping plz.toml creation")?;
        return Ok(());
    }

    output.insert_str(0, &format!("{PREAMBLE}\n"));

    // Check if any selected template has git_hook tasks
    let in_git_repo = hooks::find_git_hooks_dir(&cwd).is_ok();
    let has_git_hooks = output.contains("git_hook");

    if in_git_repo && has_git_hooks {
        let install_hooks: bool = cliclack::confirm("Install git hooks?")
            .initial_value(true)
            .interact()?;

        std::fs::write(&config_path, output.trim_end())?;

        if install_hooks && let Ok(ref cfg) = config::load(&config_path) {
            hooks::install(cfg, &cwd, false, true)?;
        }
    } else {
        std::fs::write(&config_path, output.trim_end())?;
    }

    cliclack::outro("Created plz.toml".to_string())?;
    print_templates_hint(&cfg_dir);

    Ok(())
}

fn print_templates_hint(cfg_dir: &Option<PathBuf>) {
    if !settings::config_dir_exists() {
        eprintln!("\x1b[2mRun `plz plz` to set up custom settings and templates.\x1b[0m");
    } else if let Some(dir) = cfg_dir {
        eprintln!(
            "\x1b[2mAdd templates to {} to customize\x1b[0m",
            dir.join("templates").display()
        );
    }
}

fn pick_snippet(
    all_snippets: &[(String, Vec<Snippet>)],
    detected_envs: &[String],
    footer_hint: &str,
) -> Result<Option<Snippet>> {
    use crate::utils::{PickItem, pick_from_list};

    // Build flat list: detected env snippets first, then general, then others
    let mut items: Vec<(PickItem, Snippet)> = Vec::new();

    // Detected env snippets first
    for (env_name, snippets) in all_snippets {
        if detected_envs.contains(env_name) {
            for s in snippets {
                items.push((
                    PickItem {
                        label: s.name.clone(),
                        description: s.description.clone(),
                        preview: Some(s.content.trim().to_string()),
                    },
                    s.clone(),
                ));
            }
        }
    }

    // General snippets
    for (env_name, snippets) in all_snippets {
        if env_name == "general" && !detected_envs.contains(env_name) {
            for s in snippets {
                items.push((
                    PickItem {
                        label: s.name.clone(),
                        description: s.description.clone(),
                        preview: Some(s.content.trim().to_string()),
                    },
                    s.clone(),
                ));
            }
        }
    }

    // Other env snippets
    for (env_name, snippets) in all_snippets {
        if !detected_envs.contains(env_name) && env_name != "general" {
            for s in snippets {
                items.push((
                    PickItem {
                        label: format!("{} ({})", s.name, env_name),
                        description: s.description.clone(),
                        preview: Some(s.content.trim().to_string()),
                    },
                    s.clone(),
                ));
            }
        }
    }

    let pick_items: Vec<PickItem> = items.iter().map(|(pi, _)| pi.clone()).collect();
    match pick_from_list(&pick_items, footer_hint)? {
        Some(idx) => Ok(Some(items[idx].1.clone())),
        None => Ok(None),
    }
}

const CHEATSHEET: &str = include_str!("cheatsheet.txt");

pub fn print_cheatsheet() -> Result<()> {
    let bold = "\x1b[1m";
    let dim = "\x1b[2m";
    let cyan = "\x1b[36m";
    let reset = "\x1b[0m";

    let mut out = String::new();
    out.push_str(&format!("{bold}plz.toml cheatsheet{reset}\n\n"));

    for line in CHEATSHEET.lines() {
        if let Some(heading) = line.strip_prefix("## ") {
            if let Some((title, hint)) = heading.split_once(" | ") {
                out.push_str(&format!("{cyan}{title}{reset}  {dim}{hint}{reset}\n"));
            } else {
                out.push_str(&format!("{cyan}{heading}{reset}\n"));
            }
        } else if let Some(comment) = line.strip_prefix("# ") {
            out.push_str(&format!("{dim}# {comment}{reset}\n"));
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }

    print!("{out}");
    Ok(())
}

fn rewrite_template(content: &str, task_name: &str) -> String {
    let mut result = String::new();
    for line in content.lines() {
        if !result.is_empty() {
            result.push('\n');
        }
        if line.starts_with("[tasks.") {
            result.push_str(&format!("[tasks.{task_name}]"));
        } else {
            result.push_str(line);
        }
    }
    result
}

pub fn add_task(name: Option<String>) -> Result<()> {
    let cwd = env::current_dir()?;
    let config_path = cwd.join("plz.toml");
    let dotconfig_path = cwd.join(".plz.toml");

    let target_path = if config_path.exists() {
        config_path
    } else if dotconfig_path.exists() {
        dotconfig_path
    } else {
        bail!("No plz.toml found. Run `plz init` first.");
    };

    let task_name = match name {
        Some(n) if !n.trim().is_empty() => n.trim().to_string(),
        _ => {
            let input: String = cliclack::input("Task name?")
                .placeholder("e.g. build, test, deploy")
                .interact()?;
            let trimmed = input.trim().to_string();
            if trimmed.is_empty() {
                bail!("Task name cannot be empty");
            }
            trimmed
        }
    };

    let environments = templates::load_environments();
    let detected = templates::detect_environments(&cwd, &environments);
    let all_snippets = templates::load_snippets();

    match pick_snippet(&all_snippets, &detected, "Enter to add ยท Esc to cancel")? {
        Some(snippet) => {
            let content = rewrite_template(snippet.content.trim(), &task_name);

            let mut existing = std::fs::read_to_string(&target_path)?;
            if !existing.ends_with('\n') {
                existing.push('\n');
            }
            existing.push('\n');
            existing.push_str(&content);
            existing.push('\n');

            std::fs::write(&target_path, existing)?;
            println!(
                "\x1b[32mโœ“\x1b[0m  Added task \x1b[1m{task_name}\x1b[0m to {}",
                target_path.file_name().unwrap().to_string_lossy()
            );
        }
        None => {
            println!("\x1b[2mโœ•  Cancelled\x1b[0m");
        }
    }

    Ok(())
}

fn check_dir_writable(dir: &std::path::Path) -> bool {
    let target = if dir.is_dir() {
        dir.to_path_buf()
    } else if let Some(parent) = dir.parent() {
        parent.to_path_buf()
    } else {
        return false;
    };
    if !target.exists() {
        return true;
    }
    let probe = target.join(".plz_write_test");
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

pub fn setup() -> Result<()> {
    let plz_dir =
        config_dir().ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?;

    let templates_dir = plz_dir.join("templates");
    let user_template_path = templates_dir.join("user.plz.toml");
    let settings_path = plz_dir.join("settings.toml");

    let perm_hint = format!(
        "Try: chmod u+w {} or set PLZ_CONFIG_DIR to a writable path",
        plz_dir.display()
    );

    // Check write permissions early
    if plz_dir.exists() && !check_dir_writable(&plz_dir) {
        cliclack::intro("plz setup")?;
        cliclack::outro(format!(
            "{} is not writable. {perm_hint}",
            plz_dir.display()
        ))?;
        return Ok(());
    }

    // If .plz already exists, show settings editor
    if plz_dir.exists() {
        return setup_settings_editor(&settings_path);
    }

    if !check_dir_writable(&plz_dir) {
        cliclack::log::error(format!(
            "Cannot create {} (parent directory is not writable). {perm_hint}",
            plz_dir.display(),
        ))?;
        return Ok(());
    }

    if let Err(e) = std::fs::create_dir_all(&templates_dir) {
        cliclack::log::error(format!("Could not create {}: {e}", templates_dir.display()))?;
        return Ok(());
    }

    if !user_template_path.exists() {
        let content = r#"# Uncomment and edit to create a custom template for plz init
# [template]
# description = "Custom tasks"
# env = "uv"
#
# [tasks.example]
# run = "echo hello"
"#;
        let _ = std::fs::write(&user_template_path, content);
    }

    if !settings_path.exists() {
        let content = "# show_hints = true\n# check_for_updates = false\n";
        let _ = std::fs::write(&settings_path, content);
    }

    eprintln!("๐Ÿ™ Created {}", plz_dir.display());
    eprintln!(
        "\x1b[2m   Add templates to {} to customize plz init\x1b[0m",
        templates_dir.display()
    );

    Ok(())
}

fn setup_settings_editor(settings_path: &std::path::Path) -> Result<()> {
    let raw = settings::load_raw(settings_path);

    cliclack::intro("plz settings")?;

    // Display current settings with color coding
    for (key, value, is_user_set) in &raw {
        let entry = settings::ALL_SETTINGS
            .iter()
            .find(|e| e.key == *key)
            .unwrap();
        if *is_user_set {
            // Green for user-set values
            cliclack::log::step(format!(
                "\x1b[32m{key} = {value}\x1b[0m  {}",
                entry.description
            ))?;
        } else {
            // Grey for default values
            cliclack::log::step(format!(
                "\x1b[2m{key} = {value}\x1b[0m  {}",
                entry.description
            ))?;
        }
    }

    // Build multiselect with current values
    let currently_enabled: Vec<&str> = raw
        .iter()
        .filter(|(_, value, _)| *value)
        .map(|(key, _, _)| *key)
        .collect();

    let mut ms_items: Vec<crate::utils::MultiSelectItem> = settings::ALL_SETTINGS
        .iter()
        .map(|entry| crate::utils::MultiSelectItem {
            label: format!("{} โ€” {}", entry.key, entry.description),
            hint: String::new(),
            selected: currently_enabled.contains(&entry.key),
        })
        .collect();

    let selected: Vec<&str> =
        match crate::utils::multiselect("Toggle settings", &mut ms_items, false)? {
            Some(indices) => indices
                .iter()
                .map(|&i| settings::ALL_SETTINGS[i].key)
                .collect(),
            None => return Ok(()),
        };

    let values: Vec<(&str, bool)> = settings::ALL_SETTINGS
        .iter()
        .map(|entry| (entry.key, selected.contains(&entry.key)))
        .collect();

    // Only save if something changed
    let changed = raw
        .iter()
        .zip(values.iter())
        .any(|((_, old_val, _), (_, new_val))| old_val != new_val);

    if changed {
        settings::save(settings_path, &values)?;
        cliclack::outro("Settings saved")?;
    } else {
        cliclack::outro("No changes")?;
    }

    Ok(())
}

pub fn self_update() -> Result<()> {
    use axoupdater::{AxoUpdater, ReleaseSource, ReleaseSourceType};

    let current = env!("CARGO_PKG_VERSION");
    cliclack::intro(format!("plz update (current: v{current})"))?;

    let spinner = cliclack::spinner();
    spinner.start("Checking for updates...");

    let current_exe = std::env::current_exe()?;
    let install_dir = current_exe
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Can't determine install directory"))?;

    let mut updater = AxoUpdater::new_for("plzplz");
    updater.set_release_source(ReleaseSource {
        release_type: ReleaseSourceType::GitHub,
        owner: "k88hudson".to_string(),
        name: "plzplz".to_string(),
        app_name: "plzplz".to_string(),
    });
    updater.set_install_dir(install_dir.to_string_lossy().as_ref());
    updater
        .set_current_version(current.parse()?)
        .map_err(|e| anyhow::anyhow!("{e}"))?;

    let update_needed = updater
        .is_update_needed_sync()
        .map_err(|e| anyhow::anyhow!("{e}"))?;

    if !update_needed {
        spinner.stop(format!("v{current} is already the latest version"));
        cliclack::outro("Nothing to do")?;
        return Ok(());
    }

    spinner.stop("New version available");
    let update_spinner = cliclack::spinner();
    update_spinner.start("Downloading and installing...");

    let result = updater.run_sync().map_err(|e| anyhow::anyhow!("{e}"))?;

    match result {
        Some(update_result) => {
            update_spinner.stop(format!("Updated to v{}", update_result.new_version));
            cliclack::outro("Update complete")?;
        }
        None => {
            update_spinner.stop("No update performed");
            cliclack::outro("Nothing to do")?;
        }
    }

    Ok(())
}