1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use crate::selector::Selector;
use std::collections::BTreeSet;
use crate::modifier::Modifier;
#[derive(Debug)]
pub struct Extractor<'a, 'b, 'c> {
input: &'a str,
selector: Selector<'b>,
modifiers: BTreeSet<Modifier<'c>>,
}
impl<'a, 'b, 'c> Extractor<'a, 'b, 'c> {
pub fn new(input: &'a str) -> Self {
Extractor {
input,
selector: Selector::All,
modifiers: BTreeSet::new(),
}
}
pub fn extract(&self) -> String {
self.collect().join("\n")
}
pub fn collect(&self) -> Vec<&str> {
let mut lines: Vec<&str> = match self.selector {
Selector::All =>
self.input.lines().collect(),
Selector::Terminator(terminator) =>
self.input.lines().take_while(|l| l != &terminator).collect(),
Selector::Prefix(prefix) =>
self.input.lines().take_while(|l| l.starts_with(prefix)).collect(),
Selector::LineCount(count) =>
self.input.lines().take(count).collect()
};
for modifier in &self.modifiers {
match modifier {
Modifier::DiscardFirstLine => {
lines.remove(0);
}
Modifier::DiscardLastLine => {
lines.pop();
}
Modifier::StripPrefix(prefix) => {
lines = lines.iter().map(|l| l.trim_start_matches(prefix)).collect();
}
Modifier::StripWhitespace => {
lines = lines.iter().map(|l| l.trim()).collect();
}
}
}
lines
}
pub fn select_by_terminator(&mut self, terminator: &'b str) -> &mut Self {
self.selector = Selector::Terminator(terminator);
self
}
pub fn select_by_prefix(&mut self, prefix: &'b str) -> &mut Self {
self.selector = Selector::Prefix(prefix);
self
}
pub fn select_by_line_count(&mut self, count: usize) -> &mut Self {
self.selector = Selector::LineCount(count);
self
}
pub fn discard_first_line(&mut self) -> &mut Self {
self.modifiers.insert(Modifier::DiscardFirstLine);
self
}
pub fn discard_last_line(&mut self) -> &mut Self {
self.modifiers.insert(Modifier::DiscardLastLine);
self
}
pub fn strip_prefix(&mut self, prefix: &'c str) -> &mut Self {
self.modifiers.insert(Modifier::StripPrefix(prefix));
self
}
pub fn strip_whitespace(&mut self) -> &mut Self {
self.modifiers.insert(Modifier::StripWhitespace);
self
}
}