Skip to content

Commit 6b5ef4a

Browse files
authored
fix: remade Cmd#sub_cmd not to retrieve a base name of a path-like sub command (#44)
1 parent 8c2dbb8 commit 6b5ef4a

File tree

2 files changed

+43
-5
lines changed

2 files changed

+43
-5
lines changed

src/lib.rs

+19-5
Original file line numberDiff line numberDiff line change
@@ -501,11 +501,25 @@ impl<'b, 'a> Cmd<'a> {
501501
}
502502

503503
fn sub_cmd(&'a self, from_index: usize) -> Cmd<'b> {
504-
Cmd::with_strings(
505-
self._leaked_strs[from_index..(self._num_of_args)]
506-
.into_iter()
507-
.map(|s| s.to_string()),
508-
)
504+
let arg_iter = self._leaked_strs[from_index..(self._num_of_args)].into_iter();
505+
let (size, _) = arg_iter.size_hint();
506+
let mut _leaked_strs = Vec::with_capacity(size);
507+
508+
for arg in arg_iter {
509+
let str: &'b str = arg.to_string().leak();
510+
_leaked_strs.push(str);
511+
}
512+
513+
let _num_of_args = _leaked_strs.len();
514+
515+
Cmd {
516+
name: &_leaked_strs[0],
517+
args: Vec::new(),
518+
opts: HashMap::new(),
519+
cfgs: Vec::new(),
520+
_leaked_strs,
521+
_num_of_args,
522+
}
509523
}
510524

511525
/// Returns the command name.

src/parse/parse.rs

+24
Original file line numberDiff line numberDiff line change
@@ -799,4 +799,28 @@ mod tests_of_parse_until_sub_cmd {
799799
assert_eq!(cmd.has_opt("f#o"), false);
800800
assert_eq!(cmd.opt_arg("f#o"), None);
801801
}
802+
803+
#[test]
804+
fn test_if_sub_command_is_like_path() { // for the fix of issue #39
805+
let ui_args = vec![
806+
"/path/to/app".to_string(),
807+
"--foo-bar".to_string(),
808+
"path/to/bar".to_string(),
809+
"--baz".to_string(),
810+
"qux".to_string()
811+
];
812+
let mut cmd = Cmd::with_strings(ui_args);
813+
814+
if let Some(mut sub_cmd) = cmd.parse_until_sub_cmd().unwrap() {
815+
sub_cmd.parse().unwrap();
816+
817+
assert_eq!(cmd.name(), "app");
818+
assert_eq!(cmd.args(), &[] as &[&str]);
819+
assert_eq!(cmd.has_opt("foo-bar"), true);
820+
821+
assert_eq!(sub_cmd.name(), "path/to/bar");
822+
assert_eq!(sub_cmd.args(), &["qux"]);
823+
assert_eq!(sub_cmd.has_opt("baz"), true);
824+
}
825+
}
802826
}

0 commit comments

Comments
 (0)