ravenous-tools/crates/make/src/makepdf_functions.rs

315 lines
10 KiB
Rust

// Workspace: make
// File: make/src/makepdf_functions.rs
//! The module `makepdf_functions` is a collection of helper functions used in the main build process.
//!
//! It provides various utilities for preparing, building, and cleaning up LaTeX files.
//! These functions are primarily responsible for checking and adding input lines based
//! on specified conditions, generating glossaries, and managing temporary files.
//!
use std::{
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
process::Command,
str::from_utf8,
sync::LazyLock,
};
use anyhow::Result;
use cli_parser::MakeConfig;
use indexmap::IndexMap;
use regex::Regex;
use crate::makepdf_structs::{COL_ERROR, COL_INFO, COL_MISC, COL_WARNING};
/// Regex detecting wether an input line is present
static INPUT_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"^\\input\{"?([^\}]+)\}"?"#).unwrap());
/// The chapter name list
static CHAPT_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#" *\\chapter\*?\{"?([^\}]+)\}"?"#).unwrap());
/// The info returned by a make_file
pub(super) 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(super) 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();
let mut first = true;
// Warn about wrong keys
clear_keys(args, &m);
f.read_to_string(&mut contents)
.expect("Couldn't read the file");
for line in contents.lines() {
if let Some(c) = INPUT_REGEX.captures(line) {
// Check if it's the first inport, then adds the version number
if first {
first = false;
writeln!(of, "\\def\\buildversion{{ {} }}", get_build_version())
.expect("Couldn't write version number");
}
// Check wether it should be added
if add_checker(&c[1], &m, args) {
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 if args.no_context {
println!(
"{} {} {}",
COL_INFO.apply_to("[PREP]"),
COL_WARNING.apply_to("Excluding"),
&c[1]
);
}
} else {
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,
}
}
/// Execute an external git command
macro_rules! exec_cmd {
($cmd:expr, $args:expr) => {
{
let mut cmd = Command::new($cmd);
cmd.args($args);
match cmd.output() {
Ok(v) => from_utf8(&v.stdout)
.expect("Couldn't parse the git tag result")
.to_owned(),
Err(e) => {
println!(
"[ERRR] An error has occured while trying to retrieve the Ravenous Version\n {:#?}",
e
);
"Unknown".to_string()
}
}
}
};
}
/// Ask git for the current version
fn get_build_version() -> String {
let tag = exec_cmd!("git", ["describe", "--tags", "--abbrev=0"]).replace("\n", "");
let hsh = exec_cmd!("git", ["rev-parse", "--short", "HEAD"]).replace("\n", "");
// let thsh = exec_cmd!("git", ["show-ref", tag.as_str(), "-s"]);
let vnmbr = exec_cmd!(
"git",
["rev-list", format!("{}..HEAD", tag).as_str(), "--count"]
)
.replace("\n", "");
format!("Version: {}r{} ({})", tag, vnmbr, hsh)
}
/// Clear the list of keys (for now only warn)
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 :\n{:?} rerun with option -t list for the full list",
COL_ERROR.apply_to("[ERRR]"),
k,
dict_entries.keys()
)
}
}
for k in args.no.iter() {
if !dict_entries.contains_key(k) {
panic!(
"{} 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()
)
}
}
}
/// Algorithm to check wether to add or not the entry
fn add_checker(check: &str, dict_entries: &IndexMap<String, String>, args: &MakeConfig) -> bool {
if args.only.is_empty() && args.no.is_empty() {
return true;
}
for k in args.only.iter() {
if dict_entries.contains_key(k) && dict_entries[k] == check {
return true;
}
}
if !args.no.is_empty() {
for k in args.no.iter() {
if dict_entries.contains_key(k) && dict_entries[k] == check {
return false;
}
}
return true;
}
false
}
/// List all chapters targetable by ignore and only
pub(super) fn make_list(args: &MakeConfig) {
let m = make_ignore_targets(args);
println!("The ignore targets are the following:");
println!("{:#?}", m);
}
/// Make the dict of targets
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();
for line in contents.lines() {
if let Some(c) = INPUT_REGEX.captures(line) {
// println!("[TRGT] {:?}", &c[1]);
simplify_add(c[1].to_string(), &mut map).unwrap();
}
}
map
}
/// Create a target name, by appending _build to it
pub(super) fn target_name(target: &str) -> PathBuf {
let target = Path::new(target);
let mut target_oss = target.file_stem().unwrap().to_owned();
target_oss.push("_build.tex");
target_oss.into()
}
/// Create a target suffix and by append _build
pub(super) fn target_pref(target: &str) -> String {
let target = Path::new(target);
let target_oss = target.file_stem().unwrap().to_owned();
let v = format!("{:?}", target_oss);
v[1..v.len() - 1].to_string()
}
/// Try to add a simplified entry to a list
pub(super) fn simplify_add(
entry: 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) {
return Ok(());
}
// Strategy one: use the last part after /
if let Some(e) = entry.split("/").nth(1) {
let e = e.to_lowercase();
if e.len() >= 3 {
for i in 3..e.len() {
if !dict_entries.contains_key(&e[..i]) {
dict_entries.insert(e[..i].to_owned(), entry);
return Ok(());
}
}
}
{
if !dict_entries.contains_key(&e) {
dict_entries.insert(e.to_owned(), entry);
return Ok(());
}
}
}
// Strategy two use first part before / and add _ to last
let mut spl = entry.split("/");
if let (Some(p), Some(s)) = (spl.next(), spl.next()) {
let (p, s) = (p.to_lowercase(), s.to_lowercase());
let key = format!("{:1}_{}", p, s);
if !dict_entries.contains_key(&key) {
dict_entries.insert(key.to_owned(), entry);
return Ok(());
}
}
// Last ditch strategy
let e = entry.replace("/", "_").to_lowercase();
dict_entries.insert(e, entry);
Ok(())
}
/// Make the glossaries
pub(super) fn make_glossaries(args: &MakeConfig) {
use std::str;
// let name = format!("{:?}", target_name(&args.filename));
// let name = &name[1..name.len() - 1];
// println!("{}", name);
let name = target_pref(&args.filename);
match Command::new("makeglossaries")
.arg(format!("{}_build", name))
.output()
{
Err(e) => {
println!(
"An error has occured while trying to build the glossaries\n{:#?}",
e
)
}
Ok(o) => {
println!("Program exited with status {}", o.status);
if !o.stdout.is_empty() {
println!("{}", str::from_utf8(&o.stdout).unwrap_or(""));
}
if !o.stderr.is_empty() {
println!("{}", str::from_utf8(&o.stderr).unwrap_or(""));
}
}
}
}
/// Make the working directory clean, by eliminating all temporary files
pub(super) fn make_clean(args: &MakeConfig) {
let _ = args;
// let target = format!("{:?}", Path::new(&args.filename).file_stem().unwrap());
let target = target_pref(&args.filename);
let list_suff = [
".aux", ".glg", ".glo", ".gls", ".ist", ".log", ".out", ".toc", ".pdf", ".dvi", ".fls",
];
let mut cmd = Command::new("rm");
for s in list_suff {
// The most ghetto *** I've done so far
// cmd.arg(format!("{}{}", &target, s));
cmd.arg(format!("{}_build{}", &target, s));
}
cmd.arg(format!("{}_build{}", &target, ".tex"));
// println!("{:?}", cmd);
if let Err(e) = cmd.output() {
println!(
"[ERRR] An error has occured when executing the clean target \n {:#?}",
e
)
}
}