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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! Turn a terminal `grep`/`rg` command into a croft Search.
//!
//! croft's Search sidebar already does find-in-files with multi-file
//! replace-all-on-disk. What it lacked was a way to *seed* it from a search
//! the user just ran in a terminal pane. `parse_search_command` reads the last
//! command's typed line (`rg -w "foo bar" src`, `grep -rn TODO`, `git grep -i
//! x`) and extracts the pattern plus the flags that map onto Search's toggles,
//! so the app can populate and run the Search panel — giving `:cdo`-style
//! "replace across every match" for free.
//
// ponytail: a heuristic arg parser, not a full clap model of every grep/rg
// flag. It covers the common invocations (pattern, `-i`/`-w`/`-F`/`-E`, `-e`,
// `-g`, value flags like `-C 3`); exotic combinations may misparse, but the
// seeded query is shown in the panel for the user to correct, never applied
// blindly. Upgrade to per-tool flag tables if that proves too coarse.
/// A terminal search command reduced to what the Search panel needs. The three
/// booleans map 1:1 onto `search::SearchOpts`; `include` onto the panel's
/// files-to-include glob.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchCommand {
pub pattern: String,
pub case_sensitive: bool,
pub whole_word: bool,
pub use_regex: bool,
pub include: Option<String>,
pub exclude: Option<String>,
}
/// Consume `idx`'s token as a flag value (or take the inline `--flag=value`
/// form). Returns the value and advances `idx` past a consumed token.
fn take_value(inline: Option<String>, tokens: &[String], idx: &mut usize) -> Option<String> {
if inline.is_some() {
return inline;
}
let v = tokens.get(*idx).map(|s| s.to_string());
if v.is_some() {
*idx += 1;
}
v
}
/// Parse a terminal command line into a [`SearchCommand`], or `None` if it is
/// not a recognised search (`rg`/`ripgrep`/`grep`/`egrep`/`fgrep`/`git grep`/
/// `ag`/`ack`) or carries no pattern.
pub fn parse_search_command(cmdline: &str) -> Option<SearchCommand> {
let tokens = shlex::split(cmdline)?;
if tokens.is_empty() {
return None;
}
let mut idx = 0;
// Program name, path stripped (`/usr/bin/rg` -> `rg`). Sets the regex/case
// defaults; flags below refine them.
let prog_full = tokens[idx].as_str();
let prog = prog_full.rsplit('/').next().unwrap_or(prog_full);
idx += 1;
// rg/ag/ack/egrep default to regex; plain grep's BRE is not Rust-regex, so
// treat its pattern as literal (correct for the common "grep a string"),
// upgraded by -E/-P. fgrep is always literal.
let mut use_regex = match prog {
"rg" | "ripgrep" | "ag" | "ack" | "egrep" => true,
"grep" | "fgrep" => false,
"git" => {
if tokens.get(idx).map(|s| s.as_str()) != Some("grep") {
return None;
}
idx += 1;
false
}
_ => return None,
};
// `-s` means case-sensitive only in rg/ag; GNU grep and ack use it to
// suppress error messages, and git grep has no such flag at all.
let dash_s_is_case_sensitive = matches!(prog, "rg" | "ripgrep" | "ag");
let mut case_sensitive = false; // rg smart-case & our default: case-insensitive
let mut whole_word = false;
let mut include: Option<String> = None;
let mut exclude: Option<String> = None;
let mut pattern: Option<String> = None;
// Append a glob to one of the panel's comma-separated filter lists.
fn push_glob(list: &mut Option<String>, glob: String) {
match list {
Some(s) => {
s.push(',');
s.push_str(&glob);
}
None => *list = Some(glob),
}
}
// rg spells exclusion as a `!`-negated glob; the panel spells it as the
// separate files-to-exclude list, which has no negation syntax.
fn route_glob(inc: &mut Option<String>, exc: &mut Option<String>, glob: String) {
match glob.strip_prefix('!') {
Some(neg) => push_glob(exc, neg.to_string()),
None => push_glob(inc, glob),
}
}
// A standalone `--` ends option parsing: everything after it is
// positional, so a dash-leading pattern (`rg -- -TODO`) stays a pattern.
let mut flags_done = false;
while idx < tokens.len() {
let tok = tokens[idx].clone();
idx += 1;
if flags_done {
if pattern.is_none() {
pattern = Some(tok);
}
continue;
}
if tok == "--" {
flags_done = true;
} else if let Some(long) = tok.strip_prefix("--") {
let (name, inline_val) = match long.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (long, None),
};
match name {
"ignore-case" | "smart-case" => case_sensitive = false,
"case-sensitive" => case_sensitive = true,
"word-regexp" => whole_word = true,
"fixed-strings" => use_regex = false,
"extended-regexp" | "perl-regexp" => use_regex = true,
"regexp" => {
let v = take_value(inline_val, &tokens, &mut idx);
if pattern.is_none() {
pattern = v;
}
}
"glob" | "iglob" => {
if let Some(v) = take_value(inline_val, &tokens, &mut idx) {
route_glob(&mut include, &mut exclude, v);
}
}
"include" => {
if let Some(v) = take_value(inline_val, &tokens, &mut idx) {
push_glob(&mut include, v);
}
}
// grep's exclusion flags: getopt_long takes the glob inline
// (`--exclude=GLOB`) or spaced (`--exclude GLOB`).
"exclude" | "exclude-dir" => {
if let Some(v) = take_value(inline_val, &tokens, &mut idx) {
push_glob(&mut exclude, v);
}
}
// Long flags that take a value we don't use; drop the value so
// it isn't mistaken for the pattern.
"file" | "max-count" | "type" | "type-not" | "context" | "after-context"
| "before-context" | "max-depth" | "threads" | "replace"
if inline_val.is_none() =>
{
let _ = take_value(None, &tokens, &mut idx);
}
_ => {} // boolean long flag we don't care about
}
} else if tok.starts_with('-') && tok.len() > 1 {
// Possibly-bundled short flags (`-rniw`, `-C3`, `-e pat`).
let chars: Vec<char> = tok[1..].chars().collect();
let mut ci = 0;
while ci < chars.len() {
match chars[ci] {
'i' | 'S' => case_sensitive = false,
's' if dash_s_is_case_sensitive => case_sensitive = true,
'w' => whole_word = true,
'F' => use_regex = false,
'E' | 'P' => use_regex = true,
'e' | 'g' => {
let rest: String = chars[ci + 1..].iter().collect();
let v = if rest.is_empty() {
take_value(None, &tokens, &mut idx)
} else {
Some(rest)
};
if chars[ci] == 'e' {
if pattern.is_none() {
pattern = v;
}
} else if let Some(v) = v {
route_glob(&mut include, &mut exclude, v);
}
break; // consumed the rest of this token
}
// Short flags that take a value we don't use.
'f' | 'm' | 'A' | 'B' | 'C' | 't' | 'T' | 'd' => {
if chars[ci + 1..].is_empty() {
let _ = take_value(None, &tokens, &mut idx);
}
break;
}
_ => {} // boolean short flag (r, n, l, H, o, c, v, ...)
}
ci += 1;
}
} else if pattern.is_none() {
// First positional token is the pattern; later positionals are
// paths/files we ignore.
pattern = Some(tok);
}
}
let pattern = pattern?;
if pattern.is_empty() {
return None;
}
Some(SearchCommand {
pattern,
case_sensitive,
whole_word,
use_regex,
include,
exclude,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(s: &str) -> Option<SearchCommand> {
parse_search_command(s)
}
#[test]
fn plain_rg_is_a_regex_search() {
let c = parse("rg foo").unwrap();
assert_eq!(c.pattern, "foo");
assert!(c.use_regex);
assert!(!c.case_sensitive);
assert!(!c.whole_word);
assert_eq!(c.include, None);
}
#[test]
fn short_flags_bundle_and_set_toggles() {
let c = parse("rg -iw Bar").unwrap();
assert_eq!(c.pattern, "Bar");
assert!(c.whole_word);
assert!(!c.case_sensitive);
}
#[test]
fn fixed_strings_disables_regex_and_keeps_quoted_pattern() {
let c = parse(r#"rg -F "a.b()""#).unwrap();
assert_eq!(c.pattern, "a.b()");
assert!(!c.use_regex);
}
#[test]
fn plain_grep_pattern_is_literal_but_dash_e_upgrades() {
assert!(!parse("grep -rn hello src/").unwrap().use_regex);
assert!(parse("grep -E 'a|b' .").unwrap().use_regex);
}
#[test]
fn grep_pattern_comes_before_the_path() {
let c = parse("grep -rn hello src/").unwrap();
assert_eq!(c.pattern, "hello");
}
#[test]
fn value_flag_is_not_mistaken_for_pattern() {
// -C 3 (context) must eat the 3, leaving `needle` as the pattern.
assert_eq!(parse("rg -C 3 needle").unwrap().pattern, "needle");
assert_eq!(parse("rg -C3 needle").unwrap().pattern, "needle");
assert_eq!(
parse("grep --max-count 5 needle .").unwrap().pattern,
"needle"
);
}
#[test]
fn dash_e_supplies_the_pattern() {
assert_eq!(parse("grep -rn -e pat").unwrap().pattern, "pat");
assert_eq!(parse("rg --regexp=pat").unwrap().pattern, "pat");
}
#[test]
fn glob_becomes_the_include_filter() {
let c = parse("rg -g '*.rs' TODO").unwrap();
assert_eq!(c.pattern, "TODO");
assert_eq!(c.include.as_deref(), Some("*.rs"));
}
#[test]
fn git_grep_is_recognised() {
let c = parse("git grep -w thing").unwrap();
assert_eq!(c.pattern, "thing");
assert!(c.whole_word);
}
#[test]
fn long_flags_map_to_toggles() {
let c = parse("rg --ignore-case --word-regexp Foo").unwrap();
assert_eq!(c.pattern, "Foo");
assert!(c.whole_word);
assert!(!c.case_sensitive);
}
#[test]
fn non_search_commands_are_rejected() {
assert!(parse("ls -la").is_none());
assert!(parse("echo hi").is_none());
assert!(parse("cargo build").is_none());
assert!(parse("").is_none());
assert!(parse("rg").is_none()); // no pattern
}
#[test]
fn path_prefixed_program_is_recognised() {
assert_eq!(parse("/usr/bin/rg needle").unwrap().pattern, "needle");
}
#[test]
fn rg_dash_s_forces_case_sensitivity() {
// `-s` is rg's explicit case-sensitive flag; dropping it would seed a
// case-insensitive search whose Replace All rewrites identifiers the
// terminal command never matched.
assert!(parse("rg -s Error src/").unwrap().case_sensitive);
assert!(parse("rg -sw Error").unwrap().case_sensitive);
assert!(parse("rg --case-sensitive Error").unwrap().case_sensitive);
// ag spells case-sensitive the same way.
assert!(parse("ag -s Error").unwrap().case_sensitive);
}
#[test]
fn grep_dash_s_is_not_case_sensitivity() {
// In GNU grep (and ack) `-s` suppresses error messages; reading it as
// rg's case-sensitive flag would seed a search that skips
// differently-cased matches the terminal command actually found.
assert!(!parse("grep -s Error .").unwrap().case_sensitive);
assert!(!parse("grep -rs Error .").unwrap().case_sensitive);
assert!(!parse("git grep -s Error").unwrap().case_sensitive);
}
#[test]
fn negated_globs_become_the_exclude_filter() {
// `rg -g '!node_modules'` is rg's exclude idiom. Copied verbatim into
// the include filter it matches nothing (the panel's globs have no
// negation), silently emptying the seeded search.
let c = parse("rg -g '!node_modules' TODO").unwrap();
assert_eq!(c.include, None);
assert_eq!(c.exclude.as_deref(), Some("node_modules"));
}
#[test]
fn multiple_globs_accumulate_into_the_comma_lists() {
let c = parse("rg -g '*.rs' -g '*.md' -g '!target' TODO").unwrap();
assert_eq!(c.include.as_deref(), Some("*.rs,*.md"));
assert_eq!(c.exclude.as_deref(), Some("target"));
}
#[test]
fn grep_exclude_flags_seed_the_exclude_filter() {
let c = parse("grep -rn --exclude=*.min.js --exclude-dir=dist TODO .").unwrap();
assert_eq!(c.pattern, "TODO");
assert_eq!(c.exclude.as_deref(), Some("*.min.js,dist"));
}
#[test]
fn end_of_options_marker_lets_a_dash_leading_pattern_through() {
// `rg -- -TODO src` searches for the literal `-TODO`; without
// honoring `--`, the parser ate `-TODO` as flags and seeded the
// search with `src` — running replace against unintended text.
let c = parse("rg -g '*.rs' -- -TODO src").unwrap();
assert_eq!(c.pattern, "-TODO");
assert_eq!(c.include.as_deref(), Some("*.rs"));
assert_eq!(parse("grep -rn -- --help .").unwrap().pattern, "--help");
}
#[test]
fn spaced_grep_exclusion_values_are_not_the_pattern() {
// getopt_long takes required arguments spaced too: `--exclude GLOB`.
// Not consuming the value made the glob the seeded search pattern.
let c = parse("grep -r --exclude *.min.js needle .").unwrap();
assert_eq!(c.pattern, "needle");
assert_eq!(c.exclude.as_deref(), Some("*.min.js"));
let c = parse("grep -r --exclude-dir dist TODO .").unwrap();
assert_eq!(c.pattern, "TODO");
assert_eq!(c.exclude.as_deref(), Some("dist"));
}
}