vnetod/src/main.rs

80 lines
2.3 KiB
Rust

//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@ideascup.me>
//!
//! 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 <https://www.gnu.org/licenses/>.
//!
#![deny(clippy::all, clippy::pedantic)]
mod cli;
use std::path::Path;
use std::{
fs::File,
io::{BufWriter, Write},
};
use clap::Parser;
fn main() -> Result<(), Error> {
let cli = cli::Args::parse();
change_env_layout(&cli.file, &cli.section_names)?;
Ok(())
}
fn change_env_layout(file: &Path, section_names: &[String]) -> Result<(), Error> {
let content = std::fs::read_to_string(file).map_err(|_| Error::OpenFile)?;
let mut writer = File::create(file)
.map_err(|_| Error::OpenFile)
.map(BufWriter::new)?;
let mut current_section_name: Option<String> = 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() {
let trimmed_line = line.trim_start_matches(['#', ' ']);
if section_names.contains(&cur_name) {
String::from(trimmed_line)
} else {
format!("# {}", trimmed_line)
}
} 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()
}
#[derive(Debug)]
enum Error {
OpenFile,
WriteData,
}