Repository navigation
Expand file tree
/
Copy pathpatterns.rs
More file actions
230 lines (209 loc) · 7.45 KB
/
Copy pathpatterns.rs
File metadata and controls
230 lines (209 loc) · 7.45 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::path::PathBuf;
use {
anyhow::Context,
lexopt::{Arg, Parser, ValueExt},
};
use crate::args::{Configurable, Usage};
/// A configuration object for reading patterns from the command line.
///
/// It supports two different modes. One mode limits it to reading patterns
/// from optional flags, i.e., `-p/--pattern` and `-f/--pattern-file`. The
/// other mode permits reading from optional flags, but also reads all
/// positional arguments as patterns too. The latter is convenient in cases
/// where patterns are the only input to a command (like `regex-cli debug`).
#[derive(Debug, Default)]
pub struct Config {
patterns: Vec<String>,
fixed_strings: bool,
combine: bool,
mode: Mode,
}
impl Config {
/// Creates a new configuration that will greedily treat every positional
/// argument as a pattern. This also supports all other ways of providing
/// patterns, i.e., the `-p/--pattern` and `-f/--file` flags.
///
/// This is useful for commands that don't accept any other kind of
/// positional arguments.
pub fn positional() -> Config {
Config { mode: Mode::Positional, ..Config::default() }
}
/// Creates a new configuration that will never treat a positional argument
/// as a pattern. Instead, it only reads patterns from the `-p/--pattern`
/// and `-f/--file` flags.
///
/// This is useful for commands that accept other kinds of positional
/// arguments. Forcing the use of a flag helps avoid resolving more
/// complicated ambiguities regarding how to treat each positional
/// argument.
///
/// This is equivalent to `Config::default()`.
pub fn only_flags() -> Config {
Config::default()
}
/// Returns all of the pattern strings from this configuration, escaping
/// and joining them if requested. When joining is requested, then at most
/// one pattern is returned.
///
/// Note that it is legal for this to return zero patterns!
pub fn get(
&self,
syntax: &crate::args::syntax::Config,
) -> anyhow::Result<Vec<String>> {
let mut pats = self.patterns.clone();
if self.fixed_strings {
pats = pats.iter().map(|p| regex_syntax::escape(p)).collect();
}
if self.combine {
syntax.asts(&pats)?;
pats = vec![pats.join("|")];
}
Ok(pats)
}
}
impl Configurable for Config {
fn configure(
&mut self,
p: &mut Parser,
arg: &mut Arg,
) -> anyhow::Result<bool> {
match *arg {
Arg::Short('p') | Arg::Long("pattern") => {
let pat = p.value().context("-p/--pattern needs a value")?;
let pat = pat
.string()
.context("-p/--pattern must be valid UTF-8")?;
self.patterns.push(pat);
}
Arg::Short('F') | Arg::Long("fixed-strings") => {
self.fixed_strings = true;
}
Arg::Short('f') | Arg::Long("pattern-file") => {
let path =
PathBuf::from(p.value().context("-f/--pattern-file")?);
let contents =
std::fs::read_to_string(&path).with_context(|| {
anyhow::anyhow!("failed to read {}", path.display())
})?;
self.patterns.extend(contents.lines().map(|x| x.to_string()));
}
Arg::Long("combine-patterns") => {
self.combine = true;
}
Arg::Value(ref mut v) => {
if !matches!(self.mode, Mode::Positional) {
return Ok(false);
}
let v = std::mem::take(v);
self.patterns
.push(v.string().context("patterns must be valid UTF-8")?);
}
_ => return Ok(false),
}
Ok(true)
}
fn usage(&self) -> &[Usage] {
const USAGES: &'static [Usage] = &[
Usage::new(
"-p, --pattern <pattern>",
"Add a pattern to this command.",
r#"
This adds a new pattern to the command.
All of the patterns provided, whether by this flag, as a positional argument
(if supported) or via the -f/--pattern-file flag are combined into one regex
matcher.
All patterns given must be valid UTF-8.
"#,
),
Usage::new(
"-f, --pattern-file",
"Read patterns from the file given.",
r#"
Reads patterns, one per line, from the file given.
All of the patterns provided, whether by this flag, as a positional argument
(if supported) or via the -p/--pattern flag are combined into one regex
matcher.
All patterns given must be valid UTF-8.
"#,
),
Usage::new(
"-F, --fixed-strings",
"Interpret all patterns literally.",
r#"
When set, all patterns are interpreted as literal strings. So for example,
special regex meta characters like '+' are matched literally instead of being
given special significance.
"#,
),
Usage::new(
"--combine-patterns",
"Combine all patterns into one via an alternation.",
r#"
This flag combines all patterns given in this command into one by joining
them together via a '|'. This is useful in cases where you want to provide
many different things to search for, but explicitly only want one pattern to
be constructed. In terms of debugging the regex engine, this can be used to
inspect the practical differences between multi-pattern regexes and single
pattern regexes, even when they generally match the same thing.
"#,
),
];
USAGES
}
}
/// The parsing behavior of a pattern configuration. That is, either treat
/// positional arguments as patterns or not.
///
/// The default is to only parse patterns from flags.
#[derive(Debug)]
enum Mode {
Positional,
OnlyFlags,
}
impl Default for Mode {
fn default() -> Mode {
Mode::OnlyFlags
}
}
#[cfg(test)]
mod tests {
use super::Config;
#[test]
fn combine_patterns_rejects_individually_invalid_patterns() {
let config = Config {
patterns: vec!["ab(cd".to_string(), "ef)gh".to_string()],
combine: true,
..Config::default()
};
assert!(config.get(&crate::args::syntax::Config::default()).is_err());
}
#[test]
fn combine_patterns_accepts_individually_valid_patterns() {
let config = Config {
patterns: vec!["ab(cd)".to_string(), "ef(gh)".to_string()],
combine: true,
..Config::default()
};
let got = config.get(&crate::args::syntax::Config::default()).unwrap();
assert_eq!(got, vec!["ab(cd)|ef(gh)".to_string()]);
}
#[test]
fn combine_patterns_respects_syntax_configuration() {
let mut syntax = crate::args::syntax::Config::default();
let config = Config {
patterns: vec![r"\141".to_string(), r"\142".to_string()],
combine: true,
..Config::default()
};
assert!(config.get(&syntax).is_err());
let mut parser = lexopt::Parser::from_args(["--octal"]);
crate::args::configure(
&mut parser,
"",
&mut [&mut syntax as &mut dyn crate::args::Configurable],
)
.unwrap();
let got = config.get(&syntax).unwrap();
assert_eq!(got, vec![r"\141|\142".to_string()]);
}
}