| 1 | use crate::cli::Opt; |
| 2 | use clap::CommandFactory; |
| 3 | use clap::{ArgMatches, Error}; |
| 4 | use std::ffi::{OsStr, OsString}; |
| 5 | |
| 6 | const RG: &str = "rg"; |
| 7 | const GIT: &str = "git"; |
| 8 | pub const SUBCOMMANDS: &[&str] = &[RG, GIT]; |
| 9 | |
| 10 | #[derive(PartialEq)] |
| 11 | pub enum SubCmdKind { |
| 12 | Git(Option<String>), // Some(subcommand) if a git subcommand (git show, git log) was found |
| 13 | GitDiff, |
| 14 | Diff, |
| 15 | Rg, |
| 16 | None, |
| 17 | } |
| 18 | |
| 19 | impl std::fmt::Display for SubCmdKind { |
| 20 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 21 | use SubCmdKind::*; |
| 22 | let s = match self { |
| 23 | Git(Some(arg)) => return formatter.write_fmt(format_args!("git {arg}")), |
| 24 | Git(_) => "git", |
| 25 | GitDiff => "git diff", |
| 26 | Diff => "diff", |
| 27 | Rg => "rg", |
| 28 | None => "<none>", |
| 29 | }; |
| 30 | formatter.write_str(s) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl std::fmt::Debug for SubCmdKind { |
| 35 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 36 | let s = match self { |
| 37 | SubCmdKind::Git(Some(arg)) => { |
| 38 | return formatter.write_fmt(format_args!("\"git {}\"", arg.escape_debug())) |
| 39 | } |
| 40 | _ => format!("{self}"), |
| 41 | }; |
| 42 | formatter.write_str("\"")?; |
| 43 | formatter.write_str(&s)?; |
| 44 | formatter.write_str("\"") |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug)] |
| 49 | pub struct SubCommand { |
| 50 | pub kind: SubCmdKind, |
| 51 | pub args: Vec<OsString>, |
| 52 | } |
| 53 | |
| 54 | impl SubCommand { |
| 55 | pub fn new(kind: SubCmdKind, args: Vec<OsString>) -> Self { |
| 56 | Self { kind, args } |
| 57 | } |
| 58 | |
| 59 | pub fn none() -> Self { |
| 60 | Self { |
| 61 | kind: SubCmdKind::None, |
| 62 | args: vec![], |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | pub fn is_none(&self) -> bool { |
| 67 | matches!(self.kind, SubCmdKind::None) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Find the first arg that is a registered external subcommand and return a |
| 72 | /// tuple containing: |
| 73 | /// - The args prior to that point (delta can understand these) |
| 74 | /// - A SubCommand representing the external subcommand and its subsequent args |
| 75 | pub fn extract(args: &[OsString], orig_error: Error) -> (ArgMatches, SubCommand) { |
| 76 | for (subcmd_pos, arg) in args.iter().filter_map(|a| a.to_str()).enumerate() { |
| 77 | if SUBCOMMANDS.contains(&arg) { |
| 78 | match Opt::command().try_get_matches_from(&args[..subcmd_pos]) { |
| 79 | Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayVersion => { |
| 80 | unreachable!("version handled by caller"); |
| 81 | } |
| 82 | Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayHelp => { |
| 83 | unreachable!("help handled by caller"); |
| 84 | } |
| 85 | Ok(matches) => { |
| 86 | let (subcmd_args_index, kind, subcmd) = if arg == RG { |
| 87 | (subcmd_pos + 1, SubCmdKind::Rg, vec![RG, "--json"]) |
| 88 | } else if arg == GIT { |
| 89 | let subcmd_args_index = subcmd_pos + 1; |
| 90 | let git_subcmd = args |
| 91 | .get(subcmd_args_index) |
| 92 | .and_then(|cmd| OsStr::to_str(cmd)) |
| 93 | .and_then(|cmd| { |
| 94 | if cmd.starts_with("-") { |
| 95 | None |
| 96 | } else { |
| 97 | Some(cmd.into()) |
| 98 | } |
| 99 | }); |
| 100 | ( |
| 101 | subcmd_args_index, |
| 102 | SubCmdKind::Git(git_subcmd), |
| 103 | // git does not start the pager and sees that it does not write to a |
| 104 | // terminal, so by default it will not use colors. Override it: |
| 105 | vec![GIT, "-c", "color.ui=always"], |
| 106 | ) |
| 107 | } else { |
| 108 | unreachable!("arg must be in SUBCOMMANDS"); |
| 109 | }; |
| 110 | |
| 111 | let subcmd = subcmd |
| 112 | .into_iter() |
| 113 | .map(OsString::from) |
| 114 | .chain(args[subcmd_args_index..].iter().map(OsString::from)) |
| 115 | .collect(); |
| 116 | |
| 117 | return (matches, SubCommand::new(kind, subcmd)); |
| 118 | } |
| 119 | Err(_) => { |
| 120 | // part before the subcommand failed to parse, report that error |
| 121 | #[cfg(not(test))] |
| 122 | orig_error.exit(); |
| 123 | #[cfg(test)] |
| 124 | panic!("parse error before subcommand "); |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | // no valid subcommand found, exit with the original error |
| 130 | #[cfg(not(test))] |
| 131 | orig_error.exit(); |
| 132 | #[cfg(test)] |
| 133 | { |
| 134 | let _ = orig_error; |
| 135 | panic!("unexpected delta argument"); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | #[cfg(test)] |
| 140 | mod test { |
| 141 | use super::RG; |
| 142 | use crate::ansi::strip_ansi_codes; |
| 143 | use std::ffi::OsString; |
| 144 | use std::io::Cursor; |
| 145 | |
| 146 | #[test] |
| 147 | #[ignore] // reachable with --ignored, useful with --nocapture |
| 148 | fn test_subcmd_kind_formatter() { |
| 149 | use super::SubCmdKind::*; |
| 150 | for s in [ |
| 151 | Git(Some("foo".into())), |
| 152 | Git(Some("c\"'${}".into())), |
| 153 | Git(Option::None), |
| 154 | GitDiff, |
| 155 | Diff, |
| 156 | Rg, |
| 157 | None, |
| 158 | ] { |
| 159 | eprintln!("{0} / {0:?} ", s); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | #[test] |
| 164 | #[should_panic(expected = "unexpected delta argument")] |
| 165 | fn just_delta_argument_error() { |
| 166 | let mut writer = Cursor::new(vec![]); |
| 167 | let runargs = [ |
| 168 | "--Invalid_Delta_Args", |
| 169 | "abcdefg", |
| 170 | "-C1", |
| 171 | "--Bad_diff_Args_ignored", |
| 172 | ] |
| 173 | .iter() |
| 174 | .map(OsString::from) |
| 175 | .collect::<Vec<_>>(); |
| 176 | crate::run_app(runargs, Some(&mut writer)).unwrap(); |
| 177 | } |
| 178 | |
| 179 | #[test] |
| 180 | #[should_panic(expected = "parse error before subcommand")] |
| 181 | fn subcommand_found_but_delta_argument_error() { |
| 182 | let mut writer = Cursor::new(vec![]); |
| 183 | let runargs = [ |
| 184 | "--Invalid_Delta_Args", |
| 185 | "git", |
| 186 | "show", |
| 187 | "-C1", |
| 188 | "--Bad_diff_Args_ignored", |
| 189 | ] |
| 190 | .iter() |
| 191 | .map(OsString::from) |
| 192 | .collect::<Vec<_>>(); |
| 193 | crate::run_app(runargs, Some(&mut writer)).unwrap(); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn subcommand_rg() { |
| 198 | #[cfg(windows)] |
| 199 | // `resolve_binary` only works on windows |
| 200 | if grep_cli::resolve_binary(RG).is_err() { |
| 201 | return; |
| 202 | } |
| 203 | |
| 204 | #[cfg(unix)] |
| 205 | // resolve `rg` binary by walking PATH |
| 206 | if std::env::var_os("PATH") |
| 207 | .filter(|p| { |
| 208 | std::env::split_paths(&p) |
| 209 | .filter(|p| !p.as_os_str().is_empty()) |
| 210 | .filter_map(|p| p.join(RG).metadata().ok()) |
| 211 | .any(|md| !md.is_dir()) |
| 212 | }) |
| 213 | .is_none() |
| 214 | { |
| 215 | return; |
| 216 | } |
| 217 | |
| 218 | let mut writer = Cursor::new(vec![]); |
| 219 | let needle = format!("{}{}", "Y40ii4RihK6", "lHiK4BDsGS").to_string(); |
| 220 | // --minus-style has no effect, just for cmdline parsing |
| 221 | let runargs = [ |
| 222 | "--minus-style", |
| 223 | "normal", |
| 224 | "rg", |
| 225 | &needle, |
| 226 | "src/", |
| 227 | "-N", |
| 228 | "-C", |
| 229 | "2", |
| 230 | "-C0", |
| 231 | ] |
| 232 | .iter() |
| 233 | .map(OsString::from) |
| 234 | .collect::<Vec<_>>(); |
| 235 | let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); |
| 236 | let rg_output = std::str::from_utf8(writer.get_ref()).unwrap(); |
| 237 | let mut lines = rg_output.lines(); |
| 238 | // eprintln!("{}", rg_output); |
| 239 | assert_eq!( |
| 240 | r#"src/utils/process.rs "#, |
| 241 | strip_ansi_codes(lines.next().expect("line 1")) |
| 242 | ); |
| 243 | let line2 = format!(r#" .join("{}x");"#, needle); |
| 244 | assert_eq!(line2, strip_ansi_codes(lines.next().expect("line 2"))); |
| 245 | assert_eq!(exit_code, 0); |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn subcommand_git_cat_file() { |
| 250 | let mut writer = Cursor::new(vec![]); |
| 251 | |
| 252 | // only 39 of the 40 long git hash, rev-parse doesn't look up full hashes |
| 253 | let runargs = "git rev-parse 5a4361fa037090adf729ab3f161832d969abc57" |
| 254 | .split(' ') |
| 255 | .map(OsString::from) |
| 256 | .collect::<Vec<_>>(); |
| 257 | let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); |
| 258 | assert!(exit_code == 0 || exit_code == 128); |
| 259 | |
| 260 | // ref not found, probably a shallow git clone |
| 261 | if exit_code == 128 { |
| 262 | eprintln!(" Commit for test not found (shallow git clone?), skipping."); |
| 263 | return; |
| 264 | } |
| 265 | |
| 266 | assert_eq!( |
| 267 | "5a4361fa037090adf729ab3f161832d969abc576\n", |
| 268 | std::str::from_utf8(writer.get_ref()).unwrap() |
| 269 | ); |
| 270 | |
| 271 | let mut writer = Cursor::new(vec![]); |
| 272 | |
| 273 | let runargs = "git cat-file -p 5a4361fa037090adf729ab3f161832d969abc576:src/main.rs" |
| 274 | .split(' ') |
| 275 | .map(OsString::from) |
| 276 | .collect::<Vec<_>>(); |
| 277 | let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); |
| 278 | let hello_world = std::str::from_utf8(writer.get_ref()).unwrap(); |
| 279 | assert_eq!( |
| 280 | hello_world, |
| 281 | r#"fn main() { |
| 282 | println!("Hello, world!"); |
| 283 | } |
| 284 | "# |
| 285 | ); |
| 286 | assert_eq!(exit_code, 0); |
| 287 | } |
| 288 | } |