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
use std::{borrow::Cow, io::IsTerminal};
use crate::{Arg, Cmd, Error, Flag, Opt, help::HelpBuilder};
#[expect(unused_imports)]
use crate::{ArgSpec, OptSpec};
/// Raw arguments that will be converted into [`Arg`], [`Opt`], [`Flag`] and [`Cmd`] instances.
#[derive(Debug)]
pub struct RawArgs {
metadata: Metadata,
raw_args: Vec<RawArg>,
log: Vec<Taken>,
}
impl RawArgs {
/// Makes an [`RawArgs`] instance with the given raw arguments.
pub fn new<I>(args: I) -> Self
where
I: Iterator<Item = String>,
{
let raw_args = args
.enumerate()
.map(|(i, value)| RawArg {
value: (i != 0).then_some(value),
})
.collect();
Self {
metadata: Metadata::default(),
raw_args,
log: Vec::new(),
}
}
/// Returns the metadata.
pub fn metadata(&self) -> Metadata {
self.metadata
}
/// Returns a mutable reference of the metadata.
pub fn metadata_mut(&mut self) -> &mut Metadata {
&mut self.metadata
}
/// Returns an iterator that iterates over unconsumed (not taken) raw arguments and their indices.
pub fn remaining_args(&self) -> impl '_ + Iterator<Item = (usize, &str)> {
self.raw_args
.iter()
.enumerate()
.filter_map(|(i, a)| a.value.as_ref().map(|v| (i, v.as_str())))
}
/// Completes the parsing process and checks for any errors.
///
/// If successful and [`Metadata::help_mode`] is `true`, this method returns `Ok(Some(help_text))`.
pub fn finish(self) -> Result<Option<String>, Error> {
if self.metadata.help_mode {
let help = HelpBuilder::new(&self, std::io::stdout().is_terminal()).build();
Ok(Some(help))
} else {
Error::check_command_error(&self)?;
Error::check_unexpected_arg(&self)?;
Ok(None)
}
}
pub(crate) fn raw_args_mut(&mut self) -> &mut [RawArg] {
&mut self.raw_args
}
pub(crate) fn log(&self) -> &[Taken] {
&self.log
}
pub(crate) fn with_record_arg<F>(&mut self, f: F) -> Arg
where
F: FnOnce(&mut Self) -> Arg,
{
let arg = f(self);
self.log.push(Taken::Arg(arg.clone()));
arg
}
pub(crate) fn with_record_opt<F>(&mut self, f: F) -> Opt
where
F: FnOnce(&mut Self) -> Opt,
{
let opt = f(self);
self.log.push(Taken::Opt(opt.clone()));
opt
}
pub(crate) fn with_record_flag<F>(&mut self, f: F) -> Flag
where
F: FnOnce(&mut Self) -> Flag,
{
let flag = f(self);
self.log.push(Taken::Flag(flag));
flag
}
pub(crate) fn with_record_cmd<F>(&mut self, f: F) -> Cmd
where
F: FnOnce(&mut Self) -> Cmd,
{
let cmd = f(self);
self.log.push(Taken::Cmd(cmd));
cmd
}
pub(crate) fn next_raw_arg_value(&self) -> Option<&str> {
self.raw_args.iter().find_map(|a| a.value.as_deref())
}
}
#[derive(Debug, Clone)]
pub struct RawArg {
pub value: Option<String>,
}
/// Metadata of [`RawArgs`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Metadata {
/// Application name (e.g., `env!("CARGO_PKG_NAME")`).
pub app_name: &'static str,
/// Application description (e.g., `env!("CARGO_PKG_DESCRIPTION")`).
pub app_description: &'static str,
/// Flag name for help (default: `Some("help")`).
pub help_flag_name: Option<&'static str>,
/// When enabled, the following help mode behaviors apply:
///
/// - [`RawArgs::finish()`] will return `Ok(Some(help_text))` if successful
/// - Only default and example values will be used when calling [`ArgSpec::take()`] or [`OptSpec::take()`]
pub help_mode: bool,
/// If `true`, a full help text will be displayed.
pub full_help: bool,
/// Predicate function to determine if a string contains only valid flag characters.
///
/// This function is used when parsing short flags to distinguish between:
/// - Multiple flags (e.g., `-abc` where each character is a flag)
/// - Options with concatenated values (e.g., `-khello` where 'k' is an option and "hello" is its value)
///
/// The default implementation accepts only ASCII alphabetic characters, which prevents
/// ambiguity in parsing. For example, with `-khello world`, the presence of space and
/// non-alphabetic characters indicates this is an option with a concatenated value rather
/// than multiple flags.
///
/// # Example: Only accept flags actually defined by the app
///
/// ```rust
/// use noargs::{raw_args, flag};
///
/// let mut args = raw_args();
///
/// // Define the valid short flags for your app
/// const VALID_FLAGS: &[char] = &['h', 'v', 'q', 'd'];
///
/// // Only allow characters that correspond to actual flags in your app
/// args.metadata_mut().is_valid_flag_chars = |chars| {
/// chars.chars().all(|c| VALID_FLAGS.contains(&c))
/// };
///
/// // Now only -h, -v, -q, -d and their combinations (like -hv, -vd) are valid
/// // Anything else like -khello be treated as an option with concatenated value
/// let help_flag = flag("help").short('h').take(&mut args);
/// let verbose_flag = flag("verbose").short('v').take(&mut args);
/// let quiet_flag = flag("quiet").short('q').take(&mut args);
/// let debug_flag = flag("debug").short('d').take(&mut args);
/// ```
pub is_valid_flag_chars: fn(&str) -> bool,
}
impl Default for Metadata {
fn default() -> Self {
Self {
app_name: "<APP_NAME>",
app_description: "",
help_flag_name: Some("help"),
help_mode: false,
full_help: false,
is_valid_flag_chars: |chars| chars.chars().all(|c| c.is_ascii_alphabetic()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Taken {
Arg(Arg),
Opt(Opt),
Flag(Flag),
Cmd(Cmd),
}
impl Taken {
pub fn name(&self) -> &'static str {
match self {
Taken::Arg(arg) => arg.spec().name,
Taken::Opt(opt) => opt.spec().name,
Taken::Flag(flag) => flag.spec().name,
Taken::Cmd(cmd) => cmd.spec().name,
}
}
pub fn example(&self) -> Option<Cow<'static, str>> {
match self {
Taken::Arg(arg) => arg.spec().example.map(Self::quote_if_need),
Taken::Opt(opt) => opt
.spec()
.example
.map(|v| Cow::Owned(format!("--{} {}", opt.spec().name, Self::quote_if_need(v)))),
Taken::Cmd(cmd) if cmd.is_present() => Some(Cow::Borrowed(cmd.spec().name)),
_ => None,
}
}
fn quote_if_need(s: &'static str) -> Cow<'static, str> {
if s.contains('"') && !s.contains('\'') {
Cow::Owned(format!("'{}'", s))
} else if s.contains([' ', '\'']) {
Cow::Owned(format!("{:?}", s))
} else {
Cow::Borrowed(s)
}
}
}