use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use tracing::info;
static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\{\{#include.*?\}\}").unwrap());
pub fn remove_includes_in_all_markdown_files_in<P>(
markdown_dir_path: P,
contents_to_insert: &str,
) -> Result<Vec<std::path::PathBuf>>
where
P: AsRef<Path>,
{
let mut modified = Vec::new();
let paths = crate::fs::find_markdown_files_in(markdown_dir_path.as_ref())?;
for p in paths {
info!("Looking into {p:?}");
let buf = fs::read_to_string(p.as_path())?;
if REGEX.is_match(&buf) {
let mut new_txt = buf.clone();
for cap in REGEX.captures_iter(&buf) {
new_txt = new_txt.replace(cap.get(0).unwrap().as_str(), contents_to_insert);
}
if new_txt != buf {
File::create(p.clone())?.write_all(new_txt.as_bytes())?;
modified.push(p);
}
}
}
Ok(modified)
}
#[cfg(test)]
mod test {
}