Skip to main content

jan_cli/
runner.rs

1use std::ffi::OsString;
2use std::path::PathBuf;
3
4use anyhow::{anyhow, Context, Result};
5use clap::{ArgAction, Parser};
6
7use crate::{
8    builtins, default_db_path, format_help, load_spec, match_commands, resolve_git_branch,
9    resolve_preferred_spec, run_matched, RootSpec, RunContext,
10};
11
12#[derive(Parser, Debug)]
13#[command(name = "jan")]
14#[command(
15    about = "YAML-driven command tree loaded from the preferred directory (`jan use`)",
16    version,
17    disable_help_flag = true
18)]
19pub struct JanCli {
20    /// Print help for the loaded command tree (or framework help if none is configured)
21    #[arg(long, short = 'h', action = ArgAction::SetTrue, global = true)]
22    pub help: bool,
23
24    /// SQLite database path for invocation audit log
25    #[arg(long, value_name = "FILE", env = "JAN_DB", global = true)]
26    pub db: Option<PathBuf>,
27
28    /// Override git branch recorded in the audit log (default: `git rev-parse` or JAN_BRANCH)
29    #[arg(long, global = true)]
30    pub branch: Option<String>,
31
32    /// Do not write to the SQLite audit log
33    #[arg(long, global = true)]
34    pub no_log: bool,
35
36    /// Working directory for subprocesses and git branch detection
37    #[arg(long, global = true, default_value = ".")]
38    pub cwd: PathBuf,
39
40    /// Print how the preferred spec was resolved (stderr)
41    #[arg(short, long, global = true)]
42    pub verbose: bool,
43
44    /// Spec-defined subcommands, then optional passthrough args for `exec.passthrough`
45    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
46    pub command: Vec<OsString>,
47}
48
49fn framework_builtins_help() -> String {
50    "\
51Built-in commands:
52  use — set, show, or clear the preferred jan directory
53  bundle — pack the preferred YAML tree into a ZIP
54  alias — emit shell aliases for executable leaves
55  list — list script leaves in the preferred tree
56  search — find scripts by name/about/category
57  show — print details for a script leaf
58  validate — structural checks for the preferred tree
59  audit — query the SQLite invocation log
60  cron — run scripts whose `cron:` schedule matches now
61  packages — inspect cached `packages.uv` environments
62
63Global options:
64  -h, --help       Show this help (lists live subcommands when a preferred dir is set)
65  -V, --version    Print version
66  -v, --verbose    Explain how the preferred directory was resolved
67      --cwd <DIR>  Working directory for subprocesses (default: .)
68      --db <FILE>  SQLite audit log path
69      --branch <B> Override git branch recorded in the audit log
70      --no-log     Do not write to the audit log
71
72Configure a command tree with `jan use <DIR>`, then re-run `jan --help` to list live subcommands.
73"
74    .to_string()
75}
76
77fn print_root_help(spec: Option<&RootSpec>) {
78    match spec {
79        Some(spec) => {
80            print!("{}", format_help(spec, &[], None));
81        }
82        None => {
83            println!("jan — YAML-driven command tree\n");
84            println!("No preferred jan directory is configured yet.\n");
85            println!("  jan use <DIR>     Save a directory containing scripts.spec.yaml");
86            println!("  jan use --show    Show the saved preference\n");
87        }
88    }
89    print!("{}", framework_builtins_help());
90}
91
92pub fn run_jan() -> Result<i32> {
93    let cli = JanCli::parse();
94    let cwd = cli.cwd.canonicalize().unwrap_or_else(|_| cli.cwd.clone());
95
96    // Bootstrap builtins that must work without a loaded YAML tree.
97    if let Some(first) = cli.command.first() {
98        let key = first.to_string_lossy();
99        if builtins::is_pre_spec_builtin(key.as_ref()) {
100            let tail: Vec<_> = cli.command[1..].to_vec();
101            return match key.as_ref() {
102                "use" => builtins::run_use(&tail),
103                _ => Ok(0),
104            };
105        }
106    }
107
108    let loaded = match resolve_preferred_spec() {
109        Ok(pair) => Some(pair),
110        Err(e) => {
111            if cli.help || cli.command.is_empty() {
112                print_root_help(None);
113                if cli.verbose {
114                    eprintln!("jan: no preferred spec ({e:#})");
115                }
116                return Ok(0);
117            }
118            return Err(e);
119        }
120    };
121
122    let (spec_path, spec_identity) = loaded.expect("Ok branch always sets Some");
123    let spec = load_spec(&spec_path).with_context(|| format!("load {}", spec_path.display()))?;
124
125    if cli.verbose {
126        eprintln!("jan: cwd={}", cwd.display());
127        eprintln!(
128            "jan: preferred directory: {} / {}",
129            spec_identity.spec_dir, spec_identity.root_yaml
130        );
131    }
132
133    let branch = resolve_git_branch(&cwd, cli.branch.as_deref());
134    let audit_db = cli.db.as_ref().cloned().unwrap_or_else(default_db_path);
135    let db_path = if cli.no_log {
136        None
137    } else {
138        Some(audit_db.clone())
139    };
140
141    let ctx = RunContext {
142        cwd: &cwd,
143        db_path: db_path.as_deref(),
144        branch,
145        no_log: cli.no_log,
146        spec_root: &spec_identity,
147    };
148
149    if cli.command.is_empty() {
150        print_root_help(Some(&spec));
151        return Ok(0);
152    }
153
154    if let Some(first) = cli.command.first() {
155        let key = first.to_string_lossy();
156        if builtins::is_builtin_reserved(key.as_ref()) {
157            let tail: Vec<_> = cli.command[1..].to_vec();
158            return match key.as_ref() {
159                "bundle" => builtins::bundle_spec_zip(&spec_identity, &tail, cli.verbose),
160                "alias" => builtins::emit_shell_aliases(&spec, &tail),
161                "use" => builtins::run_use(&tail),
162                "list" | "search" | "show" | "validate" => {
163                    let root = PathBuf::from(&spec_identity.spec_dir);
164                    crate::inspect::dispatch_inspect(key.as_ref(), &tail, &spec, None, Some(&root))
165                }
166                "audit" => crate::inspect::dispatch_inspect(
167                    key.as_ref(),
168                    &tail,
169                    &spec,
170                    Some(&audit_db),
171                    None,
172                ),
173                "cron" => crate::inspect::run_cron(&spec, &tail, &ctx),
174                "packages" => {
175                    let root = PathBuf::from(&spec_identity.spec_dir);
176                    crate::packages::dispatch_packages(&tail, &spec, &root)
177                }
178                _ => Ok(0),
179            };
180        }
181    }
182
183    let m = match_commands(&spec, &cli.command);
184
185    if cli.help || m.wants_help {
186        let help = format_help(&spec, &m.chain, m.node);
187        print!("{help}");
188        return Ok(0);
189    }
190
191    if m.trailing.iter().any(|a| a == "--help" || a == "-h") {
192        return Err(anyhow!(
193            "place --help immediately after the subcommand prefix you want help for"
194        ));
195    }
196
197    let node = match m.node {
198        Some(n) => n,
199        None => {
200            let key = cli.command[0].to_string_lossy();
201            return Err(anyhow!("unknown top-level command `{key}`"));
202        }
203    };
204
205    if !m.trailing.is_empty() && !node.is_leaf_exec() {
206        let t = m.trailing[0].to_string_lossy();
207        return Err(anyhow!("unknown subcommand `{t}`"));
208    }
209
210    if node.is_leaf_exec() {
211        return run_matched(&spec, &m.chain, node, &m.trailing, &ctx);
212    }
213
214    let help = format_help(&spec, &m.chain, Some(node));
215    print!("{help}");
216    Ok(0)
217}