//! Copyright (C) 2022, Dmitriy Pleshevskiy //! //! vnetod is free software: you can redistribute it and/or modify //! it under the terms of the GNU General Public License as published by //! the Free Software Foundation, either version 3 of the License, or //! (at your option) any later version. //! //! vnetod is distributed in the hope that it will be useful, //! but WITHOUT ANY WARRANTY; without even the implied warranty of //! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //! GNU General Public License for more details. //! //! You should have received a copy of the GNU General Public License //! along with vnetod. If not, see . //! use std::{ fs::File, io::{BufWriter, Write}, }; fn main() -> Result<(), Error> { match std::env::args().nth(1) { Some(name) => change_env_layout(&name)?, _ => print_help(), }; Ok(()) } fn change_env_layout(name: &str) -> Result<(), Error> { let content = std::fs::read_to_string(".env").map_err(|_| Error::OpenFile)?; let mut writer = File::create(".env") .map_err(|_| Error::OpenFile) .map(BufWriter::new)?; let mut current_section_name: Option = None; for line in content.split_inclusive('\n') { let new_line = if is_section_end(line) { current_section_name = None; line.to_string() } else if let Some(section_info) = line.strip_prefix("### ") { current_section_name = section_info.split_whitespace().next().map(String::from); line.to_string() } else if let Some(cur_name) = current_section_name.clone() { if cur_name == name { String::from(line.trim_start_matches(['#', ' '])) } else { format!("# {}", line.trim_start_matches(['#', ' '])) } } else { line.to_string() }; writer .write_all(new_line.as_bytes()) .map_err(|_| Error::WriteData)?; } writer.flush().map_err(|_| Error::WriteData) } fn is_section_end(line: &str) -> bool { line.trim().is_empty() } fn print_help() { eprintln!( "\ USAGE vnetod [STATE_NAME] - switch environment variable state by name --- vnetod Copyright (C) 2022 Dmitriy Pleshevskiy This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. " ) } #[derive(Debug)] enum Error { OpenFile, WriteData, }