1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
//! # getopt
//!
//! `getopt` provides a minimalistic, (essentially) POSIX-compliant option parser.
pub mod prelude;
mod error;
mod opt;
mod state;
#[cfg(test)]
mod tests;
pub use crate::{
error::{Error, ErrorKind},
opt::Opt,
state::State,
};
use std::result;
/// A specialized `Result` type for use with [`getopt`](fn.getopt.html)
pub type Result<T> = result::Result<T, Error>;
/// Returns the next option character, if any.
///
/// Returns an error if an unexpected option is encountered or if an expected argument is not
/// found.
///
/// Parsing stops at the first non-hyphenated argument; or at the first argument matching "-"; or
/// after the first argument matching "--".
///
/// When no more options are available, `getopt` returns [`Opt(None, None)`](struct.Opt.html).
///
/// # Examples
///
/// ## "-"
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "-", "-a"];
/// # let args: Vec<String> = vec!["program", "-", "-a"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(Opt(None, None), getopt(&args, optstring, &mut state)?);
/// assert_eq!("-", args[state.index]);
/// # Ok(())
/// # }
/// ```
///
/// ## "--"
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "--", "-a"];
/// # let args: Vec<String> = vec!["program", "--", "-a"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(Opt(None, None), getopt(&args, optstring, &mut state)?);
/// assert_eq!("-a", args[state.index]);
/// # Ok(())
/// # }
/// ```
///
/// ## Unexpected option:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "-b"];
/// # let args: Vec<String> = vec!["program", "-b"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "a";
/// let mut state = State::new();
///
/// assert_eq!(
/// "unknown option -- b".to_string(),
/// getopt(&args, optstring, &mut state)
/// .unwrap_err()
/// .to_string()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ## Missing argument:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "-a"];
/// # let args: Vec<String> = vec!["program", "-a"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "a:";
/// let mut state = State::new();
///
/// assert_eq!(
/// "option requires an argument -- a".to_string(),
/// getopt(&args, optstring, &mut state)
/// .unwrap_err()
/// .to_string()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ## A simple example:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "-abc", "foo"];
/// # let args: Vec<String> = vec!["program", "-abc", "foo"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "ab:c";
/// let mut state = State::new();
///
/// assert_eq!(Opt(Some('a'), None), getopt(&args, optstring, &mut state)?);
/// assert_eq!(State { index: 1, point: 2 }, state);
/// assert_eq!(
/// Opt(Some('b'), Some("c".to_string())),
/// getopt(&args, optstring, &mut state)?
/// );
/// assert_eq!(State { index: 2, point: 0 }, state);
/// assert_eq!(Opt(None, None), getopt(&args, optstring, &mut state)?);
/// assert_eq!(State { index: 2, point: 0 }, state);
/// assert_eq!("foo", args[state.index]);
/// # Ok(())
/// # }
/// ```
///
/// ## A more realistic example:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use getopt::prelude::*;
///
/// // args = ["program", "-abc", "-d", "foo", "-e", "bar"];
/// # let mut args: Vec<String> = vec!["program", "-abc", "-d", "foo", "-e", "bar"]
/// # .into_iter()
/// # .map(String::from)
/// # .collect();
/// let optstring = "ab:cd:e";
/// let mut state = State::new();
///
/// let mut a_flag = false;
/// let mut b_flag = String::new();
/// let mut c_flag = false;
/// let mut d_flag = String::new();
/// let mut e_flag = false;
///
/// loop {
/// match getopt(&args, optstring, &mut state)? {
/// Opt(None, _) => break,
/// Opt(Some('a'), None) => a_flag = true,
/// Opt(Some('b'), Some(arg)) => b_flag = arg.clone(),
/// Opt(Some('c'), None) => c_flag = true,
/// Opt(Some('d'), Some(arg)) => d_flag = arg.clone(),
/// Opt(Some('e'), None) => e_flag = true,
/// _ => unreachable!(),
/// }
/// }
///
/// let args = args.split_off(state.index);
///
/// assert_eq!(true, a_flag);
/// assert_eq!("c", b_flag);
/// assert_eq!(false, c_flag);
/// assert_eq!("foo", d_flag);
/// assert_eq!(true, e_flag);
///
/// assert_eq!(1, args.len());
/// assert_eq!("bar", args.first().unwrap());
/// # Ok(())
/// # }
/// ```
pub fn getopt(args: &[String], optstring: &str, state: &mut State) -> Result<Opt> {
let args: Vec<Vec<char>> = explode(args);
let nothing: Result<Opt> = Ok(Opt(None, None));
if state.point == 0 {
/*
* If, when getopt() is called:
* argv[optind] is a null pointer
* *argv[optind] is not the character '-'
* argv[optind] points to the string "-"
* getopt() shall return -1 without changing optind.
*/
if state.index >= args.len()
|| args[state.index].is_empty()
|| args[state.index][0] != '-'
|| args[state.index].len() == 1
{
return nothing;
}
/*
* If:
* argv[optind] points to the string "--"
* getopt() shall return -1 after incrementing optind.
*/
if args[state.index][1] == '-' && args[state.index].len() == 2 {
state.index += 1;
return nothing;
}
state.point += 1;
}
let opt: char = args[state.index][state.point];
state.point += 1;
match get_spec(optstring, opt) {
None => Err(Error::new(ErrorKind::UnknownOption, opt)),
Some(Spec(c, false)) => {
if state.point >= args[state.index].len() {
state.index += 1;
state.point = 0;
}
Ok(Opt(Some(c), None))
}
Some(Spec(c, true)) => {
let arg: String = if state.point >= args[state.index].len() {
state.index += 1;
if state.index >= args.len() {
return Err(Error::new(ErrorKind::MissingArgument, opt));
}
args[state.index].iter().collect()
} else {
args[state.index]
.clone()
.split_off(state.point)
.iter()
.collect()
};
state.index += 1;
state.point = 0;
Ok(Opt(Some(c), Some(arg)))
}
}
}
fn explode(array: &[String]) -> Vec<Vec<char>> {
array.into_iter().map(|e| e.chars().collect()).collect()
}
struct Spec(char, bool);
fn get_spec(optstring: &str, c: char) -> Option<Spec> {
let optstring: Vec<char> = optstring.chars().collect();
for i in 0..optstring.len() {
if optstring[i] == c {
return Some(Spec(c, i + 1 < optstring.len() && optstring[i + 1] == ':'));
}
}
None
}