add support of multi-name in section

Closes #3
This commit is contained in:
Dmitriy Pleshevskiy 2022-07-29 19:00:09 +03:00
parent dd8f120152
commit e94a9ca351
Signed by: pleshevskiy
GPG key ID: 1B59187B161C0215

View file

@ -17,7 +17,6 @@
mod cli; mod cli;
use std::path::Path;
use std::{ use std::{
fs::File, fs::File,
io::{BufWriter, Write}, io::{BufWriter, Write},
@ -28,30 +27,33 @@ use clap::Parser;
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let cli = cli::Args::parse(); let cli = cli::Args::parse();
change_env_layout(&cli.file, &cli.section_names)?; change_env_layout(&cli)?;
Ok(()) Ok(())
} }
fn change_env_layout(file: &Path, section_names: &[String]) -> Result<(), Error> { fn change_env_layout(args: &cli::Args) -> Result<(), Error> {
let content = std::fs::read_to_string(file).map_err(|_| Error::OpenFile)?; let content = std::fs::read_to_string(&args.file).map_err(|_| Error::OpenFile)?;
let mut writer = File::create(file) let mut writer = File::create(&args.file)
.map_err(|_| Error::OpenFile) .map_err(|_| Error::OpenFile)
.map(BufWriter::new)?; .map(BufWriter::new)?;
let mut current_section_name: Option<String> = None; let mut current_section_name: Option<Vec<String>> = None;
for line in content.split_inclusive('\n') { for line in content.split_inclusive('\n') {
let new_line = if is_section_end(line) { let new_line = if is_section_end(line) {
current_section_name = None; current_section_name = None;
line.to_string() line.to_string()
} else if let Some(section_info) = line.strip_prefix("### ") { } else if let Some(section_info) = line.strip_prefix("### ") {
current_section_name = section_info.split_whitespace().next().map(String::from); current_section_name = section_info
.split_whitespace()
.next()
.map(|r| r.split(',').map(str::trim).map(String::from).collect());
line.to_string() line.to_string()
} else if let Some(cur_name) = current_section_name.clone() { } else if let Some(cur_name) = current_section_name.clone() {
let trimmed_line = line.trim_start_matches(['#', ' ']); let trimmed_line = line.trim_start_matches(['#', ' ']);
if section_names.contains(&cur_name) { if args.section_names.iter().any(|sn| cur_name.contains(sn)) {
String::from(trimmed_line) String::from(trimmed_line)
} else { } else {
format!("# {}", trimmed_line) format!("# {}", trimmed_line)