use std::path::{Path, PathBuf};
use std::process::ExitCode;
fn main() -> ExitCode {
struct Stats;
impl Drop for Stats {
fn drop(&mut self) {
if std::env::var_os("TEXRS_PRELEX_STATS").is_some() {
prelex_stats();
}
}
}
let _stats = Stats;
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("-X") {
return run_document(&args[1..]);
}
let cli = match texrs::cli::parse(&args) {
Ok(c) => c,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(1);
}
};
match cli.mode {
texrs::cli::Mode::Help => {
let colored = texrs::banner::colored_stdout();
texrs::banner::print_banner(colored);
print!(
"{}",
texrs::banner::render_usage(texrs::cli::USAGE, colored)
);
return ExitCode::SUCCESS;
}
texrs::cli::Mode::Version => {
println!("{}", texrs::banner::version_banner());
return ExitCode::SUCCESS;
}
texrs::cli::Mode::Repl => {
return match texrs::repl::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::Lsp => {
return match texrs::lsp::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::Dap => {
return match texrs::dap::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::CacheStats => return cache_stats(),
texrs::cli::Mode::CacheClear => return cache_clear(),
texrs::cli::Mode::Run => {}
}
let (build, dump_tokens, disasm, aot, tiers, no_cache, jobs) = (
cli.build,
cli.dump_tokens,
cli.disasm,
cli.aot,
cli.tiers,
cli.no_cache,
cli.jobs,
);
let mut paths = cli.files.clone();
if paths.is_empty() {
if let Some(src) = cli.command_line_source() {
return run_command_line(&src, cli.interaction);
}
}
if paths.is_empty() {
return match texrs::repl::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
};
}
if paths.len() > 1 && !dump_tokens && !cli.dump_ast && !disasm && !tiers {
return run_many(&paths, jobs);
}
let path = paths.remove(0);
let mut inputs = texrs::io::ProviderStack::new();
inputs.push(Box::new(
texrs::io::FilesystemProvider::with_roots(Vec::new()).with_primary(&path),
));
let src = match texrs::io::InputProvider::input_open_primary(&mut inputs) {
texrs::io::OpenResult::Ok(input) => input.content,
texrs::io::OpenResult::NotAvailable => {
eprintln!("texrs: {path}: no such file");
return ExitCode::from(1);
}
texrs::io::OpenResult::Err(e) => {
eprintln!("texrs: {path}: {e}");
return ExitCode::from(1);
}
};
if cli.dump_ast {
return match texrs::commands(&src) {
Ok(cmds) => {
print!("{}", texrs::ir::render(&cmds));
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if dump_tokens {
let cats = texrs::catcode::CatTable::new();
let mut lx = texrs::lexer::Lexer::new(&src);
while let Some(t) = lx.next_token(&cats) {
println!("{t:?}");
}
return ExitCode::SUCCESS;
}
if disasm {
let compiled = match no_cache {
true => texrs::compile(&src),
false => texrs::compile_cached(std::path::Path::new(&path), &src),
};
return match compiled {
Ok(chunk) => {
print!("{}", chunk.disassemble());
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if aot {
let out = output_path(&cli, &path, "");
return match texrs::aot::compile_executable(&path, &out) {
Ok(p) => {
println!("{}", p.display());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if build {
return match texrs::compile_cached(std::path::Path::new(&path), &src) {
Ok(chunk) => {
println!(
"built {path}: {} ops -> {}",
chunk.ops.len(),
texrs::script_cache::default_cache_path().display()
);
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if tiers {
return match texrs::tiers::report(&src) {
Ok(r) => {
println!("{r}");
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
let trailing = cli
.command_line_source()
.filter(|_| !texrs::source_ends_run(&src));
if let Some(extra) = trailing {
return run_with_trailing(&path, &src, &extra, cli.interaction);
}
if cli.pdf_out {
return match texrs::run_pdf_at(Some(std::path::Path::new(&path)), &src) {
Ok(bytes) => {
let out = output_path(&cli, &path, "pdf");
if texrs::pdf_page_count(&bytes) == 0 {
println!("({path} -> no pages of output)");
return ExitCode::SUCCESS;
}
match std::fs::write(&out, &bytes) {
Ok(()) => {
println!("({path} -> {} [{} bytes])", out.display(), bytes.len());
ExitCode::SUCCESS
}
Err(e) => fail(&format!("{}: {e}", out.display())),
}
}
Err(e) => fail(&e.0),
};
}
if cli.dvi_out {
let chain = match texrs::typeset::FontChain::load("cmr10", &["cmsy10", "cmmi10"]) {
Ok(c) => c,
Err(e) => return fail(&format!("--dvi: {e} (is a TeX installation present?)")),
};
let layout = texrs::typeset::Layout::default();
let keyed = match no_cache {
true => None,
false => Some(std::path::Path::new(&path)),
};
let built = texrs::run_dvi_fallback(keyed, &src, &chain, &layout);
return match built {
Ok(bytes) => {
let out = output_path(&cli, &path, "dvi");
match std::fs::write(&out, &bytes) {
Ok(()) => {
println!("({path} -> {} [{} bytes])", out.display(), bytes.len());
ExitCode::SUCCESS
}
Err(e) => fail(&format!("{}: {e}", out.display())),
}
}
Err(e) => fail(&e.0),
};
}
if cli.text {
let at = std::path::Path::new(&path);
let run = match no_cache {
true => texrs::run_text_at(at, &src),
false => texrs::run_text_cached(at, &src),
};
return match run {
Ok(text) => {
print!("{text}");
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
match texrs::run_pdf_with_messages(Some(std::path::Path::new(&path)), &src) {
Ok((pdf, msgs)) => {
let tail = match write_pdf(&path, &pdf) {
Ok(t) => t,
Err(e) => return fail(&e),
};
if cli.interaction.prints() {
println!(
"{}",
file_line(&path, &msgs.join(" "), texrs::source_ends_run(&src))
);
println!("{tail}");
}
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
}
}
fn run_many(paths: &[String], jobs: Option<usize>) -> ExitCode {
let workers = jobs
.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
})
.max(1)
.min(paths.len());
let next = std::sync::atomic::AtomicUsize::new(0);
let results: Vec<std::sync::Mutex<Option<Result<String, String>>>> = (0..paths.len())
.map(|_| std::sync::Mutex::new(None))
.collect();
std::thread::scope(|scope| {
for _ in 0..workers {
scope.spawn(|| {
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= paths.len() {
break;
}
*results[i].lock().expect("result slot") = Some(one_document(&paths[i]));
}
});
}
});
let mut code = ExitCode::SUCCESS;
let mut failed = false;
for (i, slot) in results.iter().enumerate() {
match slot.lock().expect("result slot").take() {
Some(Ok(line)) => println!("{line}"),
Some(Err(e)) => {
eprintln!("! {e}.");
failed = true;
}
None => {
eprintln!("texrs: {}: not run", paths[i]);
failed = true;
}
}
}
if failed {
code = ExitCode::from(1);
}
code
}
fn output_path(cli: &texrs::cli::Cli, input: &str, extension: &str) -> PathBuf {
let named = Path::new(input).with_extension(extension);
match &cli.output_directory {
Some(dir) => match named.file_name() {
Some(base) => dir.join(base),
None => named,
},
None => named,
}
}
fn write_pdf(path: &str, pdf: &[u8]) -> Result<String, String> {
let out = Path::new(path).with_extension("pdf");
if texrs::pdf_page_count(pdf) > 0 {
std::fs::write(&out, pdf).map_err(|e| format!("{}: {e}", out.display()))?;
}
Ok(texrs::pdf_output_line(&out, pdf))
}
fn one_document(path: &str) -> Result<String, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
let (pdf, msgs) = texrs::run_pdf_with_messages(Some(Path::new(path)), &src).map_err(|e| e.0)?;
let joined = msgs.join(" ");
let body = match joined.is_empty() {
true => String::new(),
false => format!(" {joined}"),
};
let tail = write_pdf(path, &pdf)?;
Ok(format!("(./{path}{body} )\n{tail}"))
}
fn run_document(args: &[String]) -> ExitCode {
let Some(command) = args.first().map(String::as_str) else {
eprint!("{}", texrs::banner::render_usage(texrs::cli::USAGE, false));
return ExitCode::from(1);
};
match command {
"new" | "init" => {
let dir = match command {
"init" => PathBuf::from("."),
_ => args
.get(1)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(".")),
};
let name = std::fs::canonicalize(&dir)
.ok()
.as_deref()
.and_then(Path::file_name)
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "document".to_string());
match texrs::document::scaffold(&dir, &name) {
Ok(path) => {
println!("wrote {}", path.display());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"bundle" => match args.get(1).map(String::as_str) {
Some("fetch") => {
let Some(url) = args.get(2) else {
return fail("`-X bundle fetch` needs a URL");
};
match texrs::geturl::fetch(url) {
Ok(got) => {
println!("fetched {} bytes → {}", got.bytes, got.path.display());
println!(
"name it in Texrs.toml as: bundle = \"sha256:{}\"",
got.digest
);
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
Some("list") => {
let fetched = texrs::geturl::fetched();
if fetched.is_empty() {
println!("no bundles fetched");
}
for digest in fetched {
match texrs::geturl::path_for(&digest) {
Some(path) => println!("sha256:{digest} {}", path.display()),
None => println!("sha256:{digest}"),
}
}
ExitCode::SUCCESS
}
other => {
eprintln!(
"texrs: `-X bundle` takes fetch or list, not {}",
other.unwrap_or("nothing")
);
ExitCode::from(1)
}
},
"bib" => {
let Some(file) = args.get(1) else {
return fail("`-X bib` needs a .bib or .aux file");
};
if std::path::Path::new(file)
.extension()
.is_some_and(|e| e == "aux")
{
return bib_citations(std::path::Path::new(file));
}
match texrs::bib::Bib::open(file) {
Ok(bib) => {
print!("{}", bib.summary());
match bib.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
Err(e) => fail(&e),
}
}
"bibtex" => {
let Some(file) = args.get(1) else {
return fail("`-X bibtex` needs a .aux file");
};
bibtex_run(std::path::Path::new(file))
}
"special" => {
let text = args[1..].join(" ");
if text.trim().is_empty() {
return fail("`-X special` needs the text of a \\special");
}
println!("{}", texrs::special::parse(&text));
ExitCode::SUCCESS
}
"itar" => {
let Some(file) = args.get(1) else {
return fail("`-X itar` needs a .tar bundle");
};
match texrs::itar::Itar::open(file) {
Ok(itar) => match args.get(2) {
Some(name) => match itar.read(name) {
Ok(bytes) => {
use std::io::Write;
match std::io::stdout().write_all(&bytes) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e.to_string()),
}
}
Err(e) => fail(&e),
},
None => {
print!("{}", itar.summary());
print!("{}", itar.index());
ExitCode::SUCCESS
}
},
Err(e) => fail(&e),
}
}
"map" => {
let Some(file) = args.get(1) else {
return fail("`-X map` needs a font map, or a map and a TeX font name");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(file),
};
match texrs::fontmap::FontMap::open(&found) {
Ok(map) => match args.get(2) {
Some(name) => match map.lookup(name) {
Some(entry) => {
print!("{entry}");
ExitCode::SUCCESS
}
None => fail(&format!("{found}: no entry for {name}")),
},
None => {
print!("{}", map.summary());
ExitCode::SUCCESS
}
},
Err(e) => fail(&e),
}
}
"enc" => {
let Some(file) = args.get(1) else {
return fail("`-X enc` needs an encoding file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_format("enc files", file),
};
match texrs::fontmap::Encoding::open(&found) {
Ok(encoding) => {
print!("{}", encoding.summary());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"pfb" => {
let Some(file) = args.get(1) else {
return fail("`-X pfb` needs a Type 1 font");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(&match file.contains('.') {
true => file.to_string(),
false => format!("{file}.pfb"),
}),
};
match texrs::type1::Type1::open(&found) {
Ok(font) => {
match args.get(2).and_then(|c| c.chars().next()) {
Some(c) if c.is_ascii() => print!("{}", font.describe(c as u8)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", font.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"otf" => {
let Some(file) = args.get(1) else {
return fail("`-X otf` needs an OpenType or TrueType font");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(file),
};
match texrs::sfnt::Sfnt::open(&found) {
Ok(font) => {
match args.get(2).and_then(|c| c.chars().next()) {
Some(c) => print!("{}", font.describe(c as u32)),
None => print!("{}", font.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"pk" => {
let Some(file) = args.get(1) else {
return fail("`-X pk` needs a .pk file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_format("pk", file),
};
match texrs::pk::Pk::open(&found) {
Ok(pk) => {
match args.get(2).and_then(|c| c.chars().next()) {
Some(c) if c.is_ascii() => print!("{}", pk.describe(c as u32)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", pk.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"vf" => {
let Some(file) = args.get(1) else {
return fail("`-X vf` needs a .vf file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(&match file.ends_with(".vf") {
true => file.to_string(),
false => format!("{file}.vf"),
}),
};
match texrs::vf::Vf::open(&found) {
Ok(vf) => {
match args.get(2).and_then(|c| c.chars().next()) {
Some(c) if c.is_ascii() => print!("{}", vf.describe(c as u32)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", vf.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"tfm" => {
let Some(file) = args.get(1) else {
return fail("`-X tfm` needs a .tfm file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich(file),
};
match texrs::tfm::Tfm::open(&found) {
Ok(tfm) => {
match args.get(2).and_then(|c| c.chars().next()) {
Some(c) if c.is_ascii() => print!("{}", tfm.describe(c as u8)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", tfm.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"bst" => {
let Some(file) = args.get(1) else {
return fail("`-X bst` needs a .bst file");
};
match texrs::bst::Style::open(file) {
Ok(style) => {
print!("{}", style.summary());
match style.undefined().is_empty() && style.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
Err(e) => fail(&e),
}
}
"dvi" => {
let Some(file) = args.get(1) else {
return fail("`-X dvi` needs a .dvi file");
};
let dvi = match texrs::dvi::Dvi::open(file) {
Ok(dvi) => dvi,
Err(e) => return fail(&e),
};
let Some(other) = args.get(2) else {
print!("{}", dvi.summary());
return ExitCode::SUCCESS;
};
let against = match texrs::dvi::Dvi::open(other) {
Ok(dvi) => dvi,
Err(e) => return fail(&e),
};
let differences = dvi.compare(&against);
if differences.is_empty() {
println!("the same document");
return ExitCode::SUCCESS;
}
for difference in &differences {
println!("{difference:?}");
}
ExitCode::from(1)
}
"show" => {
let here = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
match texrs::document::Document::find_from(here) {
Ok(document) => {
print!("{}", document.show());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"build" | "watch" | "dump" => {
let mut profile: Option<String> = None;
let mut interval = texrs::document::WATCH_INTERVAL;
let mut rest = args[1..].iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--profile" => match rest.next() {
Some(name) => profile = Some(name.clone()),
None => return fail("--profile needs a name"),
},
"--interval" => match rest.next().and_then(|ms| ms.parse().ok()) {
Some(ms) => interval = std::time::Duration::from_millis(ms),
None => return fail("--interval needs a number of milliseconds"),
},
"-h" | "--help" => {
print!("{}", texrs::cli::USAGE);
return ExitCode::SUCCESS;
}
other => return fail(&format!("unknown argument: {other}")),
}
}
let here = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let document = match texrs::document::Document::find_from(here) {
Ok(d) => d,
Err(e) => return fail(&e),
};
if command == "dump" {
return match document.dump(profile.as_deref()) {
Ok(text) => {
print!("{text}");
if !text.ends_with('\n') {
println!();
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if command == "build" {
return match document.build(profile.as_deref()) {
Ok(built) => {
println!(
"built {} from {} input(s) → {}",
built.profile,
built.inputs.len(),
built.path.display()
);
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
let mut status = texrs::status::TexStatus::new();
match document.watch(profile.as_deref(), interval, &mut status, &|| false) {
Ok(_) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
other => match external_command(other, &args[1..]) {
Some(code) => code,
None => {
eprintln!("texrs: unknown document command: {other}");
eprint!("{}", texrs::banner::render_usage(texrs::cli::USAGE, false));
ExitCode::from(1)
}
},
}
}
fn external_command(name: &str, args: &[String]) -> Option<ExitCode> {
let program = format!("texrs-{name}");
match std::process::Command::new(&program).args(args).status() {
Ok(status) => Some(match status.code() {
Some(0) => ExitCode::SUCCESS,
Some(code) => ExitCode::from(code.min(255) as u8),
None => ExitCode::from(1),
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
eprintln!("texrs: {program}: {e}");
Some(ExitCode::from(1))
}
}
}
fn kpsewhich_format(format: &str, name: &str) -> String {
let named = match (format, name.contains('.')) {
("pk", false) => format!("{name}.600pk"),
("enc files", false) => format!("{name}.enc"),
_ => name.to_string(),
};
let found = std::process::Command::new("kpsewhich")
.arg(format!("-format={format}"))
.arg(&named)
.output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
fn kpsewhich_named(name: &str) -> String {
let found = std::process::Command::new("kpsewhich").arg(name).output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
fn kpsewhich(name: &str) -> String {
let named = match name.ends_with(".tfm") {
true => name.to_string(),
false => format!("{name}.tfm"),
};
let found = std::process::Command::new("kpsewhich").arg(&named).output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
fn bibtex_run(path: &Path) -> ExitCode {
let aux = match texrs::bib::Aux::open(path) {
Ok(aux) => aux,
Err(e) => return fail(&e),
};
let dir = path.parent().unwrap_or(Path::new("."));
let Some(name) = &aux.style else {
return fail(&format!("{}: no \\bibstyle", path.display()));
};
let beside = dir.join(format!("{name}.bst"));
let found = match beside.exists() {
true => beside.to_string_lossy().to_string(),
false => kpsewhich_named(&format!("{name}.bst")),
};
let style = match texrs::bst::Style::open(&found) {
Ok(style) => style,
Err(e) => return fail(&e),
};
for missing in style.undefined() {
eprintln!("texrs: {name}.bst calls {missing}, which nothing defines");
}
let mut database = texrs::bib::Bib::default();
if aux.databases.is_empty() {
return fail(&format!("{}: no \\bibdata", path.display()));
}
for part in &aux.databases {
let file = dir.join(format!("{part}.bib"));
let text = match std::fs::read_to_string(&file) {
Ok(text) => text,
Err(e) => return fail(&format!("cannot read {}: {e}", file.display())),
};
let read = texrs::bib::Bib::parse_with(&text, &style.macros());
database.entries.extend(read.entries);
database.strings.extend(read.strings);
database.preamble.push_str(&read.preamble);
database.warnings.extend(read.warnings);
}
let (bbl, warnings) = texrs::bstvm::run(&aux, &style, &database);
let out = path.with_extension("bbl");
if let Err(e) = std::fs::write(&out, &bbl) {
return fail(&format!("cannot write {}: {e}", out.display()));
}
for warning in database.warnings.iter().chain(warnings.iter()) {
eprintln!("texrs: {warning}");
}
match warnings.is_empty() && database.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
fn bib_citations(path: &Path) -> ExitCode {
let aux = match texrs::bib::Aux::open(path) {
Ok(aux) => aux,
Err(e) => return fail(&e),
};
let dir = path.parent().unwrap_or(Path::new("."));
let mut database = texrs::bib::Bib::default();
if aux.databases.is_empty() {
return fail(&format!("{}: no \\bibdata", path.display()));
}
for name in &aux.databases {
let file = dir.join(format!("{name}.bib"));
match texrs::bib::Bib::open(&file) {
Ok(part) => {
database.entries.extend(part.entries);
database.strings.extend(part.strings);
database.warnings.extend(part.warnings);
}
Err(e) => return fail(&e),
}
}
let selected = database.select(&aux);
for entry in &selected.cited {
let title = entry.field("title").unwrap_or("");
println!("cited {:<20} {title}", entry.key);
}
for key in &selected.missing {
println!("MISSING {key}");
}
for entry in &selected.uncited {
println!("uncited {}", entry.key);
}
match selected.missing.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
fn cache_stats() -> ExitCode {
let path = texrs::script_cache::default_cache_path();
if !texrs::script_cache::cache_enabled() {
println!("cache: off (TEXRS_CACHE)");
println!("would be: {}", path.display());
return ExitCode::SUCCESS;
}
let Ok(cache) = texrs::script_cache::ScriptCache::open(&path) else {
eprintln!("texrs: cannot open {}", path.display());
return ExitCode::from(1);
};
let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
println!("cache: {}", path.display());
println!("documents: {}", cache.len());
println!("size: {size} bytes");
ExitCode::SUCCESS
}
fn cache_clear() -> ExitCode {
let path = texrs::script_cache::default_cache_path();
let Ok(cache) = texrs::script_cache::ScriptCache::open(&path) else {
eprintln!("texrs: cannot open {}", path.display());
return ExitCode::from(1);
};
match cache.clear() {
Ok(()) => {
println!("cleared {}", path.display());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("texrs: {}: {e}", path.display());
ExitCode::from(1)
}
}
}
fn file_line(path: &str, msgs: &str, ended: bool) -> String {
let body = match msgs.is_empty() {
true => String::new(),
false => format!(" {msgs}"),
};
let close = match ended {
true => " )",
false => ")",
};
format!("(./{path}{body}{close}")
}
fn run_with_trailing(
path: &str,
src: &str,
extra: &str,
interaction: texrs::cli::Interaction,
) -> ExitCode {
let from_file = match texrs::run_messages_list(src) {
Ok(m) => m,
Err(e) => return fail(&e.0),
};
let all = match texrs::run_messages_list(&format!("{src}\n{extra}")) {
Ok(m) => m,
Err(e) => return fail(&e.0),
};
if interaction.prints() {
let after = all[from_file.len().min(all.len())..].join(" ");
let line = file_line(path, &from_file.join(" "), false);
match after.is_empty() {
true => println!("{line}"),
false => println!("{line} {after}"),
}
}
ExitCode::SUCCESS
}
fn run_command_line(src: &str, interaction: texrs::cli::Interaction) -> ExitCode {
match texrs::run_messages(src) {
Ok(msgs) => {
if interaction.prints() && !msgs.is_empty() {
println!("{msgs}");
}
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
}
}
fn fail(reason: &str) -> ExitCode {
eprintln!("! {reason}.");
ExitCode::from(1)
}
pub fn prelex_stats() {
use std::sync::atomic::Ordering;
eprintln!(
"prelex calls={} chars={} drop_gen={} drop_exhaust={}",
texrs::parallel::PRELEX_CALLS.load(Ordering::Relaxed),
texrs::parallel::PRELEX_CHARS.load(Ordering::Relaxed),
texrs::parallel::DROP_GEN.load(Ordering::Relaxed),
texrs::parallel::DROP_EXHAUST.load(Ordering::Relaxed)
);
}