306 lines
10 KiB
Rust
306 lines
10 KiB
Rust
//! Make a pdf using pdflatex
|
|
|
|
use std::time::{Duration, Instant};
|
|
// use std::str::pattern::Pattern;
|
|
use std::{cmp::min, 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};
|
|
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_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(crate) struct MakeConfig {
|
|
/// The filename to compile
|
|
pub(crate) filename: String,
|
|
|
|
/// Special target
|
|
#[arg(short, long, help = format!("Build with a special target. {}", HELP_BUILD_TARGET_LIST.as_str()))]
|
|
pub(crate) target: Option<MakeTargets>,
|
|
|
|
/// The verbosity level
|
|
#[arg(short, long, default_value = "warning", help = format!("The verbosity level. {}",HELP_VERBOSITY_LEVEL.as_str()))]
|
|
pub(crate) verbosity: VerboseLevel,
|
|
|
|
/// The progress bar style
|
|
#[arg(short, long, default_value = "class", help = format!("The progress bar style. {}",HELP_BLOCK_SELECTION.as_str()))]
|
|
pub(crate) pbar: String,
|
|
|
|
/// switch to non interactive mode
|
|
#[arg(short = 'N', long, default_value_t = false)]
|
|
pub(crate) non_interactive: bool,
|
|
|
|
/// Select only these targets
|
|
#[arg(short, long, value_name = "FILE", group = "select")]
|
|
pub(crate) only: Vec<String>,
|
|
|
|
/// Deselect these targets
|
|
#[arg(short, long, value_name = "FILE", group = "select")]
|
|
pub(crate) no: Vec<String>,
|
|
}
|
|
|
|
/// Make a pdf spawning a subprocess
|
|
pub(crate) 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
|
|
);
|
|
};
|
|
|
|
// Make the target to build
|
|
let file = make_file(args);
|
|
// Identify special targets: Clean, Glossaries, All, List etc.
|
|
match args.target {
|
|
Some(MakeTargets::All) => make_all(args, file),
|
|
Some(MakeTargets::List) => make_list(args),
|
|
Some(MakeTargets::Glossaries) => make_glossaries(args),
|
|
Some(MakeTargets::Clean) => make_clean(args),
|
|
None => {
|
|
launch_subprocess(args, file).unwrap();
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Make all targets
|
|
fn make_all(args: &MakeConfig, rebuild_target: String) {
|
|
launch_subprocess(args, rebuild_target).unwrap();
|
|
}
|
|
|
|
#[tokio::main]
|
|
/// Pdfreading and curating
|
|
async fn launch_subprocess(args: &MakeConfig, rebuild_target: String) -> Result<Status> {
|
|
let mut cmd = Command::new("pdflatex");
|
|
let mut status = Status::zero();
|
|
|
|
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;
|
|
|
|
if args.non_interactive {
|
|
cmd.arg("--interaction=nonstopmode");
|
|
}
|
|
cmd.arg(&rebuild_target);
|
|
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);
|
|
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;
|
|
status.add_error(format!("[CORE] Invalid UTF-8 sequence: {}", e));
|
|
continue;
|
|
}
|
|
};
|
|
checkline(args, s, &mut status, &mut current_run, &started, &pb)
|
|
.expect("Error while checking line");
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
current_run.time_ellapsed = started.elapsed();
|
|
pb.finish_and_clear();
|
|
status.print(¤t_run);
|
|
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,
|
|
) -> 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(ref chap) => {
|
|
run.add_lap(started, chap);
|
|
a
|
|
}
|
|
LineType::MissingReferencePrs => &LineType::MissingReference(orginal_line.to_string()),
|
|
// LineType::Warning(_) => todo!(),
|
|
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(())
|
|
}
|