use std::path::{Path, PathBuf};
use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};
use crate::error::Result;
pub(crate) fn project_file_id(name: &str) -> FileId {
let vpath = VirtualPath::new(name)
.unwrap_or_else(|_| VirtualPath::new("main.typ").expect("static path is valid"));
FileId::new(RootedPath::new(VirtualRoot::Project, vpath))
}
pub enum TemplateSource {
FilePath(PathBuf),
InMemory {
content: String,
root: Option<PathBuf>,
},
}
#[derive(Clone)]
pub struct PreparedTemplate {
pub(crate) source: Source,
pub(crate) root: Option<PathBuf>,
}
impl PreparedTemplate {
pub fn new(template: TemplateSource) -> Result<Self> {
match template {
TemplateSource::FilePath(path) => {
let content = std::fs::read_to_string(&path)?;
let file_name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("main.typ");
let id = project_file_id(file_name);
let source = Source::new(id, content);
let root = path.parent().map(Path::to_path_buf);
Ok(Self { source, root })
}
TemplateSource::InMemory { content, root } => {
let id = project_file_id("main.typ");
let source = Source::new(id, content);
Ok(Self { source, root })
}
}
}
}