82 lines
2.4 KiB
Rust
82 lines
2.4 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::{
|
|
fs::File,
|
|
io::{BufWriter, Write},
|
|
};
|
|
|
|
use clap::Parser;
|
|
|
|
fn main() -> Result<(), Error> {
|
|
let cli = cli::Args::parse();
|
|
|
|
change_env_layout(&cli)?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn change_env_layout(args: &cli::Args) -> Result<(), Error> {
|
|
let content = std::fs::read_to_string(&args.file).map_err(|_| Error::OpenFile)?;
|
|
|
|
let mut writer = File::create(&args.file)
|
|
.map_err(|_| Error::OpenFile)
|
|
.map(BufWriter::new)?;
|
|
|
|
let mut current_section_name: Option<Vec<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(|r| r.split(',').map(str::trim).map(String::from).collect());
|
|
line.to_string()
|
|
} else if let Some(cur_name) = current_section_name.clone() {
|
|
let trimmed_line = line.trim_start_matches(['#', ' ']);
|
|
if args.section_names.iter().any(|sn| cur_name.contains(sn)) {
|
|
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,
|
|
}
|