mod builtins;
mod config;
mod cron;
mod deps;
mod inputs;
mod inspect;
mod packages;
pub mod remote;
mod runner;
mod spec_load;
mod yaml_closure;
pub use config::{load_user_config, UserConfig};
pub use runner::run_jan;
pub use spec_load::HostPlatform;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{bail, Context, Result};
use rusqlite::Connection;
use serde::Deserialize;
use serde::de::{self, Deserializer, Visitor};
use std::fmt;
#[derive(Debug, Deserialize)]
pub struct RootSpec {
pub metadata: Option<Metadata>,
#[serde(default)]
pub commands: BTreeMap<String, CommandNode>,
}
#[derive(Debug, Deserialize)]
pub struct Metadata {
pub name: Option<String>,
pub description: Option<String>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct EnvSpec {
pub public: BTreeMap<String, String>,
pub private: Vec<String>,
pub pass: BTreeMap<String, String>,
}
impl EnvSpec {
pub fn is_empty(&self) -> bool {
self.public.is_empty() && self.private.is_empty() && self.pass.is_empty()
}
pub fn restricts_child_env(&self) -> bool {
!self.is_empty()
}
pub fn merge_from(&mut self, other: EnvSpec) {
for (k, v) in other.public {
self.public.insert(k, v);
}
for name in other.private {
if !self.private.iter().any(|p| p == &name) {
self.private.push(name);
}
}
for (k, v) in other.pass {
self.pass.insert(k, v);
}
}
pub fn validate(&self, path: &str) -> Result<()> {
for name in &self.private {
if name.trim().is_empty() {
bail!("command '{path}': env.private entry must not be empty");
}
}
for (env_name, pass_id) in &self.pass {
if env_name.trim().is_empty() {
bail!("command '{path}': env.pass key must not be empty");
}
if pass_id.trim().is_empty() {
bail!("command '{path}': env.pass id for `{env_name}` must not be empty");
}
if self.private.iter().any(|p| p == env_name) {
bail!(
"command '{path}': env var `{env_name}` cannot be both `env.private` and `env.pass`"
);
}
}
Ok(())
}
}
impl<'de> Deserialize<'de> for EnvSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Structured {
#[serde(default)]
public: BTreeMap<String, String>,
#[serde(default, deserialize_with = "deserialize_string_or_seq")]
private: Vec<String>,
#[serde(default)]
pass: BTreeMap<String, String>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum EnvDe {
Flat(BTreeMap<String, String>),
Sections(Structured),
}
Ok(match EnvDe::deserialize(deserializer)? {
EnvDe::Flat(public) => Self {
public,
private: Vec::new(),
pass: BTreeMap::new(),
},
EnvDe::Sections(s) => Self {
public: s.public,
private: s.private,
pass: s.pass,
},
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludeLinkKind {
Yaml,
Script,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeLink {
pub kind: IncludeLinkKind,
pub path: Option<String>,
pub url: Option<String>,
pub sha256: Option<String>,
}
#[derive(Debug, Deserialize, Default, Clone)]
pub struct CommandNode {
#[serde(default)]
pub os: Vec<String>,
#[serde(default)]
pub about: String,
pub path: Option<String>,
#[serde(default)]
pub dependencies: Vec<String>,
#[serde(default)]
pub requires: Vec<String>,
#[serde(default)]
pub env: EnvSpec,
#[serde(default)]
pub inputs: BTreeMap<String, crate::inputs::InputDef>,
#[serde(default, deserialize_with = "deserialize_string_or_seq")]
pub cron: Vec<String>,
#[serde(default)]
pub packages: PackagesSpec,
#[serde(default)]
pub commands: BTreeMap<String, CommandNode>,
pub exec: Option<ExecSpec>,
#[serde(skip)]
pub source: Option<IncludeLink>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
pub struct PackagesSpec {
#[serde(default)]
pub uv: Option<UvPackages>,
#[serde(default)]
pub pnpm: Option<serde_yaml::Value>,
}
impl PackagesSpec {
pub fn is_empty(&self) -> bool {
self.uv.is_none() && self.pnpm.is_none()
}
pub fn merge_from(&mut self, other: PackagesSpec) {
if other.uv.is_some() {
self.uv = other.uv;
}
if other.pnpm.is_some() {
self.pnpm = other.pnpm;
}
}
pub fn validate(&self, path: &str) -> Result<()> {
if self.pnpm.is_some() {
bail!("command '{path}': packages.pnpm is not implemented yet");
}
if let Some(uv) = &self.uv {
uv.validate(path)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UvPackages {
List(Vec<String>),
Project(String),
Requirements(String),
}
impl UvPackages {
pub fn validate(&self, path: &str) -> Result<()> {
match self {
Self::List(pkgs) => {
if pkgs.is_empty() {
bail!("command '{path}': packages.uv list must not be empty");
}
for p in pkgs {
if p.trim().is_empty() {
bail!("command '{path}': packages.uv entry must not be empty");
}
}
}
Self::Project(p) | Self::Requirements(p) => {
if p.trim().is_empty() {
bail!("command '{path}': packages.uv path must not be empty");
}
}
}
Ok(())
}
}
impl<'de> Deserialize<'de> for UvPackages {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MapForm {
#[serde(default)]
project: Option<String>,
#[serde(default)]
requirements: Option<String>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Helper {
List(Vec<String>),
Map(MapForm),
}
match Helper::deserialize(deserializer)? {
Helper::List(pkgs) => {
let pkgs: Vec<String> = pkgs
.into_iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
Ok(UvPackages::List(pkgs))
}
Helper::Map(m) => {
let project = m
.project
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let requirements = m
.requirements
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
match (project, requirements) {
(Some(p), None) => Ok(UvPackages::Project(p)),
(None, Some(r)) => Ok(UvPackages::Requirements(r)),
(None, None) => Err(de::Error::custom(
"packages.uv map must set exactly one of `project` or `requirements`",
)),
(Some(_), Some(_)) => Err(de::Error::custom(
"packages.uv map must set exactly one of `project` or `requirements`, not both",
)),
}
}
}
}
}
pub(crate) fn deserialize_string_or_seq<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
struct StringOrSeq;
impl<'de> Visitor<'de> for StringOrSeq {
type Value = Vec<String>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string or a sequence of strings")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if value.trim().is_empty() {
Ok(Vec::new())
} else {
Ok(vec![value.to_string()])
}
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
self.visit_str(&value)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
let mut out = Vec::new();
while let Some(s) = seq.next_element::<String>()? {
if !s.trim().is_empty() {
out.push(s);
}
}
Ok(out)
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Vec::new())
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Vec::new())
}
}
deserializer.deserialize_any(StringOrSeq)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalInclude {
pub path: String,
pub sha256: Option<String>,
pub argv: Vec<String>,
pub passthrough: bool,
}
impl LocalInclude {
pub fn from_path(path: impl Into<String>) -> Self {
Self {
path: path.into(),
sha256: None,
argv: Vec::new(),
passthrough: false,
}
}
pub fn is_yaml(&self) -> bool {
let lower = self.path.to_ascii_lowercase();
lower.ends_with(".yaml") || lower.ends_with(".yml")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IncludeRef {
Local(LocalInclude),
Remote(RemoteInclude),
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct RemoteInclude {
pub url: String,
pub sha256: String,
#[serde(default)]
pub ttl: Option<u64>,
}
impl IncludeRef {
pub fn is_remote(&self) -> bool {
matches!(self, Self::Remote(_))
}
pub fn local_path(&self) -> Option<&str> {
match self {
Self::Local(l) => Some(l.path.as_str()),
Self::Remote(_) => None,
}
}
pub fn cycle_token(&self) -> String {
match self {
Self::Local(l) => match &l.sha256 {
Some(h) => format!("{}#{}", l.path, h.to_ascii_lowercase()),
None => l.path.clone(),
},
Self::Remote(r) => format!("{}#{}", r.url, r.sha256.to_ascii_lowercase()),
}
}
}
impl<'de> Deserialize<'de> for IncludeRef {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LocalMap {
path: String,
#[serde(default)]
sha256: Option<String>,
#[serde(default)]
argv: Vec<String>,
#[serde(default)]
passthrough: bool,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Helper {
Path(String),
Local(LocalMap),
Remote(RemoteInclude),
}
match Helper::deserialize(deserializer)? {
Helper::Path(path) => {
let path = path.trim();
if path.is_empty() {
return Err(de::Error::custom("include path must not be empty"));
}
Ok(IncludeRef::Local(LocalInclude::from_path(path)))
}
Helper::Local(m) => {
let path = m.path.trim();
if path.is_empty() {
return Err(de::Error::custom("include.path must not be empty"));
}
let sha256 = m
.sha256
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
Ok(IncludeRef::Local(LocalInclude {
path: path.to_string(),
sha256,
argv: m.argv,
passthrough: m.passthrough,
}))
}
Helper::Remote(r) => {
if r.url.trim().is_empty() {
return Err(de::Error::custom("include.url must not be empty"));
}
if r.sha256.trim().is_empty() {
return Err(de::Error::custom(
"include.sha256 is required with include.url",
));
}
Ok(IncludeRef::Remote(r))
}
}
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ExecSpec {
#[serde(default)]
pub argv: Vec<String>,
#[serde(default)]
pub passthrough: bool,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub file: Option<String>,
#[serde(default)]
pub sha256: Option<String>,
#[serde(default)]
pub ttl: Option<u64>,
}
impl ExecSpec {
pub fn is_remote(&self) -> bool {
self.url
.as_deref()
.map(|u| !u.trim().is_empty())
.unwrap_or(false)
}
pub fn is_local_file(&self) -> bool {
self.file
.as_deref()
.map(|u| !u.trim().is_empty())
.unwrap_or(false)
}
pub fn validate(&self, path: &str) -> Result<()> {
let url = self
.url
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
let file = self
.file
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
let hash = self
.sha256
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
if url.is_some() && file.is_some() {
bail!("command '{path}': exec cannot set both `url` and `file`");
}
match (url, file, hash) {
(Some(_), None, Some(_)) => Ok(()),
(Some(_), None, None) => {
bail!("command '{path}': exec.sha256 is required with exec.url")
}
(None, Some(_), _) => Ok(()),
(None, None, Some(_)) => {
bail!("command '{path}': exec.sha256 requires exec.url or exec.file")
}
(None, None, None) => {
if self.argv.is_empty() {
bail!(
"command '{path}': exec.argv must not be empty (or set exec.url / exec.file)"
);
}
Ok(())
}
(Some(_), Some(_), _) => unreachable!("checked above"),
}
}
}
impl CommandNode {
pub fn is_leaf_exec(&self) -> bool {
self.exec.is_some()
}
pub fn validate(&self, path: &str) -> Result<()> {
if self.exec.is_some() && !self.commands.is_empty() {
bail!("command '{path}' cannot define both `exec` and nested `commands`");
}
if let Some(ref e) = self.exec {
e.validate(path)?;
}
self.env.validate(path)?;
self.packages.validate(path)?;
for name in self.inputs.keys() {
inputs::InputDef::validate_name(name)
.map_err(|e| anyhow::anyhow!("command '{path}': {e}"))?;
}
for (name, child) in &self.commands {
let p = if path.is_empty() {
name.clone()
} else {
format!("{path} {name}")
};
child.validate(&p)?;
}
Ok(())
}
}
pub fn merge_specs_into(base: &mut RootSpec, overlay: RootSpec) -> Result<()> {
for (name, node) in overlay.commands {
match base.commands.get_mut(&name) {
Some(existing) => merge_command_node(existing, node)?,
None => {
base.commands.insert(name, node);
}
}
}
Ok(())
}
fn merge_command_node(dst: &mut CommandNode, src: CommandNode) -> Result<()> {
if src.exec.is_some() && !src.commands.is_empty() {
bail!("merge overlay: command cannot define both `exec` and nested `commands`");
}
if !src.os.is_empty() {
dst.os = src.os;
}
if !src.about.trim().is_empty() {
dst.about = src.about;
}
if src.path.is_some() {
dst.path = src.path;
}
if !src.dependencies.is_empty() {
dst.dependencies = src.dependencies;
}
if !src.requires.is_empty() {
dst.requires = src.requires;
}
if !src.cron.is_empty() {
dst.cron = src.cron;
}
if !src.env.is_empty() {
dst.env.merge_from(src.env);
}
for (k, v) in src.inputs {
dst.inputs.insert(k, v);
}
if let Some(exec) = src.exec {
dst.exec = Some(exec);
dst.commands.clear();
return Ok(());
}
if !src.commands.is_empty() {
dst.exec = None;
for (k, child) in src.commands {
match dst.commands.get_mut(&k) {
Some(existing) => merge_command_node(existing, child)?,
None => {
dst.commands.insert(k, child);
}
}
}
}
Ok(())
}
pub fn validate_spec(spec: &RootSpec) -> Result<()> {
for (name, node) in &spec.commands {
node.validate(name)?;
}
Ok(())
}
pub fn load_spec_from_str(raw: &str, include_base: Option<&Path>) -> Result<RootSpec> {
spec_load::load_spec_from_str(raw, include_base, HostPlatform::detect())
}
pub fn load_spec(path: &Path) -> Result<RootSpec> {
spec_load::load_spec_from_path(path, HostPlatform::detect())
}
pub fn resolve_git_branch(cwd: &Path, override_branch: Option<&str>) -> String {
if let Some(b) = override_branch {
if !b.is_empty() {
return b.to_string();
}
}
if let Ok(v) = std::env::var("JAN_BRANCH") {
if !v.is_empty() {
return v;
}
}
let output = Command::new("git")
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.current_dir(cwd)
.output();
match output {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
_ => "(no-git)".to_string(),
}
}
fn first_line(s: &str) -> String {
s.lines().next().unwrap_or("").trim().to_string()
}
pub fn format_help(spec: &RootSpec, chain: &[String], node: Option<&CommandNode>) -> String {
let mut out = String::new();
let bin = spec
.metadata
.as_ref()
.and_then(|m| m.name.as_deref())
.unwrap_or("jan");
let full_cmd = if chain.is_empty() {
bin.to_string()
} else {
format!("{} {}", bin, chain.join(" "))
};
let (about, children, exec) = match node {
Some(n) => (n.about.as_str(), &n.commands, n.exec.as_ref()),
None => ("", &spec.commands, None),
};
if chain.is_empty() {
if let Some(meta) = &spec.metadata {
if let Some(desc) = &meta.description {
out.push_str(desc.trim());
out.push_str("\n\n");
}
}
}
if !about.is_empty() {
out.push_str(about.trim());
out.push_str("\n\n");
}
if exec.is_some() && children.is_empty() {
out.push_str("This command runs an external program (see spec `exec.argv`).\n");
let defs = inputs::collect_chain_inputs(chain, spec);
if !defs.is_empty() {
out.push('\n');
out.push_str(&inputs::format_inputs_help(&defs));
}
return out;
}
if !children.is_empty() {
out.push_str("Subcommands:\n");
for (name, child) in children {
let line = if child.about.is_empty() {
format!(" {name}\n")
} else {
format!(" {name} — {}\n", first_line(&child.about))
};
out.push_str(&line);
}
out.push('\n');
out.push_str(&format!(
"Use `{} --help` for more about a subcommand.\n",
full_cmd
));
let defs = inputs::collect_chain_inputs(chain, spec);
if !defs.is_empty() {
out.push('\n');
out.push_str(&inputs::format_inputs_help(&defs));
}
} else if exec.is_none() {
out.push_str("(No subcommands defined.)\n");
}
if chain.is_empty() && node.is_none() {
out.push_str(
"\nPlace `--help` or `-h` right after the subcommand prefix you want. Built-ins: `use`, `bundle`, `alias`, `list`, `search`, `show`, `validate`, `audit`, `cron`.\n",
);
}
out
}
#[derive(Debug, Clone)]
pub struct SpecRootIdentity {
pub spec_dir: String,
pub root_yaml: String,
}
pub fn resolve_preferred_spec() -> Result<(PathBuf, SpecRootIdentity)> {
let cfg = config::load_user_config().context("load user config")?;
let Some(dir_s) = cfg
.jan_dir
.as_ref()
.map(|s| s.trim())
.filter(|s| !s.is_empty())
else {
bail!(
"no preferred jan directory configured\n\
Run `jan use <DIR>` to save a YAML command tree (see docs/PORTABLE_SCRIPTS.md)"
);
};
let dir = PathBuf::from(dir_s);
if !dir.is_dir() {
bail!(
"preferred jan directory does not exist: {}\n\
Fix the path or run `jan use <DIR>` again (config: {})",
dir.display(),
config::config_path().display()
);
}
let root = cfg
.spec_root
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("scripts.spec.yaml");
resolve_spec_dir_entry(&dir, root)
}
pub fn resolve_spec_dir_entry(
spec_dir: &Path,
root_yaml: &str,
) -> Result<(PathBuf, SpecRootIdentity)> {
let rel = Path::new(root_yaml);
if rel.is_absolute() {
bail!("entry YAML must be a relative file name, not an absolute path");
}
if rel
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
bail!("entry YAML must not contain `..`");
}
let normal_only = rel
.components()
.all(|c| matches!(c, std::path::Component::Normal(_)));
let n = rel
.components()
.filter(|c| matches!(c, std::path::Component::Normal(_)))
.count();
if !normal_only || n != 1 {
bail!("entry YAML must be a single file name inside the jan directory");
}
let dir = spec_dir
.canonicalize()
.with_context(|| format!("canonicalize jan directory {}", spec_dir.display()))?;
if !dir.is_dir() {
bail!("not a directory: {}", dir.display());
}
let spec_path = dir.join(rel);
if !spec_path.is_file() {
bail!(
"spec entry not found: {} (under {})\n\
Expected a properly formatted jan directory (e.g. scripts.spec.yaml)",
spec_path.display(),
dir.display()
);
}
let identity = SpecRootIdentity {
spec_dir: dir.to_string_lossy().into_owned(),
root_yaml: rel
.file_name()
.expect("relative root has file_name")
.to_string_lossy()
.into_owned(),
};
Ok((spec_path, identity))
}
pub struct RunContext<'a> {
pub cwd: &'a Path,
pub db_path: Option<&'a Path>,
pub branch: String,
pub no_log: bool,
pub spec_root: &'a SpecRootIdentity,
}
fn shell_inline_c_needs_argv0(argv: &[String]) -> bool {
if argv.len() != 3 {
return false;
}
let prog = Path::new(&argv[0])
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(argv[0].as_str());
let is_shell = matches!(
prog,
"bash" | "zsh" | "sh" | "dash" | "ksh" | "ash" | "busybox"
);
is_shell && matches!(argv[1].as_str(), "-c" | "-lc")
}
fn shell_passthrough_argv0(chain: &[String]) -> String {
chain
.iter()
.rev()
.find(|s| s.as_str() != "run")
.cloned()
.or_else(|| chain.last().cloned())
.unwrap_or_else(|| "jan".to_string())
}
pub fn run_matched(
spec: &RootSpec,
chain: &[String],
node: &CommandNode,
trailing: &[OsString],
ctx: &RunContext<'_>,
) -> Result<i32> {
let exec = match &node.exec {
Some(e) => e,
None => {
let help = format_help(spec, chain, Some(node));
print!("{help}");
bail!("missing subcommand");
}
};
exec.validate(&chain.join(" "))?;
let input_defs = inputs::collect_chain_inputs(chain, spec);
let (input_vals, rest) = inputs::resolve_inputs(&input_defs, trailing)?;
let mut argv: Vec<String> = Vec::with_capacity(exec.argv.len() + 1);
for a in &exec.argv {
argv.push(inputs::interpolate(a, &input_vals)?);
}
if exec.is_remote() {
let url = exec.url.as_deref().unwrap().trim();
let hash = exec.sha256.as_deref().unwrap().trim();
let mut opts = remote::FetchOpts::new();
if let Some(ttl) = exec.ttl {
opts = opts.with_ttl(ttl);
}
let cached = remote::fetch_verified(url, hash, &opts, true)?;
argv.push(cached.to_string_lossy().into_owned());
} else if exec.is_local_file() {
let rel = exec.file.as_deref().unwrap().trim();
let use_root = Path::new(&ctx.spec_root.spec_dir);
let resolved = spec_load::resolve_under_use_root(use_root, rel)?;
if let Some(hash) = exec.sha256.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
remote::verify_file_sha256(&resolved, hash)
.with_context(|| format!("verify exec.file `{rel}`"))?;
}
argv.push(resolved.to_string_lossy().into_owned());
} else if argv.is_empty() {
bail!("exec.argv must not be empty");
}
if exec.passthrough {
let mut rest = rest;
if rest.first().is_some_and(|a| a == "--") {
rest = rest[1..].to_vec();
}
if shell_inline_c_needs_argv0(&argv) {
argv.push(shell_passthrough_argv0(chain));
}
for a in &rest {
argv.push(a.to_string_lossy().into_owned());
}
} else if !rest.is_empty() {
let preview = rest
.iter()
.take(3)
.map(|s| s.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ");
bail!(
"unexpected trailing arguments: {preview}{}",
if rest.len() > 3 { "…" } else { "" }
);
}
let cmd_path = if chain.is_empty() {
"(root)".to_string()
} else {
chain.join(" ")
};
let (_, requires, _) = deps::collect_chain_metadata(chain, spec);
deps::check_requires(&requires)?;
let pkgs = packages::collect_chain_packages(chain, spec);
let uv_env = packages::ensure_packages(&pkgs, ctx)?;
let path_dirs = deps::resolve_path_prefixes(spec, chain, ctx)?;
let program = packages::resolve_program_with_uv(&argv[0], uv_env.as_ref(), &path_dirs)?;
let mut env_spec = deps::collect_chain_env(chain, spec);
for value in env_spec.public.values_mut() {
*value = inputs::interpolate(value, &input_vals)?;
}
deps::check_private_env(&env_spec.private)?;
let mut path_override = if !path_dirs.is_empty() {
Some(deps::prepend_path_env(&path_dirs)?)
} else {
None
};
if let Some(ref uv) = uv_env {
path_override = Some(packages::prepend_uv_path(uv, path_override)?);
}
let mut c = Command::new(&program);
if argv.len() > 1 {
c.args(&argv[1..]);
}
c.current_dir(ctx.cwd);
deps::apply_process_env(&mut c, &env_spec, path_override)?;
let status = c.status().with_context(|| format!("spawn `{}`", argv[0]))?;
let code = status.code().unwrap_or(255);
if !ctx.no_log {
if let Some(db) = ctx.db_path {
log_invocation(
db,
&ctx.branch,
ctx.cwd,
&cmd_path,
&argv,
code,
ctx.spec_root,
)?;
}
}
Ok(code)
}
fn ensure_invocations_spec_root_column(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("PRAGMA table_info(invocations)")?;
let cols: Vec<String> = stmt
.query_map([], |row| row.get::<_, String>(1))?
.collect::<std::result::Result<_, _>>()?;
if !cols.iter().any(|c| c == "spec_root_id") {
conn.execute(
"ALTER TABLE invocations ADD COLUMN spec_root_id INTEGER",
[],
)?;
}
Ok(())
}
fn upsert_spec_root(conn: &Connection, spec: &SpecRootIdentity) -> Result<i64> {
let ts = unix_ts();
conn.execute(
r"INSERT INTO spec_roots (spec_dir, root_yaml, last_used_ts) VALUES (?1, ?2, ?3)
ON CONFLICT(spec_dir, root_yaml) DO UPDATE SET last_used_ts = excluded.last_used_ts",
rusqlite::params![&spec.spec_dir, &spec.root_yaml, &ts],
)?;
let id: i64 = conn.query_row(
"SELECT id FROM spec_roots WHERE spec_dir = ?1 AND root_yaml = ?2",
[&spec.spec_dir, &spec.root_yaml],
|r| r.get(0),
)?;
Ok(id)
}
fn log_invocation(
db_path: &Path,
branch: &str,
cwd: &Path,
command_path: &str,
argv: &[String],
exit_code: i32,
spec_root: &SpecRootIdentity,
) -> Result<()> {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent).ok();
}
let conn = Connection::open(db_path).with_context(|| format!("open {}", db_path.display()))?;
conn.execute_batch(
r"
CREATE TABLE IF NOT EXISTS spec_roots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
spec_dir TEXT NOT NULL,
root_yaml TEXT NOT NULL,
last_used_ts TEXT NOT NULL,
UNIQUE(spec_dir, root_yaml)
);
CREATE TABLE IF NOT EXISTS invocations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
git_branch TEXT NOT NULL,
cwd TEXT NOT NULL,
command_path TEXT NOT NULL,
argv_json TEXT NOT NULL,
exit_code INTEGER NOT NULL,
spec_root_id INTEGER
);
",
)?;
ensure_invocations_spec_root_column(&conn)?;
let spec_root_id = upsert_spec_root(&conn, spec_root)?;
let ts = unix_ts();
let argv_json = serde_json::to_string(argv).unwrap_or_else(|_| "[]".to_string());
let cwd_s = cwd.to_string_lossy();
conn.execute(
"INSERT INTO invocations (ts, git_branch, cwd, command_path, argv_json, exit_code, spec_root_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
rusqlite::params![
ts,
branch,
cwd_s.as_ref(),
command_path,
argv_json,
exit_code,
spec_root_id
],
)?;
Ok(())
}
fn unix_ts() -> String {
use std::time::SystemTime;
SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
.to_string()
}
#[derive(Debug)]
pub struct MatchOutcome<'a> {
pub chain: Vec<String>,
pub node: Option<&'a CommandNode>,
pub trailing: Vec<OsString>,
pub wants_help: bool,
}
pub fn match_commands<'a>(spec: &'a RootSpec, args: &[OsString]) -> MatchOutcome<'a> {
let mut chain = Vec::new();
let mut node: Option<&'a CommandNode> = None;
let mut map: &BTreeMap<String, CommandNode> = &spec.commands;
let mut i = 0usize;
let len = args.len();
while i < len {
let raw = &args[i];
if raw == "--help" || raw == "-h" {
return MatchOutcome {
chain,
node,
trailing: args[i + 1..].to_vec(),
wants_help: true,
};
}
let key = raw.to_string_lossy();
if let Some(next) = map.get(key.as_ref()) {
chain.push(key.into_owned());
node = Some(next);
map = &next.commands;
i += 1;
continue;
}
break;
}
MatchOutcome {
chain,
node,
trailing: args[i..].to_vec(),
wants_help: false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn examples_default_spec_validates() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/default.spec.yaml");
load_spec(&path).unwrap();
}
#[test]
fn merge_specs_adds_and_replaces_leaves() {
let mut base = load_spec_from_str(
r"
commands:
a:
about: base
commands:
x:
about: old
exec:
argv: [echo, old]
",
None,
)
.unwrap();
let overlay = load_spec_from_str(
r"
commands:
a:
commands:
x:
about: new leaf
exec:
argv: [echo, new]
b:
about: added top
exec:
argv: [echo, b]
",
None,
)
.unwrap();
merge_specs_into(&mut base, overlay).unwrap();
base.commands["a"].commands["x"].validate("a x").unwrap();
assert_eq!(
base.commands["a"].commands["x"].exec.as_ref().unwrap().argv,
vec!["echo", "new"]
);
assert_eq!(
base.commands["b"].exec.as_ref().unwrap().argv,
vec!["echo", "b"]
);
}
#[test]
fn validate_rejects_exec_with_children() {
let mut tmp = tempfile::NamedTempFile::with_suffix(".yaml").unwrap();
write!(
tmp,
r"
commands:
x:
exec:
argv: [echo]
commands:
child:
about: nested
"
)
.unwrap();
let err = load_spec(tmp.path()).unwrap_err();
assert!(err.to_string().contains("cannot define both"));
}
#[test]
fn shell_inline_c_needs_argv0_detects_bash_lc() {
let argv = vec![
"bash".into(),
"-lc".into(),
"case \"$1\" in create) ;; esac".into(),
];
assert!(shell_inline_c_needs_argv0(&argv));
let with_placeholder = vec![
"zsh".into(),
"-c".into(),
"echo".into(),
"issue".into(),
];
assert!(!shell_inline_c_needs_argv0(&with_placeholder));
assert!(!shell_inline_c_needs_argv0(&[
"echo".into(),
"start".into()
]));
assert!(!shell_inline_c_needs_argv0(&[
"python3".into(),
"-c".into(),
"print(1)".into()
]));
}
#[test]
fn shell_passthrough_argv0_skips_run_leaf() {
assert_eq!(
shell_passthrough_argv0(&["scripts".into(), "misc".into(), "issue".into(), "run".into()]),
"issue"
);
assert_eq!(shell_passthrough_argv0(&["probe".into()]), "probe");
}
}
pub fn default_db_path() -> PathBuf {
if let Ok(p) = std::env::var("JAN_DB") {
return PathBuf::from(p);
}
dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("jan-cli")
.join("audit.db")
}