add section info struct with computed values

Closes #13
This commit is contained in:
Dmitriy Pleshevskiy 2022-08-02 11:10:03 +03:00
parent 8f786cfd36
commit 146c0697f2
Signed by: pleshevskiy
GPG Key ID: 1B59187B161C0215
2 changed files with 20 additions and 13 deletions

View File

@ -43,3 +43,8 @@ impl Section {
.map_or_else(|| Self::new(s), |(ns, name)| Self::with_namespace(ns, name))
}
}
struct SectionInfo {
enable_variable: bool,
disable_variable: bool,
}

View File

@ -16,7 +16,7 @@
use std::io::{BufWriter, Write};
use super::Section;
use super::{Section, SectionInfo};
#[derive(Debug)]
pub enum Error {
@ -54,25 +54,27 @@ where
.map(|s| Section::parse(s.as_str()))
.collect::<Vec<_>>();
let mut current_sections: Option<Vec<Section>> = None;
let mut current_sections: Option<SectionInfo> = None;
for line in req.content.split_inclusive('\n') {
let new_line = if is_section_end(line) {
current_sections = None;
line.to_string()
} else if let Some(section_info) = line.strip_prefix("### ") {
current_sections = section_info
.split_whitespace()
.next()
.map(|r| r.split(',').map(Section::parse).collect());
current_sections = section_info.split_whitespace().next().map(|r| {
let current_sections = r.split(',').map(Section::parse).collect::<Vec<_>>();
SectionInfo {
enable_variable: should_enable_variable(&choose_sections, &current_sections),
disable_variable: should_disable_variable(&choose_sections, &current_sections),
}
});
line.to_string()
} else if let Some(cur_sections) = current_sections.clone() {
} else if let Some(section_info) = current_sections.as_ref() {
let trimmed_line = line.trim_start_matches(['#', ' ']);
if !is_variables(trimmed_line) {
line.to_string()
} else if should_enable_variable(&choose_sections, &cur_sections) {
let is_var = is_variable(trimmed_line);
if is_var && section_info.enable_variable {
String::from(trimmed_line)
} else if should_disable_variable(&choose_sections, &cur_sections) {
} else if is_var && section_info.disable_variable {
format!("# {}", trimmed_line)
} else {
line.to_string()
@ -89,7 +91,7 @@ where
writer.flush().map_err(|_| Error::WriteData)
}
fn is_variables(trimmed_line: &str) -> bool {
fn is_variable(trimmed_line: &str) -> bool {
trimmed_line
.chars()
.filter(|ch| (*ch != '_' && ch.is_ascii_punctuation()) || ch.is_whitespace())
@ -297,7 +299,7 @@ mod tests {
];
for (input, expected) in test_cases {
assert_eq!(is_variables(input), expected);
assert_eq!(is_variable(input), expected);
}
}
}