use crate::codegen;
use crate::names::Meta;
use crate::render::{self, Ctx};
use crate::spec::{Run, Spec, Step};
use crate::templates::TEMPLATES;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::collections::BTreeSet;
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StackDef {
#[serde(default)]
pub id: String,
pub about: String,
pub kind: String,
#[serde(default)]
pub codegen: String,
#[serde(default)]
pub include: Vec<String>,
#[serde(default)]
pub commands: bool,
#[serde(default)]
pub mcp: bool,
#[serde(default)]
pub brief: String,
#[serde(default)]
pub run: Run,
#[serde(default, rename = "step")]
pub steps: Vec<Step>,
#[serde(default)]
pub stubs: Vec<String>,
#[serde(default)]
pub sources: Vec<String>,
#[serde(default, rename = "format")]
pub formats: Vec<Format>,
#[serde(default)]
pub install: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Format {
pub ext: String,
pub run: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
Shell,
Seed,
}
#[derive(Debug, Clone)]
pub struct GenFile {
pub path: String,
pub text: String,
pub owner: Owner,
}
pub fn all() -> Vec<(String, String)> {
let mut ids = BTreeSet::new();
for (path, _) in TEMPLATES {
if let Some((id, rest)) = path.split_once('/')
&& rest == "stack.toml"
&& !id.starts_with('_')
{
ids.insert(id.to_string());
}
}
ids.into_iter()
.map(|id| {
let about = raw_def(&id).map(|d| format!("[{}] {}", d.kind, d.about)).unwrap_or_default();
(id, about)
})
.collect()
}
fn template(path: &str) -> Option<&'static str> {
TEMPLATES.iter().find(|(p, _)| *p == path).map(|(_, t)| *t)
}
fn raw_def(id: &str) -> Result<StackDef> {
let text = template(&format!("{id}/stack.toml")).with_context(|| unknown(id))?;
let mut def: StackDef = toml::from_str(text).with_context(|| format!("templates/{id}/stack.toml"))?;
def.id = id.to_string();
Ok(def)
}
fn unknown(id: &str) -> String {
let ids: Vec<String> = all().into_iter().map(|(id, _)| id).collect();
format!("no stack {id:?}; there's {}", ids.join(", "))
}
pub fn load(spec: &Spec) -> Result<StackDef> {
let ctx = codegen::base(spec, &Meta::of(spec));
load_with(&spec.stack, &ctx)
}
fn load_with(id: &str, ctx: &Ctx) -> Result<StackDef> {
let text = template(&format!("{id}/stack.toml")).with_context(|| unknown(id))?;
let rendered = render::render(text, ctx).with_context(|| format!("templates/{id}/stack.toml"))?;
let mut def: StackDef = toml::from_str(&rendered).with_context(|| format!("templates/{id}/stack.toml"))?;
def.id = id.to_string();
Ok(def)
}
pub fn files(spec: &Spec) -> Result<(StackDef, Vec<GenFile>)> {
let meta = Meta::of(spec);
let base = codegen::base(spec, &meta);
let def = load_with(&spec.stack, &base)?;
let ctx = codegen::slots(spec, &meta, &def, base)?;
let mut out: Vec<GenFile> = Vec::new();
let mut folders = def.include.clone();
folders.push(def.id.clone());
for folder in &folders {
let prefix = format!("{folder}/");
if !TEMPLATES.iter().any(|(p, _)| p.starts_with(&prefix)) {
bail!("stack {} includes {folder:?}, which isn't a template folder", def.id);
}
for (path, text) in TEMPLATES.iter().filter(|(p, _)| p.starts_with(&prefix)) {
let rest = &path[prefix.len()..];
let Some((kind, rel)) = rest.split_once('/') else { continue };
let render_one = |ctx: &Ctx| render::render(text, ctx).with_context(|| format!("templates/{path}"));
match kind {
"shell" | "seed" => {
let owner = if kind == "shell" { Owner::Shell } else { Owner::Seed };
out.push(GenFile { path: render::path(rel, &ctx, None), text: render_one(&ctx)?, owner });
}
"command" => {
for c in &spec.commands {
let mut cctx = ctx.clone();
codegen::command_slots(spec, c, &mut cctx);
out.push(GenFile {
path: render::path(rel, &cctx, Some(&c.module())),
text: render_one(&cctx)?,
owner: Owner::Seed,
});
}
}
_ => {}
}
}
}
out.push(GenFile { path: "docs/logo.svg".into(), text: crate::logo::svg(&meta), owner: Owner::Seed });
let mut seen = BTreeSet::new();
out.reverse();
out.retain(|f| seen.insert(f.path.clone()));
out.reverse();
Ok((def, out))
}
#[cfg(test)]
mod tests {
use super::*;
fn spec(stack: &str) -> Spec {
let commands = if stack.ends_with("-cli") {
r#"
[[command]]
name = "list-all"
about = "List them all"
[[command.arg]]
name = "path"
kind = "path"
positional = true
default = "."
[[command.arg]]
name = "tag"
kind = "list"
default = "TODO,FIXME"
[[command.arg]]
name = "max"
kind = "int"
[[command.arg]]
name = "loud"
kind = "bool"
[[command.arg]]
name = "ratio"
kind = "float"
default = "0.5"
[[command]]
name = "show"
about = "Show one"
[[command.arg]]
name = "id"
kind = "string"
positional = true
required = true
"#
} else {
""
};
Spec::parse(&format!(
"name = \"probe-anything\"\npitch = \"Probes \\\"anything\\\".\"\nstack = \"{stack}\"\nowner = \"someone\"\n{commands}"
))
.unwrap()
}
#[test]
fn every_stack_renders() {
let ids = all();
assert!(ids.len() >= 5, "{ids:?}");
for (id, about) in ids {
assert!(!about.is_empty(), "{id} has no about");
let (def, files) = files(&spec(&id)).unwrap_or_else(|e| panic!("{id}: {e:#}"));
assert_eq!(def.id, id);
assert!(files.iter().any(|f| f.path == "README.md"), "{id} has no README");
assert!(
files
.iter()
.all(|f| ["__name__", "__verb__", "__snake__", "__command__"].iter().all(|p| !f.path.contains(p))),
"{id}: unrendered path"
);
if def.commands {
assert!(files.iter().any(|f| f.path.contains("list_all")), "{id}: no command file");
assert!(!def.run.cmd.is_empty(), "{id}: a CLI stack needs [run] cmd");
}
}
}
}