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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
use std::marker::PhantomData;
use std::ops::Deref;
use crate::args::Args;
use crate::args::CLOpt;
use crate::opt::Style;
use crate::opt::BOOL_FALSE;
use crate::opt::BOOL_TRUE;
use crate::proc::NOAMatch;
use crate::proc::NOAProcess;
use crate::proc::OptMatch;
use crate::proc::OptProcess;
use crate::set::OptValidator;
use crate::set::Set;
use crate::ARef;
use crate::Error;
use crate::RawVal;
use crate::Str;
/// User set option style used for generate [`Process`](crate::proc::Process).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UserStyle {
Main,
/// NOA argument base on position.
Pos,
/// The first NOA argument.
Cmd,
/// Option set style like `--opt=value`, the value is set after `=`.
EqualWithValue,
/// Option set style like `--opt value`, the value is set in next argument.
Argument,
/// Option set style like `--i42`, the value set in the option string, only support one letter.
EmbeddedValue,
/// Option set style like `--opt42`, the value set in the option string, but suppport more than one letter.
EmbeddedValuePlus,
/// Option set style like `-abc`, thus set both boolean options `a`, `b` and `c`.
CombinedOption,
/// Option set style like `--bool`, only support boolean option.
Boolean,
/// Option set style like `--flag`, but the value will be set to None.
Flag,
}
/// Manage the support option set style[`UserStyle`].
#[derive(Debug, Clone)]
pub struct OptStyleManager {
styles: Vec<UserStyle>,
}
impl Default for OptStyleManager {
fn default() -> Self {
Self {
styles: vec![
UserStyle::EqualWithValue,
UserStyle::Argument,
UserStyle::Boolean,
UserStyle::EmbeddedValue,
],
}
}
}
impl OptStyleManager {
pub fn with(mut self, styles: Vec<UserStyle>) -> Self {
self.styles = styles;
self
}
pub fn set(&mut self, styles: Vec<UserStyle>) -> &mut Self {
self.styles = styles;
self
}
pub fn remove(&mut self, style: UserStyle) -> &mut Self {
if let Some((index, _)) = self.styles.iter().enumerate().find(|v| v.1 == &style) {
self.styles.remove(index);
}
self
}
pub fn insert(&mut self, index: usize, style: UserStyle) -> &mut Self {
self.styles.insert(index, style);
self
}
pub fn push(&mut self, style: UserStyle) -> &mut Self {
if !self.styles.iter().any(|v| v == &style) {
self.styles.push(style);
}
self
}
}
impl Deref for OptStyleManager {
type Target = Vec<UserStyle>;
fn deref(&self) -> &Self::Target {
&self.styles
}
}
pub trait Guess {
type Config;
type Process;
fn guess(
&mut self,
style: &UserStyle,
cfg: Self::Config,
) -> Result<Option<Self::Process>, Error>;
}
pub fn valueof(name: &str, value: &Option<Str>) -> Result<Str, Error> {
let string = value
.as_ref()
.ok_or_else(|| crate::raise_error!("No value of {name}, please check your option"))?;
Ok(string.clone())
}
/// Guess configuration for option.
#[derive(Debug)]
pub struct GuessOptCfg<'a, T: OptValidator> {
pub idx: usize,
pub len: usize,
pub arg: Option<ARef<RawVal>>,
pub clopt: &'a CLOpt,
pub opt_validator: &'a T,
}
impl<'a, T: OptValidator> GuessOptCfg<'a, T> {
pub fn new(
idx: usize,
len: usize,
arg: Option<ARef<RawVal>>,
clopt: &'a CLOpt,
opt_validator: &'a T,
) -> Self {
Self {
idx,
len,
arg,
clopt,
opt_validator,
}
}
pub fn idx(&self) -> usize {
self.idx
}
pub fn total(&self) -> usize {
self.len
}
pub fn arg(&self) -> Option<&ARef<RawVal>> {
self.arg.as_ref()
}
pub fn opt_validator(&self) -> &'a T {
self.opt_validator
}
}
#[derive(Debug)]
pub struct OptGuess<'a, S, T>(PhantomData<&'a (S, T)>);
impl<'a, S, T> Default for OptGuess<'a, S, T> {
fn default() -> Self {
Self::new()
}
}
impl<'a, S, T> OptGuess<'a, S, T> {
pub fn new() -> Self {
Self(PhantomData)
}
fn bool2str(value: bool) -> ARef<RawVal> {
if value {
RawVal::from(BOOL_TRUE).into()
} else {
RawVal::from(BOOL_FALSE).into()
}
}
}
impl<'a, S, T> Guess for OptGuess<'a, S, T>
where
S: Set,
T: OptValidator,
{
type Config = GuessOptCfg<'a, T>;
type Process = OptProcess<S>;
fn guess(
&mut self,
style: &UserStyle,
cfg: Self::Config,
) -> Result<Option<Self::Process>, Error> {
let mut matches = vec![];
let index = cfg.idx();
let count = cfg.total();
let clopt = &cfg.clopt;
let mut any_match = false;
match style {
UserStyle::EqualWithValue => {
if clopt.value.is_some() {
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(clopt.value.clone())
.with_style(Style::Argument)
.with_name(valueof("name", &clopt.name)?),
);
}
}
UserStyle::Argument => {
if clopt.value.is_none() && cfg.arg().is_some() {
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_consume(true)
.with_arg(cfg.arg().cloned())
.with_style(Style::Argument)
.with_name(valueof("name", &clopt.name)?),
);
}
}
UserStyle::EmbeddedValue => {
if clopt.value.is_none() {
if let Some(name) = &clopt.name {
// strip the prefix before generate
let opt_validator = cfg.opt_validator();
let splited = opt_validator.split(name).map_err(Into::into)?;
let prefix_len = splited.0.len();
// make sure we using `chars.count`, not len()
// make sure the name length >= 2
// only check first letter `--v42` ==> `--v 42`
if let Some((idx, _)) = splited.1.char_indices().nth(1) {
let name_value = name.split_at(prefix_len + idx);
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(Some(RawVal::from(name_value.1).into()))
.with_style(Style::Argument)
.with_name(name_value.0.into()),
);
}
}
}
}
UserStyle::EmbeddedValuePlus => {
if clopt.value.is_none() {
if let Some(name) = &clopt.name {
let opt_validator = cfg.opt_validator();
let splited = opt_validator.split(name).map_err(Into::into)?;
let prefix_len = splited.0.len();
let char_indices = splited.1.char_indices().skip(2);
// make sure we using `chars.count`, not len()
// check the name start 3th letter
// for `--opt42` check the option like `--op t42`, `--opt 42`, `--opt4 2`
for (i, _) in char_indices {
let name_value = name.split_at(prefix_len + i);
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(Some(RawVal::from(name_value.1).into()))
.with_style(Style::Argument)
.with_name(name_value.0.into()),
);
any_match = true;
}
}
}
}
UserStyle::CombinedOption => {
if clopt.value.is_none() {
if let Some(name) = &clopt.name {
let opt_validator = cfg.opt_validator();
let splited = opt_validator.split(name).map_err(Into::into)?;
if splited.1.chars().count() > 1 {
for char in splited.1.chars() {
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(Some(OptGuess::<S, T>::bool2str(true)))
.with_style(Style::Combined)
.with_name(format!("{}{}", splited.0, char).into()),
);
}
}
}
}
}
UserStyle::Boolean => {
if clopt.value.is_none() {
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(Some(OptGuess::<S, T>::bool2str(true)))
.with_style(Style::Boolean)
.with_name(valueof("name", &clopt.name)?),
);
}
}
UserStyle::Flag => {
if clopt.value.is_none() {
matches.push(
OptMatch::default()
.with_idx(index)
.with_total(count)
.with_arg(None)
.with_style(Style::Flag)
.with_name(valueof("name", &clopt.name)?),
);
}
}
_ => {
unimplemented!("Unsupport generate Process for OptGuess")
}
}
Ok((!matches.is_empty()).then(|| {
let mut process = Self::Process::new(matches);
process.set_any_match(any_match);
process
}))
}
}
/// Guess configuration for NOA.
pub struct GuessNOACfg {
index: usize,
total: usize,
args: ARef<Args>,
}
impl GuessNOACfg {
pub fn new(args: ARef<Args>, index: usize, total: usize) -> Self {
Self { args, index, total }
}
pub fn idx(&self) -> usize {
self.index
}
pub fn total(&self) -> usize {
self.total
}
}
#[derive(Debug)]
pub struct NOAGuess<'a, S>(PhantomData<&'a S>);
impl<'a, S> Default for NOAGuess<'a, S> {
fn default() -> Self {
Self::new()
}
}
impl<'a, S> NOAGuess<'a, S> {
pub fn new() -> Self {
Self(PhantomData)
}
}
impl<'a, S> Guess for NOAGuess<'a, S>
where
S: Set,
{
type Config = GuessNOACfg;
type Process = NOAProcess<S>;
fn guess(
&mut self,
style: &UserStyle,
cfg: Self::Config,
) -> Result<Option<Self::Process>, Error> {
let mat;
let args = cfg.args.clone();
let pos = cfg.idx();
let count = cfg.total();
let name = args.get(pos).and_then(|v| v.get_str()).map(Str::from);
match style {
UserStyle::Main => {
mat = Some(
NOAMatch::default()
.with_name(name)
.with_args(args)
.with_idx(pos)
.with_total(count)
.with_style(Style::Main)
.reset_arg(),
);
}
UserStyle::Pos => {
mat = Some(
NOAMatch::default()
.with_name(name)
.with_args(args)
.with_idx(pos)
.with_total(count)
.with_style(Style::Pos)
.reset_arg(),
);
}
UserStyle::Cmd => {
mat = Some(
NOAMatch::default()
.with_name(name)
.with_args(args)
.with_idx(pos)
.with_total(count)
.with_style(Style::Cmd)
.with_arg(Some(RawVal::from(BOOL_TRUE).into())),
);
}
_ => {
unimplemented!("Unsupport generate Process for NOAGuess")
}
}
Ok(mat.map(|v| Self::Process::new(Some(v))))
}
}