Skip to content

Commit 135ffaf

Browse files
committed
When getopts encounters an option that takes an argument, it should treat the remainder of the current option string as the argument if it is non-empty. Fix rust-lang#2791.
1 parent 86f0dcb commit 135ffaf

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/libstd/getopts.rs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,36 @@ fn getopts(args: ~[str], opts: ~[opt]) -> result unsafe {
220220
}
221221
} else {
222222
let mut j = 1u;
223+
let mut last_valid_opt_id = option::none;
223224
names = ~[];
224225
while j < curlen {
225226
let range = str::char_range_at(cur, j);
226-
vec::push(names, short(range.ch));
227+
let opt = short(range.ch);
228+
229+
/* In a series of potential options (eg. -aheJ), if we see
230+
one which takes an argument, we assume all subsequent
231+
characters make up the argument. This allows options
232+
such as -L/usr/local/lib/foo to be interpreted correctly
233+
*/
234+
alt find_opt(opts, opt) {
235+
some(id) {
236+
last_valid_opt_id = option::some(id);
237+
}
238+
none {
239+
let arg_follows = option::is_some(last_valid_opt_id) &&
240+
alt opts[option::get(last_valid_opt_id)].hasarg {
241+
yes | maybe { true }
242+
no { false }
243+
};
244+
if arg_follows && j + 1 < curlen {
245+
i_arg = option::some(str::slice(cur, j, curlen));
246+
break;
247+
} else {
248+
last_valid_opt_id = option::none;
249+
}
250+
}
251+
}
252+
vec::push(names, opt);
227253
j = range.next;
228254
}
229255
}
@@ -857,6 +883,18 @@ mod tests {
857883
assert opts_str(match, ~["e", "encrypt"]) == "foo";
858884
assert opts_str(match, ~["encrypt", "e"]) == "foo";
859885
}
886+
887+
#[test]
888+
fn test_nospace() {
889+
let args = ~["-Lfoo"];
890+
let opts = ~[optmulti("L")];
891+
let match = alt getopts(args, opts) {
892+
result::ok(m) { m }
893+
result::err(f) { fail; }
894+
};
895+
assert opts_present(match, ~["L"]);
896+
assert opts_str(match, ~["L"]) == "foo";
897+
}
860898
}
861899

862900
// Local Variables:

0 commit comments

Comments
 (0)