From 1d8ce1149294749bfaa88dbdc7b3c0dc0492ab64 Mon Sep 17 00:00:00 2001 From: Dan Davison Date: Thu, 11 Nov 2021 18:08:40 -0500 Subject: [PATCH] Parse option keys from parent process command line --- src/utils.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index 56bec6687..0be690909 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,7 +1,10 @@ +use std::collections::HashSet; + use sysinfo::{Pid, ProcessExt, SystemExt}; #[cfg(test)] const SKIP_ARGS: usize = 1; + #[cfg(not(test))] const SKIP_ARGS: usize = 2; @@ -21,13 +24,36 @@ fn guess_filename_extension_from_args(args: &[String]) -> Option { None } +// Given `command --aa val -bc -d val e f` return +// ({"--aa"}, {"-b", "-c", "-d"}) +pub fn get_command_options(args: &[String]) -> Option<(HashSet, HashSet)> { + let mut longs = HashSet::new(); + let mut shorts = HashSet::new(); + + for s in args.iter() { + if s == "--" { + break; + } else if s.starts_with("--") { + longs.insert(s.to_owned()); + } else if s.starts_with("-") { + shorts.extend(s[1..].chars().map(|c| format!("-{}", c))); + } + } + + Some((longs, shorts)) +} + pub fn parent_filename_extension() -> Option { process_parent_cmd_args(guess_filename_extension_from_args) } -fn process_parent_cmd_args(f: F) -> Option +pub fn parent_command_options() -> Option<(HashSet, HashSet)> { + process_parent_cmd_args(get_command_options) +} + +fn process_parent_cmd_args(f: F) -> Option where - F: Fn(&[String]) -> Option, + F: Fn(&[String]) -> Option, { let mut info = sysinfo::System::new(); @@ -88,4 +114,63 @@ mod tests { }); assert!(parent_arg0.is_some()); } + + #[test] + fn test_get_command_options() { + fn make_string_vec(args: &[&str]) -> Vec { + args.iter().map(|&x| x.to_owned()).collect::>() + } + fn make_hash_sets(arg1: &[&str], arg2: &[&str]) -> (HashSet, HashSet) { + let f = |strs: &[&str]| strs.iter().map(|&s| s.to_owned()).collect(); + (f(arg1), f(arg2)) + } + + let args = make_string_vec(&["grep", "hello.txt"]); + assert_eq!(get_command_options(&args), Some(make_hash_sets(&[], &[]))); + + let args = make_string_vec(&["grep", "--", "--not.an.argument"]); + assert_eq!(get_command_options(&args), Some(make_hash_sets(&[], &[]))); + + let args = make_string_vec(&[ + "grep", + "-ab", + "--function-context", + "-n", + "--show-function", + "-W", + "--", + "hello.txt", + ]); + assert_eq!( + get_command_options(&args), + Some(make_hash_sets( + &["--function-context", "--show-function"], + &["-a", "-b", "-n", "-W"] + )) + ); + + let args = make_string_vec(&[ + "grep", + "val", + "-ab", + "val", + "--function-context", + "val", + "-n", + "val", + "--show-function", + "val", + "-W", + "val", + "--", + "hello.txt", + ]); + assert_eq!( + get_command_options(&args), + Some(make_hash_sets( + &["--function-context", "--show-function"], + &["-a", "-b", "-n", "-W"] + )) + ); + } }