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
use crate::{
args::{Metadata, RawArgs},
error::Error,
};
/// Specification for [`Arg`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArgSpec {
/// Value name (usually SCREAMING_SNAKE_CASE).
pub name: &'static str,
/// Documentation.
pub doc: &'static str,
/// Default value.
pub default: Option<&'static str>,
/// Example value (if this is set, the argument is considered to be requried when generating the help text).
///
/// This is only used if `RawArgs::metadata().help_mode` is `true`.
pub example: Option<&'static str>,
}
impl ArgSpec {
/// The default specification.
pub const DEFAULT: Self = Self {
name: "<ARGUMENT>",
doc: "",
default: None,
example: None,
};
/// Makes an [`ArgSpec`] instance with a specified name (equivalent to `noargs::arg(name)`).
pub const fn new(name: &'static str) -> Self {
Self {
name,
..Self::DEFAULT
}
}
/// Updates the value of [`ArgSpec::doc`].
pub const fn doc(mut self, doc: &'static str) -> Self {
self.doc = doc;
self
}
/// Updates the value of [`ArgSpec::default`].
pub const fn default(mut self, default: &'static str) -> Self {
self.default = Some(default);
self
}
/// Updates the value of [`ArgSpec::example`].
pub const fn example(mut self, example: &'static str) -> Self {
self.example = Some(example);
self
}
/// Takes the first [`Arg`] instance that satisfies this specification from the raw arguments.
pub fn take(self, args: &mut RawArgs) -> Arg {
let metadata = args.metadata();
args.with_record_arg(|args| {
if args.metadata().help_mode {
return if self.default.is_some() {
Arg::Default {
spec: self,
metadata,
}
} else if self.example.is_some() {
Arg::Example {
spec: self,
metadata,
}
} else {
Arg::None { spec: self }
};
}
for (index, raw_arg) in args.raw_args_mut().iter_mut().enumerate() {
if let Some(value) = raw_arg.value.take() {
return Arg::Positional {
spec: self,
metadata,
index,
value,
};
};
}
if self.default.is_some() {
Arg::Default {
spec: self,
metadata,
}
} else {
Arg::None { spec: self }
}
})
}
}
impl Default for ArgSpec {
fn default() -> Self {
Self::DEFAULT
}
}
/// A positional argument.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Arg {
Positional {
spec: ArgSpec,
metadata: Metadata,
index: usize,
value: String,
},
Default {
spec: ArgSpec,
metadata: Metadata,
},
Example {
spec: ArgSpec,
metadata: Metadata,
},
None {
spec: ArgSpec,
},
}
impl Arg {
/// Returns the specification of this argument.
pub fn spec(&self) -> ArgSpec {
match self {
Arg::Positional { spec, .. }
| Arg::Default { spec, .. }
| Arg::Example { spec, .. }
| Arg::None { spec } => *spec,
}
}
/// Returns `true` if this argument has a value.
pub fn is_present(&self) -> bool {
!matches!(self, Self::None { .. })
}
/// Returns `Some(self)` if this argument is present.
pub fn present(self) -> Option<Self> {
self.is_present().then_some(self)
}
/// Applies additional conversion or validation to the argument.
///
/// This method allows for chaining transformations and validations when an argument is present.
/// It first checks if the argument has a value and then applies the provided function.
///
/// # Examples
///
/// ```
/// let mut args = noargs::RawArgs::new(["example", "42"].iter().map(|a| a.to_string()));
/// let arg = noargs::arg("<NUMBER>").take(&mut args);
///
/// // Parse as number and ensure it's positive
/// let num = arg.then(|arg| -> Result<_, Box<dyn std::error::Error>> {
/// let n: i32 = arg.value().parse()?;
/// if n <= 0 {
/// return Err("number must be positive".into());
/// }
/// Ok(n)
/// })?;
/// # Ok::<(), noargs::Error>(())
/// ```
///
/// # Errors
///
/// - Returns [`Error::MissingArg`] if `self.is_present()` is `false` (argument is missing)
/// - Returns [`Error::InvalidArg`] if `f(self)` returns `Err(_)` (validation or conversion failed)
pub fn then<F, T, E>(self, f: F) -> Result<T, Error>
where
F: FnOnce(Self) -> Result<T, E>,
E: std::fmt::Display,
{
if !self.is_present() {
return Err(Error::MissingArg {
arg: Box::new(self),
});
}
f(self.clone()).map_err(|e| Error::InvalidArg {
arg: Box::new(self),
reason: e.to_string(),
})
}
/// Shorthand for `self.present().map(|arg| arg.then(f)).transpose()`.
pub fn present_and_then<F, T, E>(self, f: F) -> Result<Option<T>, Error>
where
F: FnOnce(Self) -> Result<T, E>,
E: std::fmt::Display,
{
self.present().map(|arg| arg.then(f)).transpose()
}
/// Returns the raw value of this argument, or an empty string if not present.
pub fn value(&self) -> &str {
match self {
Arg::Positional { value, .. } => value.as_str(),
Arg::Default { spec, .. } => spec.default.unwrap_or(""),
Arg::Example { spec, .. } => spec.example.unwrap_or(""),
Arg::None { .. } => "",
}
}
/// Returns the index at which the raw value of this argument was located in [`RawArgs`].
pub fn index(&self) -> Option<usize> {
if let Arg::Positional { index, .. } = self {
Some(*index)
} else {
None
}
}
pub(crate) fn metadata(&self) -> Option<Metadata> {
match self {
Arg::Positional { metadata, .. }
| Arg::Default { metadata, .. }
| Arg::Example { metadata, .. } => Some(*metadata),
Arg::None { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn required_arg() {
let mut args = test_args(&["test", "foo", "bar"]);
let arg = crate::arg("ARG");
assert!(matches!(
arg.take(&mut args),
Arg::Positional { index: 1, .. }
));
assert!(matches!(
arg.take(&mut args),
Arg::Positional { index: 2, .. }
));
assert!(matches!(arg.take(&mut args), Arg::None { .. }));
}
#[test]
fn optional_arg() {
let mut args = test_args(&["test", "foo"]);
let arg = crate::arg("ARG").default("bar");
assert!(matches!(
arg.take(&mut args),
Arg::Positional { index: 1, .. }
));
assert!(matches!(arg.take(&mut args), Arg::Default { .. }));
assert!(matches!(arg.take(&mut args), Arg::Default { .. }));
}
#[test]
fn example_arg() {
let mut args = test_args(&["test", "foo"]);
args.metadata_mut().help_mode = true;
let arg = crate::arg("ARG").example("bar");
assert!(matches!(arg.take(&mut args), Arg::Example { .. }));
assert!(matches!(arg.take(&mut args), Arg::Example { .. }));
}
#[test]
fn parse_arg() {
let mut args = test_args(&["test", "1", "not a number"]);
let arg = crate::arg("ARG");
assert_eq!(
arg.take(&mut args)
.then(|a| a.value().parse::<usize>())
.ok(),
Some(1)
);
assert_eq!(
arg.take(&mut args)
.then(|a| a.value().parse::<usize>())
.ok(),
None
);
assert_eq!(
arg.take(&mut args)
.then(|a| a.value().parse::<usize>())
.ok(),
None
);
}
fn test_args(raw_args: &[&str]) -> RawArgs {
RawArgs::new(raw_args.iter().map(|a| a.to_string()))
}
}