From 2be25a330fd2d7d8626a9e4d8bff79dc5bb2c083 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Tue, 8 Nov 2022 00:07:21 +0300 Subject: [PATCH] domain: add optional on_line callback --- src/cli/switch.rs | 1 + src/domain.rs | 2 +- src/domain/switch.rs | 15 +++++++++++---- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/cli/switch.rs b/src/cli/switch.rs index 1f4c514..d346425 100644 --- a/src/cli/switch.rs +++ b/src/cli/switch.rs @@ -51,6 +51,7 @@ pub fn execute(args: &Args) -> Result<(), Error> { content: &content, writer, sections: &args.sections, + on_line: None, }) .map_err(Error::Switch) } diff --git a/src/domain.rs b/src/domain.rs index d35672a..88f0ab6 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -44,7 +44,7 @@ impl Section { } } -struct SectionInfo { +pub(crate) struct SectionInfo { enable_variable: bool, disable_variable: bool, } diff --git a/src/domain/switch.rs b/src/domain/switch.rs index ecf32bf..e499da4 100644 --- a/src/domain/switch.rs +++ b/src/domain/switch.rs @@ -33,6 +33,8 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} +pub type OnLineFn = Box, &String)>; + pub struct Request<'args, W> where W: Write, @@ -40,6 +42,7 @@ where pub content: &'args str, pub writer: W, pub sections: &'args [String], + pub on_line: Option, } pub fn execute(req: Request) -> Result<(), Error> @@ -54,14 +57,14 @@ where .map(|s| Section::parse(s.as_str())) .collect::>(); - let mut current_sections: Option = None; + let mut current_section: Option = None; for line in req.content.split_inclusive('\n') { let new_line = if is_section_end(line) { - current_sections = None; + current_section = None; line.to_string() } else if let Some(section_info) = line.strip_prefix("### ") { - current_sections = section_info.split_whitespace().next().map(|r| { + current_section = 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), @@ -69,7 +72,7 @@ where } }); line.to_string() - } else if let Some(section_info) = current_sections.as_ref() { + } else if let Some(section_info) = current_section.as_ref() { let trimmed_line = line.trim_start_matches(['#', ' ']); let is_var = is_variable(trimmed_line); if is_var && section_info.enable_variable { @@ -86,6 +89,10 @@ where writer .write_all(new_line.as_bytes()) .map_err(|_| Error::WriteData)?; + + if let Some(on_line) = req.on_line.as_ref() { + on_line(current_section.as_ref(), &new_line); + } } writer.flush().map_err(|_| Error::WriteData)