ravenous-tools/src/makepdf.rs

356 lines
12 KiB
Rust

//! Make a pdf using pdflatex
use std::time::{Duration, Instant};
// use std::str::pattern::Pattern;
use std::fmt::Write;
use dynfmt::FormatArgs;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use logos::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::makepdf_functions::{
make_clean, make_file, make_glossaries, make_list, BuilderParseResult,
};
use crate::makepdf_misc::{
BLOCK_PROGRESSION, HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL,
};
use crate::makepdf_structs::{
BuildInfo, LineType, MakeTargets, Status, VerboseLevel, COL_INFO, 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)]
// #[command(after_)]
/// The configuration struct for the PdfMaker
pub(super) struct MakeConfig {
/// The filename to compile
pub(super) filename: String,
/// Special target
#[arg(short, long, help = format!("Build with a special target. [{}]", HELP_BUILD_TARGET_LIST.as_str()))]
pub(super) target: Option<MakeTargets>,
/// The verbosity level
#[arg(short, long, default_value = "warning", help = format!("The verbosity level. [{}]",HELP_VERBOSITY_LEVEL.as_str()))]
pub(super) verbosity: VerboseLevel,
/// The progress bar style
#[arg(short, long, default_value = "class", help = format!("The progress bar style. [{}]",HELP_BLOCK_SELECTION.as_str()))]
pub(super) pbar: String,
/// switch to non interactive mode
#[arg(short = 'N', long, default_value_t = false)]
pub(super) non_interactive: bool,
/// Select only these targets
#[arg(short, long, value_name = "FILE", group = "select")]
pub(super) only: Vec<String>,
/// Deselect these targets
#[arg(short, long, value_name = "FILE", group = "select")]
pub(super) no: Vec<String>,
/// Wether to add the initial and final context
#[arg(short = 'C', long, action = clap::ArgAction::SetFalse)]
pub(super) no_context: bool,
/// Activate shell escape
#[arg(short, long)]
pub(super) shell_escape: bool,
}
/// Make a pdf spawning a subprocess
pub(super) fn make_pdf(args: &MakeConfig, _config: &Config) -> Result<()> {
let Ok(Some(_)) = BLOCK_PROGRESSION.get_key(&args.pbar) else {
panic!(
"Progressbar {} doesn't exists. Use one of the following [{:?}]",
args.pbar, HELP_BLOCK_SELECTION
);
};
// Identify special targets: Clean, Glossaries, All, List etc.
match args.target {
Some(MakeTargets::All) => {
// Make the target to build
let file_r = make_file(args);
make_all(args, file_r);
}
Some(MakeTargets::List) => make_list(args),
Some(MakeTargets::Glossaries) => make_glossaries(args),
Some(MakeTargets::Clean) => make_clean(args),
None => {
let file = make_file(args);
launch_subprocess(args, file).unwrap();
}
}
Ok(())
}
/// Make all targets
fn make_all(args: &MakeConfig, rebuild_target: BuilderParseResult) {
launch_subprocess(args, rebuild_target).unwrap();
}
#[tokio::main]
/// Pdfreading and curating
async fn launch_subprocess(
args: &MakeConfig,
rebuild_target: BuilderParseResult,
) -> Result<Status> {
let mut cmd = Command::new("pdflatex");
let mut status = Status::zero();
let started = Instant::now();
let mut last_total_duration = Duration::from_secs(0);
let mut current_run = BuildInfo::new(args);
let last_run = BuildInfo::load(args);
let mut built = 0;
let mut to_build = last_run.lines_parsed;
if args.non_interactive {
cmd.arg("--interaction=nonstopmode");
}
if args.shell_escape {
cmd.arg("--shell-escape");
}
cmd.arg(&rebuild_target.new_name);
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");
// 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(&BLOCK_PROGRESSION[&args.pbar]),
);
pb.enable_steady_tick(Duration::from_millis(100));
loop {
let res = reader.next_segment().await;
// let new = min(built + 1, to_build);
let new = if built < to_build {
built + 1
} else {
to_build += 1;
pb.set_length(to_build);
built + 1
};
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 {
if let Some(line) = line {
let s = match str::from_utf8(&line) {
Ok(v) => v,
Err(e) => {
// status.errors += 1;
if args.verbosity <= VerboseLevel::Info {
let valid = str::from_utf8(&line[..e.valid_up_to()]).unwrap_or("");
pb.println(format!(
"{} An invalid UTF-8 sequence was parsed {:?}",
COL_INFO.apply_to("[CORE]"),
e
));
pb.println(format!(
"{} The valid part is: {}",
COL_INFO.apply_to("[CORE]"),
valid
))
}
continue;
}
};
checkline(
args,
s,
&mut status,
&mut current_run,
&started,
&pb,
&mut last_total_duration,
)
.expect("Error while checking line");
} else {
break;
}
}
}
current_run.time_ellapsed = started.elapsed();
pb.finish_and_clear();
status.print(args, &current_run, rebuild_target);
current_run.save();
Ok(status)
}
/// Check each line and changes the status and/or display according warnings
fn checkline(
args: &MakeConfig,
orginal_line: &str,
status: &mut Status,
run: &mut BuildInfo,
started: &Instant,
pb: &ProgressBar,
last_total_duration: &mut Duration,
) -> Result<()> {
// Match the line to guess what is happening
let mut lex = LineType::lexer(orginal_line);
let parsed_line = match lex.next() {
Some(Ok(m)) => m,
None => LineType::Empty,
_ => LineType::Unknown(orginal_line.to_string()),
};
// Post processing for some lines that can't be properly handlend by the lexer
let final_line = match parsed_line {
// LineType::Mode => todo!(),
// LineType::Info(_) => todo!(),
// LineType::StartingSequence => todo!(),
// LineType::EndSequence => todo!(),
// LineType::MPSConverter => todo!(),
ref a @ LineType::Chapter(_) => {
run.add_lap(started, last_total_duration);
a
}
LineType::MissingReferencePrs => &LineType::MissingReference(orginal_line.to_string()),
LineType::WarningPrs => &LineType::Warning(orginal_line.to_string()),
LineType::PdfTexVersion(_) => &LineType::PdfTexVersion(orginal_line.to_string()),
// LineType::Context(_) => 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::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!(),
// LineType::PageGen => todo!(),
// LineType::Output => todo!(),
// LineType::Log => todo!(),
// LineType::Empty => todo!(),
// LineType::GeometryResolution => todo!(),
// LineType::GeometryFound => todo!(),
// LineType::Transcript => todo!(),
_ => &parsed_line,
};
// Early exit if the verbosity level doenst match
if final_line.vlvl() < args.verbosity {
return Ok(());
}
match &final_line.vlvl() {
VerboseLevel::None => (),
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(())
}