Add Context and ignore

This commit is contained in:
Dandaedre 2024-06-24 03:44:42 +02:00
parent e31a7fd33b
commit 6b303294f1
4 changed files with 102 additions and 66 deletions

View File

@ -16,6 +16,7 @@ dynfmt = { version = "0.1.5", features = ["curly"] }
enum_dispatch = "0.3.13"
futures = "0.3.30"
glob = "0.3.1"
indexmap = "2.2.6"
indicatif = "0.17.8"
logos = "0.14.0"
phf = { version = "0.11.2", features = ["macros"] }

View File

@ -15,13 +15,15 @@ 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_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_NORMAL, TXT_BOXX, TXT_CNTX,
TXT_CRIT, TXT_ERRR, TXT_INFO, TXT_MISC, TXT_UKNW, TXT_WARN,
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;
@ -55,6 +57,10 @@ pub(crate) struct MakeConfig {
/// Deselect these targets
#[arg(short, long, value_name = "FILE", group = "select")]
pub(crate) no: Vec<String>,
/// Wether to add the initial and final context
#[arg(short = 'C', long, action = clap::ArgAction::SetFalse)]
pub(crate) no_context: bool,
}
/// Make a pdf spawning a subprocess
@ -70,8 +76,8 @@ pub(crate) fn make_pdf(args: &MakeConfig, _config: &Config) -> Result<()> {
match args.target {
Some(MakeTargets::All) => {
// Make the target to build
let file = make_file(args);
make_all(args, file)
let file_r = make_file(args);
make_all(args, file_r);
}
Some(MakeTargets::List) => make_list(args),
Some(MakeTargets::Glossaries) => make_glossaries(args),
@ -85,13 +91,16 @@ pub(crate) fn make_pdf(args: &MakeConfig, _config: &Config) -> Result<()> {
}
/// Make all targets
fn make_all(args: &MakeConfig, rebuild_target: String) {
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: String) -> Result<Status> {
async fn launch_subprocess(
args: &MakeConfig,
rebuild_target: BuilderParseResult,
) -> Result<Status> {
let mut cmd = Command::new("pdflatex");
let mut status = Status::zero();
@ -105,7 +114,7 @@ async fn launch_subprocess(args: &MakeConfig, rebuild_target: String) -> Result<
if args.non_interactive {
cmd.arg("--interaction=nonstopmode");
}
cmd.arg(&rebuild_target);
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());
@ -159,8 +168,14 @@ async fn launch_subprocess(args: &MakeConfig, rebuild_target: String) -> Result<
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));
status.errors += 1;
if args.verbosity <= VerboseLevel::Info {
pb.println(format!(
"{} An invalid UTF-8 sequence was parsed {:?}",
COL_INFO.apply_to("[CORE]"),
e
))
}
continue;
}
};
@ -173,7 +188,7 @@ async fn launch_subprocess(args: &MakeConfig, rebuild_target: String) -> Result<
}
current_run.time_ellapsed = started.elapsed();
pb.finish_and_clear();
status.print(&current_run);
status.print(args, &current_run, rebuild_target);
current_run.save();
Ok(status)
}

View File

@ -1,7 +1,6 @@
//! Helper functions
use std::{
collections::HashMap,
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
@ -10,6 +9,7 @@ use std::{
};
use anyhow::Result;
use indexmap::IndexMap;
use regex::Regex;
use crate::{
@ -19,16 +19,28 @@ use crate::{
/// Regex detecting wether an input line is present
static INPUT_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#" *\\input\{"?([A-z/-_]+)\}"?"#).unwrap());
LazyLock::new(|| Regex::new(r#"^\\input\{"?([^\}]+)\}"?"#).unwrap());
/// The chapter name list
static CHAPT_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#" *\\chapter\*?\{"?([^\}]+)\}"?"#).unwrap());
/// Make the (new/purged) target file and return it's name
pub(crate) fn make_file(args: &MakeConfig) -> String {
/// The info returned by a make_file
pub(crate) struct BuilderParseResult {
/// The new name
pub(super) new_name: String,
/// The list of chapter encountered
pub(super) chapt_list: Vec<String>,
}
/// Make the (new/purged) target file and return (name,chapter_list)
pub(crate) fn make_file(args: &MakeConfig) -> BuilderParseResult {
let path = target_name(&args.filename);
let m = make_ignore_targets(args);
let mut f = File::open(&args.filename).expect("The file doesn't exist");
let mut of = File::create(&path).unwrap();
let mut contents = String::new();
let mut chapters = Vec::new();
// Warn about wrong keys
clear_keys(args, &m);
@ -37,15 +49,17 @@ pub(crate) fn make_file(args: &MakeConfig) -> String {
if let Some(c) = INPUT_REGEX.captures(line) {
// Check wether it should be added
if add_checker(&c[1], &m, args) {
println!(
"{} {} {}",
COL_INFO.apply_to("[PREP]"),
COL_MISC.apply_to("Including"),
&c[1]
);
if args.no_context {
println!(
"{} {} {}",
COL_INFO.apply_to("[PREP]"),
COL_MISC.apply_to("Including"),
&c[1]
);
}
of.write_all(line.as_bytes()).unwrap();
of.write_all("\n".as_bytes()).unwrap();
} else {
} else if args.no_context {
println!(
"{} {} {}",
COL_INFO.apply_to("[PREP]"),
@ -57,16 +71,23 @@ pub(crate) fn make_file(args: &MakeConfig) -> String {
of.write_all(line.as_bytes()).unwrap();
of.write_all("\n".as_bytes()).unwrap();
}
if let Some(c) = CHAPT_REGEX.captures(line) {
chapters.push(c[1].to_string());
}
}
BuilderParseResult {
new_name: format!("{:?}", &path),
chapt_list: chapters,
}
format!("{:?}", &path)
}
/// Clear the list of keys (for now only warn)
fn clear_keys(args: &MakeConfig, dict_entries: &HashMap<String, String>) {
fn clear_keys(args: &MakeConfig, dict_entries: &IndexMap<String, String>) {
for k in args.only.iter() {
if !dict_entries.contains_key(k) {
panic!(
"{} The key {} wasn't in the list of togglable imports {:?} rerun with option -t list for the full list",
"{} The key {} wasn't in the list of togglable imports :\n{:?} rerun with option -t list for the full list",
COL_ERROR.apply_to("[ERRR]"),
k,
dict_entries.keys()
@ -76,7 +97,7 @@ fn clear_keys(args: &MakeConfig, dict_entries: &HashMap<String, String>) {
for k in args.no.iter() {
if !dict_entries.contains_key(k) {
panic!(
"{} The key {} wasn't in the list of togglable imports {:?} rerun with option -t list for the full list",
"{} The key {} wasn't in the list of togglable imports:\n {:?} rerun with option -t list for the full list",
COL_ERROR.apply_to("[ERRR]"),
k,
dict_entries.keys()
@ -86,7 +107,7 @@ fn clear_keys(args: &MakeConfig, dict_entries: &HashMap<String, String>) {
}
/// Algorithm to check wether to add or not the entry
fn add_checker(check: &str, dict_entries: &HashMap<String, String>, args: &MakeConfig) -> bool {
fn add_checker(check: &str, dict_entries: &IndexMap<String, String>, args: &MakeConfig) -> bool {
if args.only.is_empty() && args.no.is_empty() {
return true;
}
@ -113,8 +134,8 @@ pub(crate) fn make_list(args: &MakeConfig) {
}
/// Make the dict of targets
fn make_ignore_targets(args: &MakeConfig) -> HashMap<String, String> {
let mut map: HashMap<String, String> = HashMap::new();
fn make_ignore_targets(args: &MakeConfig) -> IndexMap<String, String> {
let mut map: IndexMap<String, String> = IndexMap::new();
let mut f = File::open(&args.filename).unwrap();
let mut contents = String::new();
f.read_to_string(&mut contents).unwrap();
@ -147,7 +168,7 @@ pub(crate) fn target_pref(target: &str) -> String {
/// Try to add a simplified entry to a list
pub(crate) fn simplify_add(
entry: String,
dict_entries: &mut HashMap<String, String>,
dict_entries: &mut IndexMap<String, String>,
) -> Result<()> {
// If the value was already inside, no need to add it
if dict_entries.values().any(|e| e == &entry) {

View File

@ -10,7 +10,7 @@ use std::{
use console::Style;
use crate::makepdf::MakeConfig;
use crate::{makepdf::MakeConfig, makepdf_functions::BuilderParseResult};
/// Color Scheme for the NORMAL level
pub(crate) static COL_NORMAL: LazyLock<Style> = LazyLock::new(Style::new);
@ -214,7 +214,8 @@ pub(crate) enum LineType {
MissingReference(String),
/// Generic Latex Warning
#[regex("LaTeX Warning:")]
#[regex("pdf([Ll]a)?[tT]e[Xx] [wW]arning")]
#[regex("[Ll]a[tT]e[Xx] [wW]arning")]
WarningPrs,
/// Reparsed Warning
@ -382,17 +383,8 @@ pub(crate) struct Status {
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
// TODO: Print this at the end of the parse
pub(crate) fn add_error(&mut self, error_msg: String) {
// self.errors += 1;
self.v_errors.push(error_msg);
}
// /// List of all recoverable
// pub(crate) v_errors: Vec<String>,
}
impl Status {
@ -402,12 +394,16 @@ impl Status {
info: 0,
warnings: 0,
errors: 0,
v_errors: Vec::new(),
}
}
/// Print a pretty message
pub(crate) fn print(&self, run_info: &BuildInfo) {
pub(crate) fn print(
&self,
args: &MakeConfig,
run_info: &BuildInfo,
file_info: BuilderParseResult,
) {
let col_bld = COL_INFO.clone().bold();
println!();
println!(
@ -426,27 +422,30 @@ impl Status {
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() {
if args.no_context {
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")
)
"{} {}",
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,
file_info.chapt_list.get(i).unwrap_or(&"???".to_string()),
*d
))
.collect::<Vec<String>>()
.join("\n")
)
}
}
}
}