From 146c0697f2c6d453408f0371b29b9620513545df Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Tue, 2 Aug 2022 11:10:03 +0300 Subject: [PATCH] add section info struct with computed values Closes #13 --- src/domain.rs | 5 +++++ src/domain/switch.rs | 28 +++++++++++++++------------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/domain.rs b/src/domain.rs index 8684f1a..a954e88 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -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, +} diff --git a/src/domain/switch.rs b/src/domain/switch.rs index 330cc17..74c5601 100644 --- a/src/domain/switch.rs +++ b/src/domain/switch.rs @@ -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::>(); - let mut current_sections: Option> = None; + let mut current_sections: Option = 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::>(); + SectionInfo { + enable_variable: should_enable_variable(&choose_sections, ¤t_sections), + disable_variable: should_disable_variable(&choose_sections, ¤t_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); } } }