use std::{fs, path::Path}; use anyhow::Context; use log::debug; use crate::{ config_file::Config, file_tree::{FileTree, GeneratedFile}, new::{replacement::untemplatize_section, MangledName}, }; pub fn generate_new_section( config: &Config, name: String, project_root: &Path, chapter_name: &str, ) -> anyhow::Result { let chapter_root = project_root.join("content").join(chapter_name); debug!("Chapter root is: {}", chapter_root.display()); let mut file_tree = FileTree::new(); let display_chapter_name = MangledName::from_str_unsafe( chapter_name .chars() .skip_while(|a: &char| a.is_digit(10) || *(a) == '_') .collect::() .as_str(), ) .try_unmangle(); let new_section_text = untemplatize_section(&config.templates.section, &name, &display_chapter_name); file_tree.add_file(GeneratedFile::new_clobber( chapter_root .join("sections") .join(format!("{}.tex", MangledName::new(&name))), new_section_text, false, )); let chapter_file_path = chapter_root.join("chapter.tex"); let mut chapter_file_text = fs::read_to_string(&chapter_file_path).with_context(|| { format!( "Failed to read the chapter main file ('{}') to string", &chapter_file_path.display(), ) })?; chapter_file_text.push_str(&format!( "\\input{{content/{}/sections/{}}}\n", chapter_name, &MangledName::new(&name) )); let chapter_file = GeneratedFile::new(chapter_file_path, chapter_file_text); file_tree.add_file(chapter_file); Ok(file_tree) }