jan-cli 0.18.0

YAML-defined CLI trees with progressive help, optional exec aliases, merged extra specs, and SQLite audit logging keyed by git branch
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
//! `jan config` — emit shell fragments, symlink rc files, run imperative apply steps,
//! and check host tool deps.

use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};

use crate::deps::utility_available;
use crate::spec_load::resolve_under_use_root;
use crate::{ConfigShell, ConfigSpec, RootSpec};

fn print_config_help() {
    print!(
        "\
config — emit / link / apply / deps host configuration from the preferred tree

USAGE:
    jan config emit [OPTIONS]
    jan config link [OPTIONS]
    jan config apply [OPTIONS]
    jan config deps [OPTIONS]
    jan config --help

SUBCOMMANDS:
    emit     Concatenate `config.shell` fragments (source from your shell / install)
    link     Symlink (or copy) `config.link` sources into $HOME destinations
    apply    Run `config.apply` argv lists (e.g. git config --global …)
    deps     Report `config.deps` host tools missing from PATH

EMIT OPTIONS:
        --shell <sh|bash|zsh>   Header dialect (default: zsh)
    -o, --output <FILE>         Write to FILE instead of stdout

LINK OPTIONS:
        --dry-run               Print planned links without changing the filesystem
        --copy                  Copy files instead of symlinking
        --force                 Replace an existing destination (default: warn and skip)

APPLY OPTIONS:
        --dry-run               Print argv lists without running them

DEPS OPTIONS:
        --strict                Exit 1 if any listed tool is missing (default: exit 0)

DESCRIPTION:
    Declare `config:` on any command node (see docs/cli/config.md). Fragments and
    link sources are paths under the preferred jan directory (`jan use`).
    Interactive shortcuts belong in `aliases:` (`jan alias`), not here.
    `config link` does not overwrite an existing path unless `--force` is set;
    it prints a warning and skips that destination instead.

"
    );
}

#[derive(Debug, Clone)]
struct CollectedConfig {
    chain: Vec<String>,
    spec: ConfigSpec,
}

fn collect_configs(spec: &RootSpec) -> Vec<CollectedConfig> {
    let mut out = Vec::new();
    crate::shell_emit::visit_command_tree(&spec.commands, &[], &mut |chain, node| {
        if !node.config.is_empty() {
            out.push(CollectedConfig {
                chain: chain.to_vec(),
                spec: node.config.clone(),
            });
        }
    });
    out
}

fn expand_home_dest(dest: &str) -> Result<PathBuf> {
    let dest = dest.trim();
    if dest.is_empty() {
        bail!("empty link destination");
    }
    let expanded = if let Some(rest) = dest.strip_prefix("~/") {
        let home = dirs::home_dir().context("$HOME is not set")?;
        home.join(rest)
    } else if dest == "~" {
        dirs::home_dir().context("$HOME is not set")?
    } else {
        PathBuf::from(dest)
    };
    if expanded.is_absolute() {
        let home = dirs::home_dir().context("$HOME is not set")?;
        let xdg = std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute());
        let under_home = expanded.starts_with(&home);
        let under_xdg = xdg.as_ref().is_some_and(|x| expanded.starts_with(x));
        if !under_home && !under_xdg {
            bail!(
                "refusing link destination outside $HOME (or $XDG_CONFIG_HOME): {}",
                expanded.display()
            );
        }
        Ok(expanded)
    } else {
        bail!("link destination must be absolute or start with ~/ : {dest}");
    }
}

fn emit_body(spec: &RootSpec, use_root: &Path, shell: &str) -> Result<String> {
    let mut body = crate::shell_emit::generated_shell_header(
        "jan config emit",
        shell,
        "# requires: jan use <DIR>; source this file in your shell",
    );
    let collected = collect_configs(spec);
    if collected.is_empty() {
        body.push_str("# (no config.shell fragments in the preferred tree)\n");
        return Ok(body);
    }
    for item in collected {
        let Some(shell_frag) = &item.spec.shell else {
            continue;
        };
        let chain = item.chain.join(" ");
        body.push('\n');
        body.push_str(&format!("# --- from `{chain}` ---\n"));
        match shell_frag {
            ConfigShell::Inline(text) => {
                let t = text.trim_end();
                body.push_str(t);
                if !t.ends_with('\n') {
                    body.push('\n');
                }
            }
            ConfigShell::Path(rel) => {
                let path = resolve_under_use_root(use_root, rel)?;
                let text = fs::read_to_string(&path)
                    .with_context(|| format!("read config.shell {}", path.display()))?;
                body.push_str(&format!("# path: {rel}\n"));
                let t = text.trim_end();
                body.push_str(t);
                if !t.ends_with('\n') {
                    body.push('\n');
                }
            }
        }
    }
    Ok(body)
}

fn run_emit(spec: &RootSpec, use_root: &Path, args: &[OsString]) -> Result<i32> {
    let mut shell = "zsh".to_string();
    let mut output: Option<PathBuf> = None;
    let mut i = 0usize;
    while i < args.len() {
        let s = args[i].to_string_lossy();
        match s.as_ref() {
            "--help" | "-h" => {
                print_config_help();
                return Ok(0);
            }
            "--shell" => {
                i += 1;
                let v = args
                    .get(i)
                    .ok_or_else(|| anyhow::anyhow!("missing value after `--shell`"))?
                    .to_string_lossy()
                    .into_owned();
                if !matches!(v.as_str(), "sh" | "bash" | "zsh") {
                    bail!("--shell must be sh, bash, or zsh");
                }
                shell = v;
            }
            "-o" | "--output" => {
                i += 1;
                let v = args
                    .get(i)
                    .ok_or_else(|| anyhow::anyhow!("missing value after `-o`/`--output`"))?;
                output = Some(PathBuf::from(v));
            }
            other if other.starts_with('-') => bail!("unknown config emit flag `{other}`"),
            _ => bail!("unexpected config emit argument `{s}`"),
        }
        i += 1;
    }
    let body = emit_body(spec, use_root, &shell)?;
    if let Some(path) = output {
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("create {}", parent.display()))?;
            }
        }
        fs::write(&path, body.as_bytes())
            .with_context(|| format!("write {}", path.display()))?;
    } else {
        print!("{body}");
    }
    Ok(0)
}

fn dest_exists(dest: &Path) -> bool {
    dest.symlink_metadata().is_ok()
}

/// True when `dest` is already a symlink whose target is `src`.
fn already_linked_to(dest: &Path, src: &Path) -> bool {
    let Ok(meta) = dest.symlink_metadata() else {
        return false;
    };
    if !meta.file_type().is_symlink() {
        return false;
    }
    match fs::read_link(dest) {
        Ok(target) => target == src,
        Err(_) => false,
    }
}

fn run_link(spec: &RootSpec, use_root: &Path, args: &[OsString]) -> Result<i32> {
    let mut dry_run = false;
    let mut copy = false;
    let mut force = false;
    let mut i = 0usize;
    while i < args.len() {
        let s = args[i].to_string_lossy();
        match s.as_ref() {
            "--help" | "-h" => {
                print_config_help();
                return Ok(0);
            }
            "--dry-run" => dry_run = true,
            "--copy" => copy = true,
            "--force" => force = true,
            other if other.starts_with('-') => bail!("unknown config link flag `{other}`"),
            _ => bail!("unexpected config link argument `{s}`"),
        }
        i += 1;
    }

    let collected = collect_configs(spec);
    let mut n = 0usize;
    let mut skipped = 0usize;
    for item in &collected {
        for (dest_raw, src_rel) in &item.spec.link {
            let dest = expand_home_dest(dest_raw)?;
            let src = resolve_under_use_root(use_root, src_rel)?;
            let chain = item.chain.join(" ");
            let action = if copy { "copy" } else { "symlink" };

            if dest_exists(&dest) {
                if !copy && already_linked_to(&dest, &src) {
                    if dry_run {
                        println!(
                            "# dry-run [{chain}] already linked {} -> {}",
                            src.display(),
                            dest.display()
                        );
                    } else {
                        println!("ok (already linked): {} -> {}", src.display(), dest.display());
                    }
                    n += 1;
                    continue;
                }
                if !force {
                    eprintln!(
                        "warning: destination already exists, skipping {action}: {} (use --force to replace)",
                        dest.display()
                    );
                    skipped += 1;
                    continue;
                }
            }

            if dry_run {
                println!(
                    "# dry-run [{chain}] {action} {} -> {}",
                    src.display(),
                    dest.display()
                );
                n += 1;
                continue;
            }
            if let Some(parent) = dest.parent() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("create {}", parent.display()))?;
            }
            if dest_exists(&dest) {
                fs::remove_file(&dest)
                    .or_else(|_| fs::remove_dir_all(&dest))
                    .with_context(|| format!("remove existing {}", dest.display()))?;
            }
            if copy {
                fs::copy(&src, &dest).with_context(|| {
                    format!("copy {} -> {}", src.display(), dest.display())
                })?;
            } else {
                std::os::unix::fs::symlink(&src, &dest).with_context(|| {
                    format!("symlink {} -> {}", src.display(), dest.display())
                })?;
            }
            println!("{action}: {} -> {}", src.display(), dest.display());
            n += 1;
        }
    }
    if n == 0 && skipped == 0 {
        eprintln!("jan config link: no config.link entries in the preferred tree");
    }
    Ok(0)
}

fn run_apply(spec: &RootSpec, args: &[OsString]) -> Result<i32> {
    let mut dry_run = false;
    let mut i = 0usize;
    while i < args.len() {
        let s = args[i].to_string_lossy();
        match s.as_ref() {
            "--help" | "-h" => {
                print_config_help();
                return Ok(0);
            }
            "--dry-run" => dry_run = true,
            other if other.starts_with('-') => bail!("unknown config apply flag `{other}`"),
            _ => bail!("unexpected config apply argument `{s}`"),
        }
        i += 1;
    }

    let collected = collect_configs(spec);
    let mut n = 0usize;
    for item in &collected {
        let chain = item.chain.join(" ");
        for argv in &item.spec.apply {
            if argv.is_empty() {
                continue;
            }
            if dry_run {
                println!("# dry-run [{chain}] {}", argv.join(" "));
                n += 1;
                continue;
            }
            let prog = &argv[0];
            let status = Command::new(prog)
                .args(&argv[1..])
                .status()
                .with_context(|| format!("spawn `{}` (from `{chain}`)", argv.join(" ")))?;
            if !status.success() {
                bail!(
                    "config.apply failed for `{chain}`: {} (exit {:?})",
                    argv.join(" "),
                    status.code()
                );
            }
            println!("ok: {}", argv.join(" "));
            n += 1;
        }
    }
    if n == 0 {
        eprintln!("jan config apply: no config.apply entries in the preferred tree");
    }
    Ok(0)
}

fn group_label(chain: &[String], node_about: &str) -> String {
    let about = node_about.trim();
    if !about.is_empty() {
        return first_line(about);
    }
    if chain.is_empty() {
        return "deps".to_string();
    }
    chain.join(" ")
}

fn first_line(s: &str) -> String {
    s.lines().next().unwrap_or("").trim().to_string()
}

fn format_dep_line(bin: &str, hint: &str) -> String {
    let hint = hint.trim();
    if hint.is_empty() {
        bin.to_string()
    } else {
        format!("{bin} ({hint})")
    }
}

fn run_deps(spec: &RootSpec, args: &[OsString]) -> Result<i32> {
    let mut strict = false;
    let mut i = 0usize;
    while i < args.len() {
        let s = args[i].to_string_lossy();
        match s.as_ref() {
            "--help" | "-h" => {
                print_config_help();
                return Ok(0);
            }
            "--strict" => strict = true,
            other if other.starts_with('-') => bail!("unknown config deps flag `{other}`"),
            _ => bail!("unexpected config deps argument `{s}`"),
        }
        i += 1;
    }

    // Preserve tree-walk order; within a node, BTreeMap sorts bins.
    let mut sections: Vec<(String, Vec<(String, String)>)> = Vec::new();
    let mut total = 0usize;
    crate::shell_emit::visit_command_tree(&spec.commands, &[], &mut |chain, node| {
        if node.config.deps.is_empty() {
            return;
        }
        let label = group_label(chain, &node.about);
        let mut missing = Vec::new();
        for (bin, hint) in &node.config.deps {
            let bin = bin.trim();
            if bin.is_empty() {
                continue;
            }
            total += 1;
            if !utility_available(bin) {
                missing.push((bin.to_string(), hint.clone()));
            }
        }
        if !missing.is_empty() {
            sections.push((label, missing));
        }
    });

    if total == 0 {
        eprintln!("jan config deps: no config.deps entries in the preferred tree");
        return Ok(0);
    }

    let mut missing_n = 0usize;
    if sections.is_empty() {
        println!("jan config deps: all {total} listed tool(s) are on PATH");
    } else {
        for (label, missing) in &sections {
            missing_n += missing.len();
            println!("\nMissing {label}:");
            for (bin, hint) in missing {
                println!("  {}", format_dep_line(bin, hint));
            }
        }
        println!(
            "\n{missing_n} missing of {total} listed tool(s). Install them or trim `config.deps`."
        );
    }

    if strict && missing_n > 0 {
        Ok(1)
    } else {
        Ok(0)
    }
}

/// `jan config [emit|link|apply|deps] …`
pub fn dispatch_config(spec: &RootSpec, use_root: &Path, args: &[OsString]) -> Result<i32> {
    if args.is_empty() {
        print_config_help();
        return Ok(0);
    }
    let first = args[0].to_string_lossy();
    match first.as_ref() {
        "--help" | "-h" => {
            print_config_help();
            Ok(0)
        }
        "emit" => run_emit(spec, use_root, &args[1..]),
        "link" => run_link(spec, use_root, &args[1..]),
        "apply" => run_apply(spec, &args[1..]),
        "deps" => run_deps(spec, &args[1..]),
        other => {
            bail!("unknown config subcommand `{other}`; use emit, link, apply, or deps");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CommandNode, ConfigShell, ConfigSpec};
    use std::collections::BTreeMap;

    #[test]
    fn expand_home_accepts_tilde() {
        let home = dirs::home_dir().unwrap();
        let p = expand_home_dest("~/.config/jan/x").unwrap();
        assert_eq!(p, home.join(".config/jan/x"));
    }

    #[test]
    fn expand_home_rejects_outside() {
        assert!(expand_home_dest("/etc/passwd").is_err());
    }

    #[test]
    fn collect_walks_nested_config() {
        let mut leaf = CommandNode::default();
        leaf.config = ConfigSpec {
            shell: Some(ConfigShell::Inline("export A=1\n".into())),
            ..Default::default()
        };
        let mut mid = CommandNode::default();
        mid.commands.insert("zsh".into(), leaf);
        let mut root = RootSpec {
            metadata: None,
            commands: BTreeMap::new(),
        };
        root.commands.insert("config".into(), mid);
        let c = collect_configs(&root);
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].chain, vec!["config".to_string(), "zsh".to_string()]);
    }
}