use std::{ fs::{self, File}, io::{self, Write}, }; use convert_case::{Case, Casing}; use crate::data::Data; use super::{get_project_root, CHAPTER}; pub fn generate_new_chapter(name: String) -> io::Result<()> { let project_root = get_project_root().unwrap(); let raw_data_file = fs::read_to_string(project_root.join("lpm.toml")).unwrap(); let mut data_file: Data = toml::from_str(&raw_data_file).unwrap(); let mut main_file = fs::read_to_string(project_root.join("main.tex")).unwrap(); fs::create_dir(project_root.join(format!("content/{}", name.to_case(Case::Snake),))).unwrap(); let mut new_chapter = File::create(project_root.join(format!( "content/{}/chapter_{:02}.tex", name.to_case(Case::Snake), data_file.last_chapter.number + 1 ))).unwrap(); new_chapter.write_all(CHAPTER.replace("REPLACEMENT_CHAPTER", &name).as_bytes()).unwrap(); fs::create_dir(project_root.join(format!("content/{}/sections", name.to_case(Case::Snake),))).unwrap(); main_file = main_file.replace( &format!( "\\includeonly{{content/{}/{}}}", &data_file.last_chapter.user_name, &format!("chapter_{:02}", data_file.last_chapter.number) ), &format!( "\\includeonly{{content/{}/{}}}", name.to_case(Case::Snake), &format!("chapter_{:02}", data_file.last_chapter.number + 1) ), ); let find_index = main_file.find("% NEXT_CHAPTER").unwrap(); main_file.insert_str( find_index, &format!( "\\include{{content/{}/{}}}\n ", name.to_case(Case::Snake), &format!("chapter_{:02}", data_file.last_chapter.number + 1) ), ); data_file.last_chapter.user_name = name.to_case(Case::Snake); data_file.last_chapter.number += 1; fs::write( project_root.join("lpm.toml"), toml::to_string(&data_file).expect("We changed it ourselfes, the conversion should work"), ).unwrap(); fs::write(project_root.join("main.tex"), main_file).unwrap(); Ok(()) }