Full working feature 1 #6

Merged
Dandaedre merged 1 commits from feature/builder into main 2024-06-23 03:21:11 +02:00
5 changed files with 580 additions and 303 deletions

View File

@ -9,12 +9,14 @@ edition = "2021"
[dependencies]
anyhow = "1.0.86"
clap = { version = "4.5.7", features = ["derive"] }
console = "0.15.8"
csv = "1.3.0"
debug_print = "1.0.0"
dynfmt = { version = "0.1.5", features = ["curly"] }
enum_dispatch = "0.3.13"
futures = "0.3.30"
glob = "0.3.1"
indicatif = "0.17.8"
logos = "0.14.0"
phf = { version = "0.11.2", features = ["macros"] }
regex = "1.10.5"

View File

@ -7,6 +7,7 @@
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]
mod makepdf;
mod makepdf_structs;
mod stat_algo;
mod stat_io;
mod stat_structs;

View File

@ -1,8 +1,11 @@
//! Make a pdf using pdflatex
// use std::fmt::Display;
use logos::{Lexer, Logos};
use phf::phf_map;
// use std::str::pattern::Pattern;
use std::time::{Duration, Instant};
use std::{cmp::min, fmt::Write};
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use logos::Logos;
use std::str;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
@ -11,6 +14,10 @@ use anyhow::{anyhow, Result};
use clap::Args;
use std::process::Stdio;
use crate::makepdf_structs::{
BuildInfo, LineType, Status, VerboseLevel, COL_NORMAL, TXT_BOXX, TXT_CNTX, TXT_CRIT, TXT_ERRR,
TXT_INFO, TXT_MISC, TXT_UKNW, TXT_WARN,
};
use crate::Config;
#[derive(Args, Debug, Clone)]
@ -27,53 +34,6 @@ pub(crate) struct MakeConfig {
// pub(crate) blacklist: Vec<VerboseLevel>,
}
/// The verbosity level
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum VerboseLevel {
/// Shouldn't be printed no matter what
None,
/// Garbage
Misc,
/// Boxness, barely above Misc
Box,
/// Context info (Debug info)
Context,
/// Usefull info
Info,
/// Important warnings
Warning,
/// Errors encountered requiring user input
Error,
/// Uncatachable errors
Critical,
/// Literrally uncatchable things
Uncatchable,
}
static STR_TO_TARGET: phf::Map<&'static str, VerboseLevel> = phf_map! {
"misc" =>VerboseLevel::Misc,
"box" => VerboseLevel::Box,
"context" => VerboseLevel::Context,
"info" => VerboseLevel::Info,
"warning" => VerboseLevel::Warning,
"error" => VerboseLevel::Error,
"critical" => VerboseLevel::Critical,
};
impl From<&str> for VerboseLevel {
fn from(value: &str) -> Self {
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
target
} else {
panic!(
"Invalid debug level {}. The debug level available are: {:?}",
value,
STR_TO_TARGET.keys()
)
}
}
}
/// Make a pdf spawning a subprocess
pub(crate) fn make_pdf(args: &MakeConfig, config: &Config) -> Result<()> {
let _ = config;
@ -81,54 +41,21 @@ pub(crate) fn make_pdf(args: &MakeConfig, config: &Config) -> Result<()> {
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();
let started = Instant::now();
let mut current_run = BuildInfo::new(args);
let last_run = BuildInfo::load(args);
let mut built = 0;
let to_build = last_run.lines_parsed;
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());
@ -144,16 +71,36 @@ async fn launch_subprocess(args: &MakeConfig) -> Result<Status> {
// 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
let _status = child
.wait()
.await
.expect("Child process encountered an error");
println!("Child status was: {}", status);
// sleep(Duration::from_millis(100)).await;
// println!("Child status was: {}", status);
});
let pb = ProgressBar::new(to_build);
pb.set_style(
ProgressStyle::with_template(
"{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] (lines: {pos}/{len}) (speed: {per_sec}) (eta: {eta})",
)
.unwrap()
.with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap()
})
.with_key("per_sec",|state:&ProgressState,w:&mut dyn Write|{
write!(w,"{:.1}/lps",state.per_sec()).unwrap()
})
.progress_chars("#>-"),
);
pb.enable_steady_tick(Duration::from_millis(100));
loop {
let res = reader.next_segment().await;
let new = min(built + 1, to_build);
built = new;
pb.set_position(new);
current_run.lines_parsed += 1;
if let Err(e) = res {
return Err(anyhow!("[CORE] Runtime error : {}", e));
} else if let Ok(line) = res {
@ -166,207 +113,28 @@ async fn launch_subprocess(args: &MakeConfig) -> Result<Status> {
continue;
}
};
// println!("Line: {:?}", s);
checkline(args, s, &mut status, &mut context).expect("Error while checking line");
checkline(args, s, &mut status, &mut current_run, &started, &pb)
.expect("Error while checking line");
} else {
break;
}
}
}
// println!("{:?}", status);
current_run.time_ellapsed = started.elapsed();
pb.finish_and_clear();
status.print(&current_run);
current_run.save();
Ok(status)
}
/// The line encountered
// #[allow(unused)]
#[derive(Debug, Logos, PartialEq)]
#[logos(skip r"[) ]+")]
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(" ){/")]
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(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
// TODO: False positives / Reparsing Context("10") )) [107] (./Ecoles/Protecteur.tex
#[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,
}
impl LineType {
/// Decides all verbose levels, for output
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::MissingReferencePrs => VerboseLevel::Warning,
LineType::Warning(_) => VerboseLevel::Warning,
LineType::MissingReference(_) => VerboseLevel::Warning,
LineType::PdfTexVersion => VerboseLevel::Misc,
LineType::Context(_) => VerboseLevel::Misc,
LineType::BoxFullness => VerboseLevel::Box,
LineType::LaTexVersion => VerboseLevel::Misc,
LineType::WriteMode => VerboseLevel::Misc,
LineType::DocumentClass => VerboseLevel::Misc,
LineType::EnteringDocument(_) => VerboseLevel::Info,
LineType::Library(_) => VerboseLevel::Context,
LineType::PackageWarning(_) => VerboseLevel::Box,
LineType::PackageContextWarning(_) => 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,
}
}
}
/// 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(
args: &MakeConfig,
orginal_line: &str,
status: &mut Status,
context: &mut [String],
run: &mut BuildInfo,
started: &Instant,
pb: &ProgressBar,
) -> Result<()> {
// Match the line to guess what is happening
let mut lex = LineType::lexer(orginal_line);
@ -376,11 +144,6 @@ fn checkline(
_ => LineType::Unknown(orginal_line.to_string()),
};
// Early exit if the verbosity level doenst match
if parsed_line.vlvl() < args.verbosity {
return Ok(());
}
// Post processing for some lines that can't be properly handlend by the lexer
let final_line = match parsed_line {
// LineType::Mode => todo!(),
@ -388,19 +151,32 @@ fn checkline(
// LineType::StartingSequence => todo!(),
// LineType::EndSequence => todo!(),
// LineType::MPSConverter => todo!(),
// LineType::Chapter(_) => todo!(),
ref a @ LineType::Chapter(ref chap) => {
run.add_lap(started, chap);
a
}
LineType::MissingReferencePrs => &LineType::MissingReference(orginal_line.to_string()),
// LineType::Warning(_) => todo!(),
// LineType::PdfTexVersion => todo!(),
LineType::PdfTexVersion(_) => &LineType::PdfTexVersion(orginal_line.to_string()),
// LineType::Context(_) => todo!(),
// TODO: Add
// LineType::BoxFullness => todo!(),
LineType::BoxFullnessPrs => &LineType::BoxFullness(orginal_line.to_string()),
// LineType::LaTexVersion => todo!(),
// LineType::WriteMode => todo!(),
// LineType::DocumentClass => todo!(),
// LineType::EnteringDocument(_) => todo!(),
// LineType::Library(_) => todo!(),
// LineType::PackageWarning(_) => todo!(),
LineType::PackageWarningPrs((ref pkg, ref wrn)) => match pkg.as_str() {
"Package tabularray Warning" => {
&LineType::LowPackageWarning(("tabulararray".to_string(), wrn.clone()))
}
_ => {
let mut name = pkg.split(" ");
&LineType::PackageWarning((
name.nth(1).unwrap_or("unknown").to_string(),
wrn.clone(),
))
}
},
// LineType::PackageContextWarning(_) => todo!(),
// LineType::Loading(_) => todo!(),
// LineType::Unknown(_) => todo!(),
@ -414,16 +190,68 @@ fn checkline(
_ => &parsed_line,
};
match &parsed_line.vlvl() {
// Early exit if the verbosity level doenst match
if parsed_line.vlvl() < args.verbosity {
return Ok(());
}
match &final_line.vlvl() {
VerboseLevel::None => (),
VerboseLevel::Misc => println!("[MISC] {:?}", final_line),
VerboseLevel::Box => println!("[BOXX] {:?}", final_line),
VerboseLevel::Context => println!("[CNTX] {:?}", final_line), // Context tends to be shit ?
VerboseLevel::Info => println!("[INFO] {:?}", final_line),
VerboseLevel::Warning => println!("[WARN] {:?}", final_line),
VerboseLevel::Error => println!("[CRIT] {:?}", final_line),
VerboseLevel::Critical => println!("[CRIT] {:?}", final_line),
VerboseLevel::Uncatchable => println!("[UKNW] {}", orginal_line),
VerboseLevel::Misc => pb.println(format!(
"{} {:?}",
*TXT_MISC,
COL_NORMAL.apply_to(final_line)
)),
VerboseLevel::Box => pb.println(format!(
"{} {:?}",
*TXT_BOXX,
COL_NORMAL.apply_to(final_line)
)),
VerboseLevel::Context => pb.println(format!(
"{} {:?}",
*TXT_CNTX,
COL_NORMAL.apply_to(final_line)
)), // Context tends to be shit ))?
VerboseLevel::Info => {
status.info += 1;
pb.println(format!(
"{} {:?}",
*TXT_INFO,
COL_NORMAL.apply_to(final_line)
))
}
VerboseLevel::Warning => {
status.warnings += 1;
pb.println(format!(
"{} {:?}",
*TXT_WARN,
COL_NORMAL.apply_to(final_line)
))
}
VerboseLevel::Error => {
status.errors += 1;
pb.println(format!(
"{} {:?}",
*TXT_ERRR,
COL_NORMAL.apply_to(final_line)
))
}
VerboseLevel::Critical => {
status.errors += 1;
pb.println(format!(
"{} {:?}",
*TXT_CRIT,
COL_NORMAL.apply_to(final_line)
))
}
VerboseLevel::Uncatchable => {
// status.errors += 1;
pb.println(format!(
"{} {}",
*TXT_UKNW,
COL_NORMAL.apply_to(orginal_line)
))
}
}
Ok(())
}

446
src/makepdf_structs.rs Normal file
View File

@ -0,0 +1,446 @@
//! Holds all the structs for the makepdf module
use logos::Logos;
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
sync::LazyLock,
time::{Duration, Instant},
};
use console::Style;
use phf::phf_map;
use crate::makepdf::MakeConfig;
/// Color Scheme for the NORMAL level
pub(crate) static COL_NORMAL: LazyLock<Style> = LazyLock::new(Style::new);
/// Color Scheme for the MISC level
pub(crate) static COL_MISC: LazyLock<Style> = LazyLock::new(|| Style::new().color256(44));
/// Color Scheme for the BOX level
pub(crate) static COL_BOX: LazyLock<Style> = LazyLock::new(|| Style::new().color256(37));
/// Color Scheme for the CONTEXT level
pub(crate) static COL_CONTEXT: LazyLock<Style> = LazyLock::new(|| Style::new().color256(30));
/// Color Scheme for the INFO level
pub(crate) static COL_INFO: LazyLock<Style> = LazyLock::new(|| Style::new().color256(2));
/// Color Scheme for the WARNING level
pub(crate) static COL_WARNING: LazyLock<Style> = LazyLock::new(|| Style::new().color256(166));
/// Color Scheme for the ERROR level
#[allow(dead_code)]
pub(crate) static COL_ERROR: LazyLock<Style> = LazyLock::new(|| Style::new().color256(52));
/// Color Scheme for the CRITICAL level
pub(crate) static COL_CRITICAL: LazyLock<Style> = LazyLock::new(|| Style::new().color256(1));
/// Color Scheme for the UNCATCHABLE level
pub(crate) static COL_UNCATCHABLE: LazyLock<Style> =
LazyLock::new(|| Style::new().color256(124).bold());
/// Filler box for the [MISC] text box
pub(crate) static TXT_MISC: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_MISC.apply_to(&"[MISC]")));
/// Filler box for the [BOXX] text box
pub(crate) static TXT_BOXX: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_BOX.apply_to(&"[BOXX]")));
/// Filler box for the [CNTX] text box
pub(crate) static TXT_CNTX: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CONTEXT.apply_to(&"[CNTX]")));
/// Filler box for the [INFO] text box
pub(crate) static TXT_INFO: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_INFO.apply_to(&"[INFO]")));
/// Filler box for the [WARN] text box
pub(crate) static TXT_WARN: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_WARNING.apply_to(&"[WARN]")));
/// Filler box for the [CRIT] text box
pub(crate) static TXT_CRIT: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[CRIT]")));
/// Filler box for the [ERRR] text box
pub(crate) static TXT_ERRR: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[ERRR]")));
/// Filler box for the [UKNW] text box
pub(crate) static TXT_UKNW: LazyLock<String> =
LazyLock::new(|| format!("{}", COL_UNCATCHABLE.apply_to(&"[UKNW]")));
/// The verbosity level
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum VerboseLevel {
/// Shouldn't be printed no matter what
None,
/// Garbage
Misc,
/// Boxness, barely above Misc
Box,
/// Context info (Debug info)
Context,
/// Usefull info
Info,
/// Important warnings
Warning,
/// Errors encountered requiring user input
Error,
/// Uncatachable errors
Critical,
/// Literrally uncatchable things
Uncatchable,
}
static STR_TO_TARGET: phf::Map<&'static str, VerboseLevel> = phf_map! {
"misc" =>VerboseLevel::Misc,
"box" => VerboseLevel::Box,
"context" => VerboseLevel::Context,
"info" => VerboseLevel::Info,
"warning" => VerboseLevel::Warning,
"error" => VerboseLevel::Error,
"critical" => VerboseLevel::Critical,
};
impl From<&str> for VerboseLevel {
fn from(value: &str) -> Self {
if let Some(target) = STR_TO_TARGET.get(&value.to_lowercase()).cloned() {
target
} else {
let mut targets = STR_TO_TARGET.values().collect::<Vec<&VerboseLevel>>();
targets.sort();
panic!(
"Invalid debug level {}. The debug level available are (from highest verbosity to lowest): {:?}",
value, targets
)
}
}
}
/// Keeps tracks of the stats of the last(s) run to offer accurate estimation
#[derive(Serialize, Deserialize)]
pub(crate) 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(crate) 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(crate) 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
pub(crate) fn add_lap(&mut self, started: &Instant, chap: &String) {
let _ = chap;
self.time_spent.push(started.elapsed());
}
}
/// The line encountered
// #[allow(unused)]
#[derive(Debug, Logos, PartialEq)]
#[logos(skip r"[) ]+")]
pub(crate) 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(" ){/")]
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(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", |_| "".to_string())]
PdfTexVersion(String),
/// Context, mosty for boxes
// TODO: False positives / Reparsing Context("10") )) [107] (./Ecoles/Protecteur.tex
#[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.")]
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()))]
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..]))]
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,
}
impl LineType {
/// Decides all verbose levels, for output
pub(crate) 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::Warning(_) => VerboseLevel::Warning,
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::PackageContextWarning(_) => 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::BoxFullness(_) => VerboseLevel::Box,
LineType::PackageWarning(_) => VerboseLevel::Warning,
LineType::LowPackageWarning(_) => VerboseLevel::Box,
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() {
if 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(crate) struct Status {
/// Number of encountered info (mainly o/ufull)
pub(crate) info: usize,
/// Number of warnings, mainly label/reference rerun
pub(crate) warnings: usize,
/// Only makes sense with non-interactie builds
pub(crate) errors: usize,
/// List of all recoverable
pub(crate) v_errors: Vec<String>,
}
impl Status {
/// Add a recoverable error to the list of errors
pub(crate) fn add_error(&mut self, error_msg: String) {
self.errors += 1;
self.v_errors.push(error_msg);
}
}
impl Status {
/// Initialize a new status
pub(crate) fn zero() -> Self {
Self {
info: 0,
warnings: 0,
errors: 0,
v_errors: Vec::new(),
}
}
/// Print a pretty message
pub(crate) fn print(&self, run_info: &BuildInfo) {
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
))
);
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?}",
COL_CONTEXT.apply_to("[===>]"),
i + 1,
*d
))
.collect::<Vec<String>>()
.join("\n")
)
}
}
}

View File

@ -164,7 +164,7 @@ impl Creature {
/// Can the stat be picked positively (aka, test the length and wether the stat was already selected)
/// This test only works if the algo is done in the correct order
#[deprecated]
// TODO: #[deprecated]
fn can_pick(&self, stat: AffName) -> bool {
debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat);
self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat)
@ -172,7 +172,7 @@ impl Creature {
/// Can the stat be picked negatively (aka, is the length ok and does the vector already contains the value)
/// This test only works if the algo is done in the correct order
#[deprecated]
// TODO: #[deprecated]
fn can_pick_negatively(&self, stat: AffName) -> bool {
debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat);
self.selected_negative_affinities.is_empty() && !self.selected_affinities.contains(&stat)