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
|
use crate::cli::Opt;
use clap::CommandFactory;
use clap::{ArgMatches, Error};
use std::ffi::{OsStr, OsString};
const RG: &str = "rg";
const GIT: &str = "git";
pub const SUBCOMMANDS: &[&str] = &[RG, GIT];
#[derive(PartialEq)]
pub enum SubCmdKind {
Git(Option<String>), // Some(subcommand) if a git subcommand (git show, git log) was found
GitDiff,
Diff,
Rg,
None,
}
impl std::fmt::Display for SubCmdKind {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use SubCmdKind::*;
let s = match self {
Git(Some(arg)) => return formatter.write_fmt(format_args!("git {arg}")),
Git(_) => "git",
GitDiff => "git diff",
Diff => "diff",
Rg => "rg",
None => "<none>",
};
formatter.write_str(s)
}
}
impl std::fmt::Debug for SubCmdKind {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
SubCmdKind::Git(Some(arg)) => {
return formatter.write_fmt(format_args!("\"git {}\"", arg.escape_debug()))
}
_ => format!("{self}"),
};
formatter.write_str("\"")?;
formatter.write_str(&s)?;
formatter.write_str("\"")
}
}
#[derive(Debug)]
pub struct SubCommand {
pub kind: SubCmdKind,
pub args: Vec<OsString>,
}
impl SubCommand {
pub fn new(kind: SubCmdKind, args: Vec<OsString>) -> Self {
Self { kind, args }
}
pub fn none() -> Self {
Self {
kind: SubCmdKind::None,
args: vec![],
}
}
pub fn is_none(&self) -> bool {
matches!(self.kind, SubCmdKind::None)
}
}
/// Find the first arg that is a registered external subcommand and return a
/// tuple containing:
/// - The args prior to that point (delta can understand these)
/// - A SubCommand representing the external subcommand and its subsequent args
pub fn extract(args: &[OsString], orig_error: Error) -> (ArgMatches, SubCommand) {
for (subcmd_pos, arg) in args.iter().filter_map(|a| a.to_str()).enumerate() {
if SUBCOMMANDS.contains(&arg) {
match Opt::command().try_get_matches_from(&args[..subcmd_pos]) {
Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayVersion => {
unreachable!("version handled by caller");
}
Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayHelp => {
unreachable!("help handled by caller");
}
Ok(matches) => {
let (subcmd_args_index, kind, subcmd) = if arg == RG {
(subcmd_pos + 1, SubCmdKind::Rg, vec![RG, "--json"])
} else if arg == GIT {
let subcmd_args_index = subcmd_pos + 1;
let git_subcmd = args
.get(subcmd_args_index)
.and_then(|cmd| OsStr::to_str(cmd))
.and_then(|cmd| {
if cmd.starts_with("-") {
None
} else {
Some(cmd.into())
}
});
(
subcmd_args_index,
SubCmdKind::Git(git_subcmd),
// git does not start the pager and sees that it does not write to a
// terminal, so by default it will not use colors. Override it:
vec![GIT, "-c", "color.ui=always"],
)
} else {
unreachable!("arg must be in SUBCOMMANDS");
};
let subcmd = subcmd
.into_iter()
.map(OsString::from)
.chain(args[subcmd_args_index..].iter().map(OsString::from))
.collect();
return (matches, SubCommand::new(kind, subcmd));
}
Err(_) => {
// part before the subcommand failed to parse, report that error
#[cfg(not(test))]
orig_error.exit();
#[cfg(test)]
panic!("parse error before subcommand ");
}
}
}
}
// no valid subcommand found, exit with the original error
#[cfg(not(test))]
orig_error.exit();
#[cfg(test)]
{
let _ = orig_error;
panic!("unexpected delta argument");
}
}
#[cfg(test)]
mod test {
use super::RG;
use crate::ansi::strip_ansi_codes;
use std::ffi::OsString;
use std::io::Cursor;
#[test]
#[ignore] // reachable with --ignored, useful with --nocapture
fn test_subcmd_kind_formatter() {
use super::SubCmdKind::*;
for s in [
Git(Some("foo".into())),
Git(Some("c\"'${}".into())),
Git(Option::None),
GitDiff,
Diff,
Rg,
None,
] {
eprintln!("{0} / {0:?} ", s);
}
}
#[test]
#[should_panic(expected = "unexpected delta argument")]
fn just_delta_argument_error() {
let mut writer = Cursor::new(vec![]);
let runargs = [
"--Invalid_Delta_Args",
"abcdefg",
"-C1",
"--Bad_diff_Args_ignored",
]
.iter()
.map(OsString::from)
.collect::<Vec<_>>();
crate::run_app(runargs, Some(&mut writer)).unwrap();
}
#[test]
#[should_panic(expected = "parse error before subcommand")]
fn subcommand_found_but_delta_argument_error() {
let mut writer = Cursor::new(vec![]);
let runargs = [
"--Invalid_Delta_Args",
"git",
"show",
"-C1",
"--Bad_diff_Args_ignored",
]
.iter()
.map(OsString::from)
.collect::<Vec<_>>();
crate::run_app(runargs, Some(&mut writer)).unwrap();
}
#[test]
fn subcommand_rg() {
#[cfg(windows)]
// `resolve_binary` only works on windows
if grep_cli::resolve_binary(RG).is_err() {
return;
}
#[cfg(unix)]
// resolve `rg` binary by walking PATH
if std::env::var_os("PATH")
.filter(|p| {
std::env::split_paths(&p)
.filter(|p| !p.as_os_str().is_empty())
.filter_map(|p| p.join(RG).metadata().ok())
.any(|md| !md.is_dir())
})
.is_none()
{
return;
}
let mut writer = Cursor::new(vec![]);
let needle = format!("{}{}", "Y40ii4RihK6", "lHiK4BDsGS").to_string();
// --minus-style has no effect, just for cmdline parsing
let runargs = [
"--minus-style",
"normal",
"rg",
&needle,
"src/",
"-N",
"-C",
"2",
"-C0",
]
.iter()
.map(OsString::from)
.collect::<Vec<_>>();
let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap();
let rg_output = std::str::from_utf8(writer.get_ref()).unwrap();
let mut lines = rg_output.lines();
// eprintln!("{}", rg_output);
assert_eq!(
r#"src/utils/process.rs "#,
strip_ansi_codes(lines.next().expect("line 1"))
);
let line2 = format!(r#" .join("{}x");"#, needle);
assert_eq!(line2, strip_ansi_codes(lines.next().expect("line 2")));
assert_eq!(exit_code, 0);
}
#[test]
fn subcommand_git_cat_file() {
let mut writer = Cursor::new(vec![]);
// only 39 of the 40 long git hash, rev-parse doesn't look up full hashes
let runargs = "git rev-parse 5a4361fa037090adf729ab3f161832d969abc57"
.split(' ')
.map(OsString::from)
.collect::<Vec<_>>();
let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap();
assert!(exit_code == 0 || exit_code == 128);
// ref not found, probably a shallow git clone
if exit_code == 128 {
eprintln!(" Commit for test not found (shallow git clone?), skipping.");
return;
}
assert_eq!(
"5a4361fa037090adf729ab3f161832d969abc576\n",
std::str::from_utf8(writer.get_ref()).unwrap()
);
let mut writer = Cursor::new(vec![]);
let runargs = "git cat-file -p 5a4361fa037090adf729ab3f161832d969abc576:src/main.rs"
.split(' ')
.map(OsString::from)
.collect::<Vec<_>>();
let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap();
let hello_world = std::str::from_utf8(writer.get_ref()).unwrap();
assert_eq!(
hello_world,
r#"fn main() {
println!("Hello, world!");
}
"#
);
assert_eq!(exit_code, 0);
}
}
|