diff options
Diffstat (limited to 'src/new/section.rs')
-rw-r--r-- | src/new/section.rs | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/new/section.rs b/src/new/section.rs new file mode 100644 index 0000000..31742c2 --- /dev/null +++ b/src/new/section.rs @@ -0,0 +1,63 @@ +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::<Local>::from(SystemTime::now()).format("%Y-%m-%d") + ), + ), + )?; + Ok(()) +} + +pub fn get_section_root() -> io::Result<PathBuf> { + 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", + )) +} |