use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::io::{InputProvider, OpenResult, ProviderStack};
pub const DOCUMENT_FILE: &str = "Texrs.toml";
pub const BUILD_DIR: &str = "build";
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputType {
Messages,
Tokens,
Disasm,
}
impl OutputType {
pub fn extension(self) -> &'static str {
match self {
OutputType::Messages => "txt",
OutputType::Tokens => "tokens",
OutputType::Disasm => "disasm",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Output {
pub name: String,
#[serde(rename = "type")]
pub kind: OutputType,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocSection {
pub name: String,
#[serde(default)]
pub preamble: Vec<String>,
#[serde(default = "default_inputs")]
pub inputs: Vec<String>,
#[serde(default)]
pub extra_paths: Vec<PathBuf>,
#[serde(default)]
pub bundle: Option<PathBuf>,
#[serde(default)]
pub metadata: Option<toml::Value>,
}
fn default_inputs() -> Vec<String> {
vec!["index.tex".to_string()]
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocumentFile {
pub doc: DocSection,
#[serde(rename = "output", default)]
pub outputs: Vec<Output>,
}
#[derive(Clone, Debug)]
pub struct Document {
pub src_dir: PathBuf,
pub build_dir: PathBuf,
pub file: DocumentFile,
}
#[derive(Debug)]
pub struct Built {
pub profile: String,
pub path: PathBuf,
pub inputs: Vec<crate::io::InputRecord>,
}
impl Document {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let src_dir = dir.as_ref().to_path_buf();
let path = src_dir.join(DOCUMENT_FILE);
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
Self::parse(&src_dir, &text)
}
pub fn parse(src_dir: impl AsRef<Path>, text: &str) -> Result<Self, String> {
let file: DocumentFile =
toml::from_str(text).map_err(|e| format!("{DOCUMENT_FILE}: {e}"))?;
if file.doc.name.trim().is_empty() {
return Err(format!("{DOCUMENT_FILE}: the document needs a name"));
}
if file.doc.inputs.is_empty() {
return Err(format!("{DOCUMENT_FILE}: the document needs an input"));
}
if file.outputs.is_empty() {
return Err(format!("{DOCUMENT_FILE}: the document needs an output"));
}
let mut seen = BTreeMap::new();
for output in &file.outputs {
if seen.insert(output.name.clone(), ()).is_some() {
return Err(format!(
"{DOCUMENT_FILE}: two outputs are named {:?}",
output.name
));
}
}
let src_dir = src_dir.as_ref().to_path_buf();
Ok(Document {
build_dir: src_dir.join(BUILD_DIR),
src_dir,
file,
})
}
pub fn find_from(start: impl AsRef<Path>) -> Result<Self, String> {
let mut at = start.as_ref().to_path_buf();
if at.is_file() {
at.pop();
}
loop {
if at.join(DOCUMENT_FILE).is_file() {
return Self::open(&at);
}
if !at.pop() {
return Err(format!(
"no {DOCUMENT_FILE} here or in any directory above it"
));
}
}
}
pub fn profile(&self, name: Option<&str>) -> Result<&Output, String> {
match name {
Some(name) => self
.file
.outputs
.iter()
.find(|o| o.name == name)
.ok_or_else(|| {
let known: Vec<&str> =
self.file.outputs.iter().map(|o| o.name.as_str()).collect();
format!("no output named {name:?}; this document has {known:?}")
}),
None if self.file.outputs.len() == 1 => Ok(&self.file.outputs[0]),
None => self
.file
.outputs
.iter()
.find(|o| o.name == "default")
.ok_or_else(|| {
"this document has several outputs and none is `default`; \
name one with --profile"
.to_string()
}),
}
}
pub fn bundle_path(&self, bundle: &Path) -> Result<PathBuf, String> {
let name = bundle.to_string_lossy();
let digest = if let Some(digest) = name.strip_prefix("sha256:") {
digest.to_string()
} else if name.starts_with("https://") || name.starts_with("http://") {
return Err(format!(
"{name} is a URL: fetch it with `texrs -X bundle fetch {name}`, \
then name the bundle it prints as sha256:<digest>"
));
} else {
return Ok(match bundle.is_absolute() {
true => bundle.to_path_buf(),
false => self.src_dir.join(bundle),
});
};
let path = crate::geturl::path_for(&digest).ok_or("no cache directory")?;
if !path.is_file() {
return Err(format!(
"the bundle sha256:{digest} is not in the cache; \
fetch it with `texrs -X bundle fetch <url>`"
));
}
Ok(path)
}
fn format_path(&self, digests: &[String]) -> Option<PathBuf> {
let key = crate::script_cache::document_key(digests, "preamble");
let cache = crate::script_cache::default_cache_path();
let dir = cache.parent()?.join("formats");
Some(dir.join(format!("{}.fmt", key.trim_start_matches("doc:"))))
}
pub fn assemble(&self) -> Result<(String, Vec<crate::io::InputRecord>), String> {
self.read(&self.file.doc.inputs)
}
pub fn assemble_preamble(
&self,
) -> Result<Option<(String, Vec<crate::io::InputRecord>)>, String> {
if self.file.doc.preamble.is_empty() {
return Ok(None);
}
self.read(&self.file.doc.preamble).map(Some)
}
fn read(&self, names: &[String]) -> Result<(String, Vec<crate::io::InputRecord>), String> {
let mut roots = vec![self.src_dir.clone()];
roots.extend(self.file.doc.extra_paths.iter().map(|p| {
if p.is_absolute() {
p.clone()
} else {
self.src_dir.join(p)
}
}));
let mut stack = ProviderStack::new();
stack.push(Box::new(crate::io::FilesystemProvider::with_roots(roots)));
if let Some(bundle) = &self.file.doc.bundle {
stack.push(Box::new(crate::bundle::Bundle::open(
self.bundle_path(bundle)?,
)?));
}
let mut source = String::new();
for name in names {
match stack.input_open(name) {
OpenResult::Ok(input) => {
source.push_str(&input.content);
if !input.content.ends_with('\n') {
source.push('\n');
}
}
OpenResult::NotAvailable => {
return Err(format!("input {name:?} is not in this document"))
}
OpenResult::Err(e) => return Err(format!("input {name:?}: {e}")),
}
}
Ok((source, stack.inputs_read().to_vec()))
}
pub fn build(&self, profile: Option<&str>) -> Result<Built, String> {
let output = self.profile(profile)?.clone();
let (source, inputs) = self.assemble()?;
let body = self.render(&output, &source, &inputs)?;
std::fs::create_dir_all(&self.build_dir)
.map_err(|e| format!("cannot make {}: {e}", self.build_dir.display()))?;
let path = self.build_dir.join(format!(
"{}.{}",
self.file.doc.name,
output.kind.extension()
));
let mut text = body;
if !text.ends_with('\n') {
text.push('\n');
}
std::fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
Ok(Built {
profile: output.name,
path,
inputs,
})
}
}
impl Document {
pub fn show(&self) -> String {
let mut out = String::new();
out.push_str(&format!("name {}\n", self.file.doc.name));
out.push_str(&format!("source {}\n", self.src_dir.display()));
out.push_str(&format!("build {}\n", self.build_dir.display()));
for path in &self.file.doc.extra_paths {
out.push_str(&format!("extra path {}\n", path.display()));
}
if let Some(bundle) = &self.file.doc.bundle {
out.push_str(&format!("bundle {}\n", bundle.display()));
}
out.push_str("\ninputs\n");
match self.assemble() {
Ok((_, read)) => {
for record in read {
out.push_str(&format!(
" {} {}\n",
&record.digest[..12.min(record.digest.len())],
record.name
));
}
}
Err(e) => out.push_str(&format!(" (cannot be read: {e})\n")),
}
out.push_str("\noutputs\n");
for output in &self.file.outputs {
out.push_str(&format!(
" {:<12} {:?} → {}.{}\n",
output.name,
output.kind,
self.file.doc.name,
output.kind.extension()
));
}
out
}
pub fn dump(&self, profile: Option<&str>) -> Result<String, String> {
let output = self.profile(profile)?.clone();
let (source, inputs) = self.assemble()?;
self.render(&output, &source, &inputs)
}
fn render(
&self,
output: &Output,
source: &str,
inputs: &[crate::io::InputRecord],
) -> Result<String, String> {
if output.kind == OutputType::Tokens {
let cats = crate::catcode::CatTable::new();
let mut lexer = crate::lexer::Lexer::new(source);
let mut out = String::new();
while let Some(token) = lexer.next_token(&cats) {
out.push_str(&format!("{token:?}\n"));
}
return Ok(out);
}
let digests: Vec<String> = inputs.iter().map(|r| r.digest.clone()).collect();
let profile = match crate::lua::explicit_jobname() {
Some(job) => format!("{}#jobname={job}", output.name),
None => output.name.clone(),
};
let key = crate::script_cache::document_key(&digests, &profile);
let chunk = match crate::script_cache::try_load_keyed(&key) {
Some(chunk) => chunk,
None => {
let chunk = self.compile_with_format(source)?;
crate::script_cache::store_keyed(&key, &chunk);
chunk
}
};
match output.kind {
OutputType::Disasm => Ok(chunk.disassemble()),
_ => Ok(crate::runtime::run(chunk)?.join(" ")),
}
}
}
impl Document {
pub fn compile_with_format(&self, source: &str) -> Result<fusevm::Chunk, String> {
let Some((preamble_source, preamble_inputs)) = self.assemble_preamble()? else {
return crate::compile(source).map_err(|e| e.0);
};
let digests: Vec<String> = preamble_inputs.iter().map(|r| r.digest.clone()).collect();
let path = self.format_path(&digests);
let mut lowerer = crate::lower::Lowerer::new();
let loaded = path
.as_deref()
.and_then(crate::format::Format::load)
.map(|format| {
let mark = format.apply(&mut lowerer.eng);
lowerer.set_scratch_mark(mark);
})
.is_some();
if !loaded {
let commands = lowerer
.lower(&preamble_source)
.map_err(|e| format!("preamble: {}", e.0))?;
if !commands.is_empty() {
let whole = format!("{preamble_source}{source}");
return crate::compile(&whole).map_err(|e| e.0);
}
if let Some(path) = &path {
let mark = lowerer.scratch_mark();
let format = crate::format::Format::capture(&lowerer.eng, mark);
let _ = format.save(path);
}
}
let commands = lowerer.lower(source).map_err(|e| e.0)?;
crate::compiler::Compiler::new()
.compile(&commands)
.map_err(|e| e.0)
}
}
pub const WATCH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250);
impl Document {
pub fn watch(
&self,
profile: Option<&str>,
interval: std::time::Duration,
status: &mut dyn crate::status::StatusBackend,
stop: &dyn Fn() -> bool,
) -> Result<usize, String> {
let profile = self.profile(profile)?.name.clone();
let mut builds = 0usize;
let mut last: Option<Vec<crate::io::InputRecord>> = None;
while !stop() {
let (_, current) = match self.assemble() {
Ok(v) => v,
Err(e) => {
status.warning(&e);
std::thread::sleep(interval);
continue;
}
};
let changed = last.as_ref().is_none_or(|previous| {
previous.len() != current.len()
|| previous
.iter()
.zip(¤t)
.any(|(a, b)| a.digest != b.digest || a.name != b.name)
});
if changed {
match self.build(Some(&profile)) {
Ok(built) => {
builds += 1;
status.note(&format!(
"built {} from {} input(s) → {}",
built.profile,
built.inputs.len(),
built.path.display()
));
}
Err(e) => status.error(&e),
}
last = Some(current);
}
std::thread::sleep(interval);
}
Ok(builds)
}
}
pub fn scaffold(dir: impl AsRef<Path>, name: &str) -> Result<PathBuf, String> {
let dir = dir.as_ref();
let path = dir.join(DOCUMENT_FILE);
if path.exists() {
return Err(format!("{} already exists", path.display()));
}
std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
let document = format!(
"# What this document is made of, and what comes out of it.\n\
# `texrs -X build` reads this; see texrs(1).\n\
[doc]\n\
name = {name:?}\n\
inputs = [\"index.tex\"]\n\
\n\
[[output]]\n\
name = \"default\"\n\
type = \"messages\"\n"
);
std::fs::write(&path, document).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
let index = dir.join("index.tex");
if !index.exists() {
let body = "% INITEX leaves `{` and `}` ordinary, so a document that wants\n\
% groups says so first.\n\
\\catcode`\\{=1 \\catcode`\\}=2\n\
\n\
\\message{hello from texrs}\n\
\\end\n";
std::fs::write(&index, body)
.map_err(|e| format!("cannot write {}: {e}", index.display()))?;
}
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
fn without_the_shared_cache() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| std::env::set_var("TEXRS_CACHE", "0"));
}
fn scratch(name: &str) -> PathBuf {
without_the_shared_cache();
let dir = std::env::temp_dir().join(format!("texrs_doc_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
const HELLO: &str = "\\catcode`\\{=1 \\catcode`\\}=2 \\message{HI}\n\\end\n";
#[test]
fn a_document_file_says_what_it_is_made_of() {
let dir = scratch("parse");
let doc = Document::parse(
&dir,
r#"
[doc]
name = "thesis"
inputs = ["macros.tex", "body.tex"]
[[output]]
name = "default"
type = "messages"
[[output]]
name = "bytecode"
type = "disasm"
"#,
)
.expect("parses");
assert_eq!(doc.file.doc.name, "thesis");
assert_eq!(doc.file.doc.inputs, vec!["macros.tex", "body.tex"]);
assert_eq!(doc.build_dir, dir.join("build"));
assert_eq!(
doc.profile(Some("bytecode")).unwrap().kind,
OutputType::Disasm
);
assert_eq!(doc.profile(None).unwrap().name, "default");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_document_that_cannot_be_built_is_refused_rather_than_half_read() {
let dir = scratch("refuse");
let cases = [
("[doc]\nname = \"\"\ninputs = [\"a.tex\"]\n[[output]]\nname=\"d\"\ntype=\"messages\"\n", "needs a name"),
("[doc]\nname = \"x\"\ninputs = []\n[[output]]\nname=\"d\"\ntype=\"messages\"\n", "needs an input"),
("[doc]\nname = \"x\"\n", "needs an output"),
(
"[doc]\nname=\"x\"\n[[output]]\nname=\"d\"\ntype=\"messages\"\n[[output]]\nname=\"d\"\ntype=\"tokens\"\n",
"two outputs are named",
),
("[doc]\nname=\"x\"\n[[output]]\nname=\"d\"\ntype=\"pdf\"\n", "unknown variant"),
];
for (text, expected) in cases {
let err = Document::parse(&dir, text).unwrap_err();
assert!(err.contains(expected), "{text:?} gave {err:?}");
}
let doc = Document::parse(
&dir,
"[doc]\nname=\"x\"\n[[output]]\nname=\"only\"\ntype=\"messages\"\n",
)
.unwrap();
let err = doc.profile(Some("nope")).unwrap_err();
assert!(
err.contains("no output named") && err.contains("only"),
"{err}"
);
assert_eq!(doc.profile(None).unwrap().name, "only");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_document_is_found_by_walking_up() {
let dir = scratch("find");
let nested = dir.join("chapters/one");
std::fs::create_dir_all(&nested).unwrap();
scaffold(&dir, "thesis").unwrap();
let found = Document::find_from(&nested).expect("found from below");
assert_eq!(found.file.doc.name, "thesis");
assert_eq!(found.src_dir, dir);
let found = Document::find_from(dir.join("index.tex")).expect("found from a file");
assert_eq!(found.src_dir, dir);
let empty = scratch("find_none");
assert!(Document::find_from(&empty)
.unwrap_err()
.contains("no Texrs.toml"));
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&empty);
}
#[test]
fn several_inputs_are_read_in_order_and_recorded() {
let dir = scratch("assemble");
std::fs::write(dir.join("macros.tex"), "\\catcode`\\{=1 \\catcode`\\}=2\n").unwrap();
std::fs::write(dir.join("body.tex"), "\\message{FROM-BODY}\n\\end").unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"multi\"\ninputs=[\"macros.tex\",\"body.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let (source, read) = doc.assemble().expect("assembles");
assert!(source.starts_with("\\catcode"), "{source}");
assert!(source.contains("FROM-BODY"), "{source}");
assert!(source.ends_with('\n'), "the join ends the last line");
assert_eq!(read.len(), 2, "both inputs are recorded");
assert_eq!(read[0].name, "macros.tex");
assert_eq!(read[1].digest.len(), 64);
let missing = Document::parse(
&dir,
"[doc]\nname=\"x\"\ninputs=[\"nope.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
assert!(missing.assemble().unwrap_err().contains("nope.tex"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_build_writes_what_the_profile_asked_for() {
let dir = scratch("build");
std::fs::write(dir.join("index.tex"), HELLO).unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"doc\"\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n\
[[output]]\nname=\"tok\"\ntype=\"tokens\"\n\
[[output]]\nname=\"bytes\"\ntype=\"disasm\"\n",
)
.unwrap();
let built = doc.build(None).expect("builds");
assert_eq!(built.profile, "default");
assert_eq!(built.path, dir.join("build/doc.txt"));
assert_eq!(std::fs::read_to_string(&built.path).unwrap().trim(), "HI");
assert_eq!(built.inputs.len(), 1, "what it read is reported");
let tokens = doc.build(Some("tok")).expect("builds");
assert!(std::fs::read_to_string(&tokens.path)
.unwrap()
.contains("Cs("));
let disasm = doc.build(Some("bytes")).expect("builds");
let listing = std::fs::read_to_string(&disasm.path).unwrap();
assert!(listing.starts_with("0000"), "{listing}");
assert!(listing.contains("LoadInt"), "{listing}");
assert_ne!(built.path, tokens.path);
assert_ne!(tokens.path, disasm.path);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_bundle_supplies_what_the_directory_does_not_and_yields_to_what_it_does() {
use std::io::Write;
let dir = scratch("bundle");
let bundle_path = dir.join("support.zip");
{
let mut zip = zip::ZipWriter::new(std::fs::File::create(&bundle_path).unwrap());
for (name, body) in [
(
"macros.tex",
"\\catcode`\\{=1 \\catcode`\\}=2 \\def\\who{BUNDLE}\n",
),
("extra.tex", "\\def\\extra{FROM-BUNDLE}\n"),
] {
zip.start_file(name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(body.as_bytes()).unwrap();
}
zip.finish().unwrap();
}
std::fs::write(
dir.join("macros.tex"),
"\\catcode`\\{=1 \\catcode`\\}=2 \\def\\who{BESIDE-THE-DOCUMENT}\n",
)
.unwrap();
std::fs::write(dir.join("index.tex"), "\\message{\\who\\extra}\n\\end\n").unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"b\"\nbundle=\"support.zip\"\n\
inputs=[\"macros.tex\",\"extra.tex\",\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let built = doc.build(None).expect("builds");
let output = std::fs::read_to_string(&built.path).unwrap();
assert!(output.contains("BESIDE-THE-DOCUMENT"), "{output}");
assert!(output.contains("FROM-BUNDLE"), "{output}");
assert!(!output.contains("BUNDLE\\"), "{output}");
let (_, read) = doc.assemble().unwrap();
let from_bundle = read.iter().find(|r| r.name == "extra.tex").unwrap();
assert_eq!(from_bundle.origin, crate::io::InputOrigin::Memory);
assert_eq!(from_bundle.path, None);
let beside = read.iter().find(|r| r.name == "macros.tex").unwrap();
assert_eq!(beside.origin, crate::io::InputOrigin::Filesystem);
assert!(
doc.show().contains("bundle support.zip"),
"{}",
doc.show()
);
let by_url = Document::parse(
&dir,
"[doc]\nname=\"b\"\nbundle=\"https://example.invalid/support.zip\"\n\
inputs=[\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let err = by_url.assemble().unwrap_err();
assert!(err.contains("-X bundle fetch"), "{err}");
let by_digest = Document::parse(
&dir,
"[doc]\nname=\"b\"\nbundle=\"sha256:0000000000000000\"\ninputs=[\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let err = by_digest.assemble().unwrap_err();
assert!(err.contains("not in the cache"), "{err}");
let broken = Document::parse(
&dir,
"[doc]\nname=\"b\"\nbundle=\"absent.zip\"\ninputs=[\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
assert!(broken.assemble().unwrap_err().contains("cannot read"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_preamble_is_compiled_once_and_applied_from_the_format_after() {
let dir = scratch("format");
std::fs::write(
dir.join("macros.tex"),
"\\catcode`\\{=1 \\catcode`\\}=2 \\catcode`\\#=6\n\\def\\greet#1{HELLO-#1}\n",
)
.unwrap();
std::fs::write(dir.join("index.tex"), "\\message{\\greet{WORLD}}\n\\end\n").unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"f\"\npreamble=[\"macros.tex\"]\ninputs=[\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
assert!(crate::compile("\\message{\\greet{WORLD}}\n\\end\n").is_err());
let built = doc.build(None).expect("builds with the preamble");
assert_eq!(
std::fs::read_to_string(&built.path).unwrap().trim(),
"HELLO-WORLD"
);
let (_, preamble_inputs) = doc.assemble_preamble().unwrap().unwrap();
let digests: Vec<String> = preamble_inputs.iter().map(|r| r.digest.clone()).collect();
let format_path = doc.format_path(&digests).expect("a cache directory");
assert!(
format_path.is_file(),
"the format was dumped: {format_path:?}"
);
assert!(crate::format::Format::load(&format_path).is_some());
let again = doc.dump(None).expect("builds from the format");
assert_eq!(again.trim(), "HELLO-WORLD");
let _ = std::fs::remove_file(&format_path);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_preamble_that_does_something_is_not_made_into_a_format() {
let dir = scratch("format_runtime");
std::fs::write(
dir.join("macros.tex"),
"\\catcode`\\{=1 \\catcode`\\}=2\n\\message{FROM-PREAMBLE}\n",
)
.unwrap();
std::fs::write(dir.join("index.tex"), "\\message{FROM-BODY}\n\\end\n").unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"r\"\npreamble=[\"macros.tex\"]\ninputs=[\"index.tex\"]\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let built = doc.build(None).expect("builds");
let output = std::fs::read_to_string(&built.path).unwrap();
assert!(output.contains("FROM-PREAMBLE"), "{output}");
assert!(output.contains("FROM-BODY"), "{output}");
let (_, inputs) = doc.assemble_preamble().unwrap().unwrap();
let digests: Vec<String> = inputs.iter().map(|r| r.digest.clone()).collect();
let path = doc.format_path(&digests).expect("a cache directory");
assert!(!path.exists(), "and nothing was dumped: {path:?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn showing_a_document_reads_it_rather_than_remembering_it() {
let dir = scratch("show");
std::fs::write(dir.join("index.tex"), HELLO).unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"shown\"\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n\
[[output]]\nname=\"bytes\"\ntype=\"disasm\"\n",
)
.unwrap();
let shown = doc.show();
assert!(shown.contains("name shown"), "{shown}");
assert!(shown.contains(&dir.display().to_string()), "{shown}");
assert!(shown.contains("index.tex"), "{shown}");
assert!(
shown.contains("default") && shown.contains("bytes"),
"{shown}"
);
assert!(
shown.contains("shown.disasm"),
"the file each profile writes: {shown}"
);
let before = shown.clone();
std::fs::write(dir.join("index.tex"), "\\message{OTHER}\n\\end\n").unwrap();
assert_ne!(doc.show(), before, "it reads the input, not a memory of it");
std::fs::remove_file(dir.join("index.tex")).unwrap();
assert!(doc.show().contains("cannot be read"), "{}", doc.show());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn dumping_produces_what_a_build_would_write_without_writing_it() {
let dir = scratch("dump");
std::fs::write(dir.join("index.tex"), HELLO).unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"d\"\n\
[[output]]\nname=\"default\"\ntype=\"messages\"\n\
[[output]]\nname=\"tok\"\ntype=\"tokens\"\n",
)
.unwrap();
assert_eq!(doc.dump(None).unwrap().trim(), "HI");
assert!(doc.dump(Some("tok")).unwrap().contains("Cs("));
assert!(
!dir.join("build").exists(),
"a dump writes nothing: the build directory was not made"
);
let built = doc.build(None).unwrap();
assert_eq!(
std::fs::read_to_string(&built.path).unwrap().trim(),
doc.dump(None).unwrap().trim()
);
assert!(doc
.dump(Some("nope"))
.unwrap_err()
.contains("no output named"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn watching_rebuilds_when_an_input_changes_and_not_otherwise() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
let dir = scratch("watch");
std::fs::write(dir.join("index.tex"), HELLO).unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let ticks = AtomicUsize::new(0);
let edited = dir.join("index.tex");
let stop = || {
let n = ticks.fetch_add(1, Ordering::SeqCst);
if n == 2 {
std::fs::write(
&edited,
"\\catcode`\\{=1 \\catcode`\\}=2 \\message{EDITED}\n\\end\n",
)
.unwrap();
}
n >= 4
};
let mut status = crate::status::CollectingStatus::new();
let builds = doc
.watch(None, Duration::from_millis(1), &mut status, &stop)
.expect("watches");
assert_eq!(builds, 2, "the first build, and the one the edit caused");
let output = std::fs::read_to_string(dir.join("build/w.txt")).unwrap();
assert_eq!(output.trim(), "EDITED", "the rebuild used the new content");
assert_eq!(
status
.messages()
.iter()
.filter(|(level, _)| *level == crate::status::Level::Note)
.count(),
2,
"one report per build: {:?}",
status.messages()
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn watching_survives_a_document_that_does_not_compile() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
let dir = scratch("watch_broken");
std::fs::write(dir.join("index.tex"), "\\undefined@thing\n").unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let ticks = AtomicUsize::new(0);
let fixed = dir.join("index.tex");
let stop = || {
let n = ticks.fetch_add(1, Ordering::SeqCst);
if n == 1 {
std::fs::write(&fixed, HELLO).unwrap();
}
n >= 3
};
let mut status = crate::status::CollectingStatus::new();
doc.watch(None, Duration::from_millis(1), &mut status, &stop)
.expect("keeps watching");
assert!(status.had_error(), "the failure is reported");
assert_eq!(
std::fs::read_to_string(dir.join("build/w.txt"))
.unwrap()
.trim(),
"HI",
"and the document that compiles is built"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn watching_refuses_a_profile_that_is_not_there_before_it_starts() {
let dir = scratch("watch_profile");
std::fs::write(dir.join("index.tex"), HELLO).unwrap();
let doc = Document::parse(
&dir,
"[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
)
.unwrap();
let mut status = crate::status::SilentStatus;
let err = doc
.watch(
Some("nope"),
std::time::Duration::from_millis(1),
&mut status,
&|| true,
)
.unwrap_err();
assert!(err.contains("no output named"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_scaffolded_document_builds_as_it_stands() {
let dir = scratch("scaffold");
let path = scaffold(&dir, "fresh").expect("scaffolds");
assert!(path.ends_with(DOCUMENT_FILE));
assert!(dir.join("index.tex").is_file(), "and a document to build");
let doc = Document::open(&dir).expect("reads back");
let built = doc.build(None).expect("builds");
assert_eq!(
std::fs::read_to_string(&built.path).unwrap().trim(),
"hello from texrs"
);
assert!(scaffold(&dir, "again")
.unwrap_err()
.contains("already exists"));
let _ = std::fs::remove_dir_all(&dir);
}
}