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