Skip to content

Commit

Permalink
Change parsing of long option that has optional argument
Browse files Browse the repository at this point in the history
This changes the parsing of long options that have optional arguments.
Now the `=` is required; that is, `--arg=something` and `--arg something`
are parsed differently.
Fixes #49
  • Loading branch information
tromey committed Aug 28, 2017
1 parent 4e20d21 commit 74a068c
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ impl Options {
} else {
let mut names;
let mut i_arg = None;
let mut was_long = true;
if cur.as_bytes()[1] == b'-' || self.long_only {
let tail = if cur.as_bytes()[1] == b'-' {
&cur[2..curlen]
Expand All @@ -357,6 +358,7 @@ impl Options {
i_arg = Some(tail_eq[1].to_string());
}
} else {
was_long = false;
names = Vec::new();
for (j, ch) in cur.char_indices().skip(1) {
let opt = Short(ch);
Expand Down Expand Up @@ -404,11 +406,17 @@ impl Options {
vals[optid].push(Given);
}
Maybe => {
// Note that here we do not handle `--arg value`.
// This matches GNU getopt behavior; but also
// makes sense, because if this were accepted,
// then users could only write a "Maybe" long
// option at the end of the arguments when
// FloatingFrees is in use.
if !i_arg.is_none() {
vals[optid]
.push(Val((i_arg.clone())
.unwrap()));
} else if name_pos < names.len() || i + 1 == l ||
} else if was_long || name_pos < names.len() || i + 1 == l ||
is_arg(&args[i + 1]) {
vals[optid].push(Given);
} else {
Expand Down Expand Up @@ -1362,6 +1370,30 @@ mod tests {
}
_ => panic!()
}
let short_args = vec!("-t".to_string(), "x".to_string());
match opts.parse(&short_args) {
Ok(ref m) => {
assert_eq!(m.opt_str("t").unwrap(), "x");
assert_eq!(m.opt_str("test").unwrap(), "x");
}
_ => panic!()
}
let long_args = vec!("--test=x".to_string());
match opts.parse(&long_args) {
Ok(ref m) => {
assert_eq!(m.opt_str("t").unwrap(), "x");
assert_eq!(m.opt_str("test").unwrap(), "x");
}
_ => panic!()
}
let long_args = vec!("--test".to_string(), "x".to_string());
match opts.parse(&long_args) {
Ok(ref m) => {
assert_eq!(m.opt_str("t"), None);
assert_eq!(m.opt_str("test"), None);
}
_ => panic!()
}
let no_args: Vec<String> = vec!();
match opts.parse(&no_args) {
Ok(ref m) => {
Expand Down

0 comments on commit 74a068c

Please sign in to comment.