ravenous-tools/src/makepdf.rs

294 lines
8.9 KiB
Rust

//! Make a pdf using pdflatex
// use std::fmt::Display;
use logos::{Lexer, Logos};
use std::str;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use anyhow::{anyhow, Result};
use clap::Args;
use std::process::Stdio;
use crate::Config;
#[derive(Args, Debug, Clone)]
/// The configuration struct for the PdfMaker
pub(crate) struct MakeConfig {
/// The filename to compile
pub(crate) filename: String,
/// The verbosity level
#[arg(short, long, default_value_t = false)]
pub(crate) verbosity: bool,
}
/// Make a pdf spawning a subprocess
pub(crate) fn make_pdf(args: &MakeConfig, config: &Config) -> Result<()> {
let _ = config;
launch_subprocess(args).unwrap();
Ok(())
}
#[derive(Debug)]
/// The current status of a run, holding all final info
struct Status {
/// Number of encountered info (mainly o/ufull)
info: usize,
/// Number of warnings, mainly label/reference rerun
warnings: usize,
/// Only makes sense with non-interactie builds
errors: usize,
/// List of all recoverable
v_errors: Vec<String>,
}
impl Status {
/// Add a recoverable error to the list of errors
fn add_error(&mut self, error_msg: String) {
self.errors += 1;
self.v_errors.push(error_msg);
}
}
// impl Display for Status {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// todo!()
// }
// }
impl Status {
/// Initialize a new status
fn zero() -> Self {
Self {
info: 0,
warnings: 0,
errors: 0,
v_errors: Vec::new(),
}
}
}
#[tokio::main]
/// Pdfreading and curating
async fn launch_subprocess(args: &MakeConfig) -> Result<Status> {
let mut cmd = Command::new("pdflatex");
let mut status = Status::zero();
let mut context = Vec::new();
cmd.arg(&args.filename);
cmd.env("max_print_line", "3000");
// Specify that we want the command's standard output piped back to us.
cmd.stdout(Stdio::piped());
let mut child = cmd.spawn().expect("Failed to spawn command");
let stdout = child
.stdout
.take()
.expect("Child did not have a handle to stdout");
let mut reader = BufReader::new(stdout).split(0xA);
// Ensure the child process is spawned in the runtime so it can
// make progress on its own while we await for any output.
tokio::spawn(async move {
let status = child
.wait()
.await
.expect("Child process encountered an error");
println!("Child status was: {}", status);
});
loop {
let res = reader.next_segment().await;
if let Err(e) = res {
return Err(anyhow!("[CORE] Runtime error : {}", e));
} else if let Ok(line) = res {
if let Some(line) = line {
let s = match str::from_utf8(&line) {
Ok(v) => v,
Err(e) => {
// status.errors += 1;
status.add_error(format!("[CORE] Invalid UTF-8 sequence: {}", e));
continue;
}
};
// println!("Line: {:?}", s);
checkline(s, &mut status, &mut context).expect("Error while checking line");
} else {
break;
}
}
}
// println!("{:?}", status);
Ok(status)
}
/// The line encountered
// #[allow(unused)]
#[derive(Debug, Logos, PartialEq)]
#[logos(skip r"[) ]+")]
enum LineType {
/// The tex building mode
#[regex("entering[_ ]extended[_ ]mode")]
Mode,
/// Info level
#[token("L3 programming layer", |lex| lex.slice().to_string())]
#[token("For additional information", |lex| lex.slice().to_string())]
#[token("Pictures in Paragraphs", |lex| lex.slice().to_string())]
#[token("2021/01/20 v 2.00 tkz-graph.sty", |lex| lex.slice().to_string())]
Info(String),
/// Strange starting sequence
#[token("? [1{")]
StartingSequence,
/// Strange end sequence
#[token(" ){/")]
EndSequence,
/// Converter [Loading MPS to PDF converter (version 2006.09.02).]
#[token("[Loading MPS to PDF converter")]
MPSConverter,
/// A chapter was processed
#[regex(r"Chapitre [0-9]+", |lex| lex.slice()[9..].to_string())]
Chapter(String),
/// Missing reference
#[token(r"LaTeX Warning: Reference")]
MissingReference,
/// Generic Latex Warning
#[regex(r"(LaTex |Warning:){2}[^\n]+", |lex| lex.slice()[14..].to_string())]
Warning(String),
// /// Runaway argument
// #[token("Runaway argument?")]
// RunAway,
/// PdfTex VersionThis is pdfTeX, Version 3.141592653-2.6-1.40.22
#[token("This is pdfTeX")]
PdfTexVersion,
/// Context, mosty for boxes
#[regex(r"\[\d[^\]]+", |lex| lex.slice()[1..lex.slice().len()-1].to_string())]
Context(String),
/// Overfull and underfull boxes
#[regex("(Over|Under)full")]
BoxFullness,
/// The Latex Version
#[regex("LaTeX2e")]
LaTexVersion,
/// The write18 mode, whatever that is
#[token(" restricted \\write18 enabled.")]
WriteMode,
/// The class of document (book, article, etc)
// s if s.starts_with("Document Class") => LineType::DocumentClass(s.to_string()),
#[token("Document Class:")]
DocumentClass,
/// Signals that the parser entered a document
//TODO: Fix name collection
// #[regex(r"(\)+ )?\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").next().unwrap_or("").to_string())]
// #[regex(r"(\)+ )?(\[\w+\])?\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").next().unwrap_or("").to_string())]
// #[regex(r"[\) ]*\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
// #[regex(r"[\) ]*(\[[0-9]+\] )?\(\./[A-z/-_]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
// #[regex(r"[\) 0-9\[\]]*\(\./[A-z/-_]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
#[regex(r"\(\./[A-z/_-]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
EnteringDocument(String),
/// Info on the loading of a library
#[regex(r"Library \(\w+\)[^\n]+", |lex| split_by(":",&lex.slice()[8..]))]
Library((String, String)),
/// The warning generated by a package
#[regex(r"Package [A-z_-]+ Warning: [^\n]+", |lex| split_by(":",lex.slice()))]
PackageWarning((String, String)),
/// The warning context generated by a package
#[regex(r"\([A-z_-]+\) [^\n]+", |lex| split_by(")",&lex.slice()[1..]))]
PackageContextWarning((String, String)),
/// Loading (Load something)
#[regex(r"(\)+ )?\(/usr[^)]*", |lex| lex.slice().split("/").last().unwrap_or("").to_string())]
Loading(String),
/// Unknown type
Unknown(String),
/// Building blocks, signals pages being rendered ?
#[token(" []")]
#[token("[]")]
PageGen,
/// Output
// #[regex(r"Output written on", |lex| lex.slice()[18..].to_string())]
#[token(r"Output written on")]
Output,
/// Log
// #[regex("Transcript written on [^\n]+", |lex| lex.slice()[18..].to_string())]
#[token("Transcript written on")]
Log,
// /// Barely parsable data
// #[regex(r"\)+")]
// Garbage,
/// Empty line, to discard
Empty,
/// Geometry package
#[token("*geometry* driver: auto-detecting")]
GeometryResolution,
/// Geometry found
#[token("*geometry* detected driver: pdftex")]
GeometryFound,
/// Transcript
#[token("(see the transcript file for additional information)")]
Transcript,
}
/// Tries to split the token and return two string
fn split_by(delim: &str, text: &str) -> Option<(String, String)> {
let mut slice = text.split(delim);
// println!("{:?}", text);
if let Some(one) = slice.next() {
// println!("{:?}", one);
if let Some(two) = slice.next() {
// println!("{} {:?}", one, slice.next());
return Some((one.to_string(), two.trim_start().to_string()));
}
}
None
}
/// Check each line and changes the status and/or display according warnings
fn checkline(s: &str, status: &mut Status, context: &mut [String]) -> Result<()> {
// Match the line to guess what is happening
let mut lex = LineType::lexer(s);
let line = match lex.next() {
Some(Ok(m)) => m,
None => LineType::Empty,
_ => LineType::Unknown(s.to_string()),
};
match line {
LineType::Unknown(w) => println!("[UKWN] {}", w),
LineType::Empty => (),
LineType::EnteringDocument(_) => println!("{:?}", line),
// LineType::TabWarn(_) => println!("{:?}", line),
// LineType::Library(_) => println!("{:?}", line),
// LineType::PackageWarning(_) => println!("{:?},{}", line, s),
LineType::PackageContextWarning(_) => println!("{:?}", line),
LineType::MissingReference => println!("{:?} {}", line, s),
// LineType::=> (),
_ => (),
}
Ok(())
}