ravenous-tools/crates/make/src/makepdf_structs.rs

415 lines
15 KiB
Rust

// Workspace: make
// File: make/src/makepdf_structs.rs
//! Contains utility data types used by other modules in the `makepdf` workspace.
//!
use cli_parser::MakeConfig;
use config::make::VerboseLevel;
use logos::Logos;
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
sync::LazyLock,
time::{Duration, Instant},
};
use console::Style;
use crate::makepdf_functions::BuilderParseResult;
/// Color Scheme for the NORMAL level
pub(super) static COL_NORMAL: LazyLock<Style> = LazyLock::new(Style::new);
/// Color Scheme for the MISC level
pub(super) static COL_MISC: LazyLock<Style> = LazyLock::new(|| Style::new().color256(44));
/// Color Scheme for the BOX level
pub(super) static COL_BOX: LazyLock<Style> = LazyLock::new(|| Style::new().color256(37));
/// Color Scheme for the CONTEXT level
pub(super) static COL_CONTEXT: LazyLock<Style> = LazyLock::new(|| Style::new().color256(30));
/// Color Scheme for the INFO level
pub(super) static COL_INFO: LazyLock<Style> = LazyLock::new(|| Style::new().color256(2));
/// Color Scheme for the WARNING level
pub(super) static COL_WARNING: LazyLock<Style> = LazyLock::new(|| Style::new().color256(166));
/// Color Scheme for the ERROR level
#[allow(dead_code)]
pub(super) static COL_ERROR: LazyLock<Style> = LazyLock::new(|| Style::new().color256(52));
/// Color Scheme for the CRITICAL level
pub(super) static COL_CRITICAL: LazyLock<Style> = LazyLock::new(|| Style::new().color256(1));
/// Color Scheme for the UNCATCHABLE level
pub(super) static COL_UNCATCHABLE: LazyLock<Style> =
LazyLock::new(|| Style::new().color256(124).bold());
/// Filler box for the [MISC] text box
pub(super) static TXT_MISC: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_MISC.apply_to(&"[MISC]")));
/// Filler box for the [BOXX] text box
pub(super) static TXT_BOXX: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_BOX.apply_to(&"[BOXX]")));
/// Filler box for the [CNTX] text box
pub(super) static TXT_CNTX: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CONTEXT.apply_to(&"[CNTX]")));
/// Filler box for the [INFO] text box
pub(super) static TXT_INFO: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_INFO.apply_to(&"[INFO]")));
/// Filler box for the [WARN] text box
pub(super) static TXT_WARN: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_WARNING.apply_to(&"[WARN]")));
/// Filler box for the [CRIT] text box
pub(super) static TXT_CRIT: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[CRIT]")));
/// Filler box for the [ERRR] text box
pub(super) static TXT_ERRR: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[ERRR]")));
/// Filler box for the [UKNW] text box
pub(super) static TXT_UKNW: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_UNCATCHABLE.apply_to(&"[UKNW]")));
/// Keeps tracks of the stats of the last(s) run to offer accurate estimation
#[derive(Serialize, Deserialize)]
pub(super) struct BuildInfo {
/// File parsed
pub filename: String,
/// Options Selected
pub options: Vec<String>,
/// Number of lines parsed
pub lines_parsed: u64,
/// Time ellapsed
pub time_ellapsed: Duration,
/// Time per section ellapsed
pub time_spent: Vec<Duration>,
/// Final file size
pub file_size: u64,
}
impl BuildInfo {
/// Create a new empty run
pub fn new(args: &MakeConfig) -> Self {
Self {
filename: args.filename.clone(),
// options: args.update_from_arg_matches,
options: Vec::new(),
lines_parsed: 0,
time_ellapsed: Duration::from_secs(0),
time_spent: Vec::new(),
file_size: 0,
}
}
/// Load a run from file
pub(super) fn load(args: &MakeConfig) -> Self {
let mut file = match std::fs::File::open(".last_run.toml") {
Ok(f) => f,
Err(_) => return Self::empty_guess(args),
};
let mut cfg = String::new();
file.read_to_string(&mut cfg).unwrap();
let cfg = toml::from_str(&cfg);
match cfg {
Ok(c) => c,
Err(_) => Self::empty_guess(args),
}
}
/// An enmpty (and very small) initial guess
fn empty_guess(args: &MakeConfig) -> BuildInfo {
let mut s = Self::new(args);
s.lines_parsed = 100;
s.file_size = 100;
s
}
/// Save the last run info
pub(super) fn save(&self) {
let mut file = std::fs::File::create(".last_run.toml").unwrap();
file.write_all(toml::to_string(&self).unwrap().as_bytes())
.unwrap();
}
/// Add a level to a chapter, and return the new total duration
pub(super) fn add_lap(&mut self, started: &Instant, last_total: &mut Duration) {
let total = started.elapsed();
self.time_spent
.push(total.checked_sub(*last_total).unwrap());
*last_total = total;
}
}
// [7] [8]
// [UKNW] LaTeX Warning: There were undefined references.
// [UKNW] (./Ravenous_build.gls [29] [30] (/usr/share/texmf/tex/latex/lm/ot1lmr.fd) (/usr/share/texmf/tex/latex/lm/omllmm.fd) (/usr/share/texmf/tex/latex/lm/omslmsy.fd) (/usr/share/texmf/tex/latex/lm/omxlmex.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msa.cfg) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msb.cfg) [31] [32]
// [UKNW] LaTeX Warning: There were undefined references.
/// The line encountered
// #[allow(unused)]
#[derive(Debug, Logos, PartialEq)]
#[logos(skip r"[) ]+")]
pub(super) enum LineType {
/// The tex building mode : entering extended 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("? ) [")]
#[token("? [1{")]
StartingSequence,
/// Strange end sequence
#[token("{/usr/share")]
#[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")]
MissingReferencePrs,
/// Missed reference, completed with all info
MissingReference(String),
/// Generic Latex Warning
#[regex("pdf([Ll]a)?[tT]e[Xx] [wW]arning")]
#[regex("[Ll]a[tT]e[Xx] [wW]arning")]
WarningPrs,
/// Reparsed Warning
Warning(String),
// /// Runaway argument
// #[token("Runaway argument?")]
// RunAway,
/// PdfTex VersionThis is pdfTeX, Version 3.141592653-2.6-1.40.22
#[token("This is pdfTeX", |_| "".to_string())]
PdfTexVersion(String),
/// Context, mosty for boxes
// TODO: False positives / Reparsing Context("10") )) [107] (./Ecoles/Protecteur.tex
// TODO: uncaught: [UKNW] [3] [4] (./Chapters/Intro.tex (/usr/share/texmf/tex/latex/lm/ot1lmr.fd) (/usr/share/texmf/tex/latex/lm/omllmm.fd) (/usr/share/texmf/tex/latex/lm/omslmsy.fd) (/usr/share/texmf/tex/latex/lm/omxlmex.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msa.cfg) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msb.cfg) (/usr/share/texmf/tex/latex/lm/ts1lmr.fd)) [5 <./Images//Ico/LogoNoush.jpg>] [6]
#[regex(r"\[\d+\]", |lex| lex.slice()[1..lex.slice().len()-1].to_string())]
#[regex(r"\[\d[^\]]+", |lex| lex.slice()[1..lex.slice().len()-1].to_string())]
Context(String),
/// Overfull and underfull boxes
#[regex("(Over|Under)full")]
BoxFullnessPrs,
/// A box, reparsed
BoxFullness(String),
/// The Latex Version
#[regex("LaTeX2e")]
LaTexVersion,
/// The write18 mode, whatever that is
#[token(" restricted \\write18 enabled.")]
#[token(" \\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/_-]+\.(gls|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()))]
PackageWarningPrs((String, String)),
/// A package warning, with normal warning level
PackageWarning((String, String)),
/// A package warning, with low warning level
LowPackageWarning((String, String)),
/// The warning context generated by a package
#[regex(r"\([A-z_-]+\) [^\n]+", |lex| split_by(")",&lex.slice()[1..]))]
PackageContext((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,
}
impl LineType {
/// Decides all verbose levels, for output
pub(super) fn vlvl(&self) -> VerboseLevel {
match &self {
LineType::Mode => VerboseLevel::Misc,
LineType::Info(_) => VerboseLevel::Misc,
LineType::StartingSequence => VerboseLevel::Misc,
LineType::EndSequence => VerboseLevel::Misc,
LineType::MPSConverter => VerboseLevel::Misc,
LineType::Chapter(_) => VerboseLevel::Context,
LineType::MissingReference(_) => VerboseLevel::Warning,
LineType::PdfTexVersion(_) => VerboseLevel::Misc,
LineType::Context(_) => VerboseLevel::Misc,
LineType::LaTexVersion => VerboseLevel::Misc,
LineType::WriteMode => VerboseLevel::Misc,
LineType::DocumentClass => VerboseLevel::Misc,
LineType::EnteringDocument(_) => VerboseLevel::Info,
LineType::Library(_) => VerboseLevel::Context,
LineType::PackageContext(_) => VerboseLevel::Warning,
LineType::Loading(_) => VerboseLevel::Context,
LineType::Unknown(_) => VerboseLevel::Uncatchable,
LineType::PageGen => VerboseLevel::None,
LineType::Output => VerboseLevel::Misc,
LineType::Log => VerboseLevel::Misc,
LineType::Empty => VerboseLevel::None,
LineType::GeometryResolution => VerboseLevel::Misc,
LineType::GeometryFound => VerboseLevel::Misc,
LineType::Transcript => VerboseLevel::Misc,
LineType::PackageWarning(_) => VerboseLevel::Warning,
LineType::LowPackageWarning(_) => VerboseLevel::Box,
LineType::BoxFullness(_) => VerboseLevel::Box,
LineType::Warning(_) => VerboseLevel::Warning,
LineType::WarningPrs => VerboseLevel::Critical,
LineType::MissingReferencePrs => VerboseLevel::Critical,
LineType::BoxFullnessPrs => VerboseLevel::Critical,
LineType::PackageWarningPrs(_) => VerboseLevel::Critical,
}
}
}
/// 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);
if let Some(one) = slice.next()
&& let Some(two) = slice.next()
{
return Some((one.to_string(), two.trim_start().to_string()));
}
None
}
#[derive(Debug)]
/// The current status of a run, holding all final info
pub(super) struct Status {
/// Number of encountered info (mainly o/ufull)
pub(super) info: usize,
/// Number of warnings, mainly label/reference rerun
pub(super) warnings: usize,
/// Only makes sense with non-interactie builds
pub(super) errors: usize,
// /// List of all recoverable
// pub(super) v_errors: Vec<String>,
}
impl Status {
/// Initialize a new status
pub(super) fn zero() -> Self {
Self {
info: 0,
warnings: 0,
errors: 0,
}
}
/// Print a pretty message
pub(super) fn print(
&self,
args: &MakeConfig,
run_info: &BuildInfo,
file_info: BuilderParseResult,
) {
let col_bld = COL_INFO.clone().bold();
println!();
println!(
"{} {}",
col_bld.apply_to("[RCAP]"),
COL_NORMAL.apply_to(format!(
"Processed file {} in {:?}.",
run_info.filename, run_info.time_ellapsed
))
);
println!(
"{} {}",
col_bld.apply_to("[RCAP]"),
COL_NORMAL.apply_to(format!(
"The compilation generated {} Warnings and {} Errors.",
self.warnings, self.errors
))
);
if args.no_context {
println!(
"{} {}",
col_bld.apply_to("[RCAP]"),
COL_NORMAL.apply_to("Time spent per chapter")
);
if !run_info.time_spent.is_empty() {
println!(
"{}",
run_info
.time_spent
.iter()
.enumerate()
.map(|(i, d)| format!(
"{} Chapter {} {} - {:.2?}s",
COL_CONTEXT.apply_to("[===>]"),
i + 1,
file_info.chapt_list.get(i).unwrap_or(&"???".to_string()),
d.as_secs_f64()
))
.collect::<Vec<String>>()
.join("\n")
)
}
}
}
}