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  computer — register, show, or clear the host computer id for `computer:` filtering
54  bundle — pack the preferred YAML tree into a ZIP
55  alias — emit shell aliases for executable leaves
56  config — emit / link / unlink / apply / deps host configuration from the preferred tree
57  list — list script leaves in the preferred tree
58  search — find scripts by name/about/category
59  show — print details for a script leaf
60  validate — structural checks for the preferred tree
61  audit — query the SQLite invocation log
62  cron — start/stop daemon; --list reads the schedule cache (100ms ticks)
63  runtime — warm language interpreter pool (python/node/shell/kotlin)
64  packages — inspect / prune cached package environments (uv, pnpm, gradle)
65  test — run Given/When/Then shell tests for a command path (and nested)
66  ps — show jan processes and collective CPU usage
67
68Global options:
69  -h, --help       Show this help (lists live subcommands when a preferred dir is set)
70  -V, --version    Print version
71  -v, --verbose    Explain how the preferred directory was resolved
72      --cwd <DIR>  Working directory for subprocesses (default: .)
73      --db <FILE>  SQLite audit log path
74      --branch <B> Override git branch recorded in the audit log
75      --no-log     Do not write to the audit log
76
77Configure a command tree with `jan use <DIR>`, then re-run `jan --help` to list live subcommands.
78"
79    .to_string()
80}
81
82fn print_root_help(spec: Option<&RootSpec>) {
83    match spec {
84        Some(spec) => {
85            print!("{}", format_help(spec, &[], None));
86        }
87        None => {
88            println!("jan — YAML-driven command tree\n");
89            println!("No preferred jan directory is configured yet.\n");
90            println!("  jan use <DIR>     Save a directory containing scripts.spec.yaml");
91            println!("  jan use --show    Show the saved preference\n");
92        }
93    }
94    print!("{}", framework_builtins_help());
95}
96
97pub fn run_jan() -> Result<i32> {
98    let cli = JanCli::parse();
99    let cwd = cli.cwd.canonicalize().unwrap_or_else(|_| cli.cwd.clone());
100
101    // Bootstrap builtins that must work without a loaded YAML tree.
102    if let Some(first) = cli.command.first() {
103        let key = first.to_string_lossy();
104        if builtins::is_pre_spec_builtin(key.as_ref()) {
105            let tail: Vec<_> = cli.command[1..].to_vec();
106            return match key.as_ref() {
107                "use" => builtins::run_use(&tail),
108                "computer" => builtins::run_computer(&tail),
109                "ps" => crate::ps::run_ps(&tail),
110                "runtime" => crate::runtime_daemon::dispatch_runtime(&tail),
111                _ => Ok(0),
112            };
113        }
114    }
115
116    let loaded = match resolve_preferred_spec() {
117        Ok(pair) => Some(pair),
118        Err(e) => {
119            if cli.help || cli.command.is_empty() {
120                print_root_help(None);
121                if cli.verbose {
122                    eprintln!("jan: no preferred spec ({e:#})");
123                }
124                return Ok(0);
125            }
126            return Err(e);
127        }
128    };
129
130    let (spec_path, spec_identity) = loaded.expect("Ok branch always sets Some");
131    let spec = load_spec(&spec_path).with_context(|| format!("load {}", spec_path.display()))?;
132
133    if cli.verbose {
134        eprintln!("jan: cwd={}", cwd.display());
135        eprintln!(
136            "jan: preferred directory: {} / {}",
137            spec_identity.spec_dir, spec_identity.root_yaml
138        );
139    }
140
141    let branch = resolve_git_branch(&cwd, cli.branch.as_deref());
142    let is_test = cli
143        .command
144        .first()
145        .is_some_and(|s| s.to_string_lossy() == "test");
146    let no_log = cli.no_log || is_test || std::env::var_os("JAN_NO_LOG").is_some();
147    let audit_db = cli.db.as_ref().cloned().unwrap_or_else(default_db_path);
148    let db_path = if no_log { None } else { Some(audit_db.clone()) };
149
150    let ctx = RunContext {
151        cwd: &cwd,
152        db_path: db_path.as_deref(),
153        branch,
154        no_log,
155        spec_root: &spec_identity,
156    };
157
158    if cli.command.is_empty() {
159        print_root_help(Some(&spec));
160        return Ok(0);
161    }
162
163    if let Some(first) = cli.command.first() {
164        let key = first.to_string_lossy();
165        if builtins::is_builtin_reserved(key.as_ref()) {
166            let tail: Vec<_> = cli.command[1..].to_vec();
167            return match key.as_ref() {
168                "bundle" => builtins::bundle_spec_zip(&spec_identity, &tail, cli.verbose),
169                "alias" => builtins::emit_shell_aliases(&spec, &tail),
170                "config" => {
171                    let root = PathBuf::from(&spec_identity.spec_dir);
172                    crate::hostconfig::dispatch_config(&spec, &root, &tail)
173                }
174                "use" => builtins::run_use(&tail),
175                "computer" => builtins::run_computer(&tail),
176                "list" | "search" | "show" | "validate" => {
177                    let root = PathBuf::from(&spec_identity.spec_dir);
178                    crate::inspect::dispatch_inspect(key.as_ref(), &tail, &spec, None, Some(&root))
179                }
180                "audit" => crate::inspect::dispatch_inspect(
181                    key.as_ref(),
182                    &tail,
183                    &spec,
184                    Some(&audit_db),
185                    None,
186                ),
187                "cron" => crate::inspect::run_cron(&spec, &tail, &ctx),
188                "runtime" => crate::runtime_daemon::dispatch_runtime(&tail),
189                "packages" => {
190                    let root = PathBuf::from(&spec_identity.spec_dir);
191                    crate::packages::dispatch_packages(&tail, &spec, &root)
192                }
193                "test" => crate::cmdtest::dispatch_test(&tail, &spec, &ctx),
194                "ps" => crate::ps::run_ps(&tail),
195                _ => Ok(0),
196            };
197        }
198    }
199
200    let m = match_commands(&spec, &cli.command);
201
202    if cli.help || m.wants_help {
203        let help = format_help(&spec, &m.chain, m.node);
204        print!("{help}");
205        return Ok(0);
206    }
207
208    if m.trailing.iter().any(|a| a == "--help" || a == "-h") {
209        return Err(anyhow!(
210            "place --help immediately after the subcommand prefix you want help for"
211        ));
212    }
213
214    let node = match m.node {
215        Some(n) => n,
216        None => {
217            let key = cli.command[0].to_string_lossy();
218            return Err(anyhow!("unknown top-level command `{key}`"));
219        }
220    };
221
222    if !m.trailing.is_empty() && !node.is_leaf_exec() {
223        let t = m.trailing[0].to_string_lossy();
224        return Err(anyhow!("unknown subcommand `{t}`"));
225    }
226
227    if node.is_leaf_exec() {
228        return run_matched(&spec, &m.chain, node, &m.trailing, &ctx);
229    }
230
231    let help = format_help(&spec, &m.chain, Some(node));
232    print!("{help}");
233    Ok(0)
234}