330 lines
11 KiB
Rust
330 lines
11 KiB
Rust
// Workspace: make
|
|
// File: make/src/makepdf.rs
|
|
//! The module `makepdf_functions` is responsible for making a pdf using pdflatex.
|
|
//!
|
|
//!
|
|
//! # Usage
|
|
//!
|
|
//! - [make_pdf]: Make a pdf spawning a subprocess
|
|
//!
|
|
//! # Functions
|
|
//!
|
|
//! - `launch_subprocess`: Launches the subprocess to make the pdf
|
|
//! - `checkline`: Checks each line of the subprocess output and updates the status accordingly
|
|
//!
|
|
|
|
use config::make::{BLOCK_PROGRESSION, HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel};
|
|
use std::{
|
|
fmt::Write,
|
|
process::Stdio,
|
|
str,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use cli_parser::{Config, MakeConfig};
|
|
use dynfmt::FormatArgs;
|
|
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
|
|
use logos::Logos;
|
|
use tokio::{
|
|
io::{AsyncBufReadExt, BufReader},
|
|
process::Command,
|
|
};
|
|
|
|
use anyhow::{Result, anyhow};
|
|
|
|
use crate::makepdf_functions::{
|
|
BuilderParseResult, make_clean, make_file, make_glossaries, make_list,
|
|
};
|
|
use crate::makepdf_structs::{
|
|
BuildInfo, COL_INFO, COL_NORMAL, LineType, Status, TXT_BOXX, TXT_CNTX, TXT_CRIT, TXT_ERRR,
|
|
TXT_INFO, TXT_MISC, TXT_UKNW, TXT_WARN,
|
|
};
|
|
|
|
/// Make a pdf spawning a subprocess
|
|
pub 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;
|
|
let last_duration = last_run.time_ellapsed.as_secs_f64();
|
|
|
|
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", move |state: &ProgressState, w: &mut dyn Write| {
|
|
write!(w, "{:.1}s", (last_duration - state.elapsed().as_secs_f64()).max(0.)).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, ¤t_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(())
|
|
}
|