use std::fs::{self, read_to_string}; pub struct CGitRepoInfo { pub section: String, pub url: String, pub path: String, pub owner: String, pub description: String, } pub fn cgit_add_repo(cgit_repos_file_path: String, info: CGitRepoInfo) { let mut lines: Vec = vec![]; read_to_string(&cgit_repos_file_path) .expect("file read error.") .lines() .for_each(|line| { if line == "\n" || line.is_empty() || line == " " || line.starts_with('#') { return; } lines.push(String::from(line)); }); let mut target_line_index: Option = None; for (i, l) in lines.iter().enumerate() { // println!("DEBUG: PARSING: {}", l); let (header, value) = l.split_once("=").expect("expected full line"); if header == "section" && value == info.section { // we've found our desired section target_line_index = Some(i + 1); } } let mut new_lines = vec![ format!("repo.url={}", info.url), format!("repo.path={}", info.path), format!("repo.desc={}", info.description), format!("repo.owner={}", info.owner), ]; if Option::is_none(&target_line_index) { // there is no section, shall create new new_lines.insert(0, format!("section={}", info.section)); lines.append(&mut new_lines); } for (index, new_line) in new_lines.iter().enumerate() { lines.insert( target_line_index.expect("should expect target line index to exist") + index, new_line.to_string(), ); } let final_text = lines.join("\n"); // println!("DEBUG:: Writing following to cgitrepos: \n{}", final_text); fs::write(&cgit_repos_file_path, final_text).expect("cgit repo write err"); }