use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct TemplateContext {
base_dir: Arc<PathBuf>,
trust_mode: bool,
}
impl TemplateContext {
pub fn new(base_dir: PathBuf, trust_mode: bool) -> Self {
Self {
base_dir: Arc::new(base_dir),
trust_mode,
}
}
pub fn from_template_file(template_path: &str, trust_mode: bool) -> std::io::Result<Self> {
let path = Path::new(template_path);
let base_dir = path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let canonical = std::fs::canonicalize(&base_dir)?;
Ok(Self::new(canonical, trust_mode))
}
pub fn from_stdin(trust_mode: bool) -> std::io::Result<Self> {
let cwd = std::env::current_dir()?;
Ok(Self::new(cwd, trust_mode))
}
pub fn base_dir(&self) -> &Path {
&self.base_dir
}
pub fn is_trust_mode(&self) -> bool {
self.trust_mode
}
pub fn resolve_path(&self, path: &str) -> PathBuf {
let path_obj = Path::new(path);
if path_obj.is_absolute() {
path_obj.to_path_buf()
} else {
self.base_dir.join(path)
}
}
}