use std::{ env, fs::{self, read_dir}, io::{self, ErrorKind}, path::PathBuf, time::SystemTime, }; use chrono::{DateTime, Local}; use convert_case::{Case, Casing}; use super::SECTION; pub fn generate_new_section(name: String) -> io::Result<()> { let chapter_root = get_section_root()?; let chapter_main_file_path = read_dir(&chapter_root)? .into_iter() .map(|path| path.unwrap()) .filter(|path| path.file_name().to_str().unwrap().contains("chapter_")) .last() .unwrap() .path(); let mut main_file = fs::read_to_string(&chapter_main_file_path).unwrap(); main_file.push_str(&format!( "\\input{{content/{}/sections/{}}}\n", chapter_root.file_name().unwrap().to_str().unwrap(), &name.to_case(Case::Snake) )); fs::write(chapter_main_file_path, main_file)?; fs::write( chapter_root.join(format!("sections/{}.tex", name.to_case(Case::Snake))), SECTION.replace("REPLACMENT_SECTION_TITLE", &name).replace( "DATE", &format!( "{}", DateTime::::from(SystemTime::now()).format("%Y-%m-%d") ), ), )?; Ok(()) } pub fn get_section_root() -> io::Result { let path = env::current_dir()?; let mut path_ancestors = path.as_path().ancestors(); while let Some(path_segment) = path_ancestors.next() { if read_dir(path_segment)?.into_iter().any(|path| { path.expect("The read_dir shouldn't error out here") .file_name() .to_str() .unwrap() .contains("chapter_") }) { return Ok(PathBuf::from(path_segment)); } } Err(io::Error::new( ErrorKind::NotFound, "Ran out of places to find chapter_root", )) }