use std::fs;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use anyhow::{bail, Context, Result};
use crate::config::SastriConfig;
use crate::engine::{registry, MechanismContext};
use crate::tui::{self, ProgressState};
pub struct GenerateOptions {
pub config: SastriConfig,
pub root: PathBuf,
pub only: Option<Vec<String>>,
pub use_tui: bool,
pub force: bool,
}
pub fn generate(opts: GenerateOptions) -> Result<()> {
let root = opts.root.canonicalize().unwrap_or(opts.root.clone());
let mechs: Vec<_> = registry::all()
.into_iter()
.filter(|m| {
if let Some(ref only) = opts.only {
only.iter().any(|id| id == m.id())
} else {
opts.config.mechanism_enabled(m.id())
}
})
.collect();
if mechs.is_empty() {
bail!("no mechanisms selected — enable some in Sastri.toml or pass --only");
}
let names: Vec<String> = mechs.iter().map(|m| m.id().to_string()).collect();
let written = Arc::new(Mutex::new(Vec::<String>::new()));
let notes = Arc::new(Mutex::new(Vec::<String>::new()));
let idx = Arc::new(Mutex::new(0usize));
let run_one = |i: usize| -> Result<()> {
let m = mechs[i];
let ctx = MechanismContext {
config: &opts.config,
root: &root,
force: opts.force,
};
let result = m
.generate(&ctx)
.with_context(|| format!("mechanism {}", m.id()))?;
for file in result.files {
write_file(
&root,
&file.relative_path,
&file.contents,
file.executable,
opts.force,
)?;
written
.lock()
.unwrap()
.push(format!("{} ({})", file.relative_path, m.id()));
}
notes.lock().unwrap().extend(result.notes);
Ok(())
};
if opts.use_tui && std::io::IsTerminal::is_terminal(&std::io::stdout()) {
let names_c = names.clone();
let idx_c = Arc::clone(&idx);
let written_c = Arc::clone(&written);
tui::run_progress(move |state: &mut ProgressState| {
state.total = names_c.len();
let i = *idx_c.lock().unwrap();
if i >= names_c.len() {
state.done = names_c.len();
state.current = "done".into();
state.log = written_c.lock().unwrap().clone();
return Ok(true);
}
state.current = names_c[i].clone();
state.done = i;
state.log = written_c.lock().unwrap().clone();
run_one(i)?;
*idx_c.lock().unwrap() += 1;
state.done = i + 1;
state.log = written_c.lock().unwrap().clone();
Ok(false)
})?;
} else {
tui::run_spinner_list(&names, run_one)?;
}
println!("\ngenerated into {}", root.display());
for line in written.lock().unwrap().iter() {
println!(" + {line}");
}
let n = notes.lock().unwrap();
if !n.is_empty() {
println!("\nnext steps:");
for note in n.iter() {
println!(" • {note}");
}
}
Ok(())
}
fn write_file(
root: &Path,
relative: &str,
contents: &str,
executable: bool,
force: bool,
) -> Result<()> {
let path = root.join(relative);
if path.exists() && !force {
bail!("{} exists (pass --force to overwrite)", path.display());
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, contents).with_context(|| format!("write {}", path.display()))?;
if executable {
let mut perms = fs::metadata(&path)?.permissions();
#[cfg(unix)]
{
perms.set_mode(0o755);
fs::set_permissions(&path, perms)?;
}
#[cfg(not(unix))]
{
let _ = &mut perms;
}
}
Ok(())
}