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
//! Command line argument parsing with [`serde`].
//!
//! This library allows parsing command line arguments into types implementing [`Deserialize`].
//! Included are all of the typical features you'd find in an command line argument parsing
//! library, including help generation, help customization, version support, and flexible parsing
//! options.
//!
//! Unlike other argument parsing libraries, `serde_args` uses `serde`'s traits to define the
//! command line interface. No builder or derive interface is provided; instead, any object
//! implementing `Deserialize` can be used. This means that you can use `serde`'s own derive macros
//! (that you are likely already familiar with) or implement the `Deserialize` trait by hand to
//! define your command line interface.
//!
//! `serde_args` defines an unambiguous deserialization format through internal [`Deserializer`]s;
//! therefore it should be noted that not every command line interface can be represented using it.
//! Notably, optional positional parameters are not supported at all, nor are default command
//! values. The format defined here requires that all positional arguments (those *without* a `-`
//! or `--` preceeding them) be required arguments, and that all other arguments be preceeded with
//! either a `-` or `--` (including compound types). See the [format specification](specification)
//! for more details.
//!
//! # Parsing Arguments
//!
//! To use `serde_args` for your own command line argument parsing, you must first define a type
//! implementing `serde`'s [`Deserialize`] trait. This can be done using `serde`'s derive macro or
//! by implementing the trait by hand. For example, a simple program could be defined as:
//!
//! ``` rust
//! # mod hidden {
//! use serde::Deserialize;
//! # }
//! # use serde_derive::Deserialize;
//! use std::path::PathBuf;
//!
//! #[derive(Deserialize)]
//! #[serde(expecting = "An example program")]
//! struct Args {
//! path: PathBuf,
//! #[serde(alias = "f")]
//! force: bool,
//! }
//!
//! fn main() {
//! let args: Args = match serde_args::from_env() {
//! Ok(args) => args,
//! Err(error) => {
//! println!("{error}");
//! return;
//! }
//! };
//! // Execute your program with `args`...
//! }
//! ```
//!
//! Command-based interfaces can be defined using `enums`:
//!
//! ``` rust
//! # mod hidden {
//! use serde::Deserialize;
//! # }
//! # use serde_derive::Deserialize;
//! use std::path::PathBuf;
//!
//! #[derive(Deserialize)]
//! #[serde(expecting = "A command-based interface")]
//! #[serde(rename_all = "kebab-case")]
//! enum Command {
//! Add {
//! path: PathBuf,
//! },
//! Commit {
//! #[serde(alias = "m")]
//! message: Option<String>,
//! },
//! Push {
//! #[serde(alias = "f")]
//! force: bool,
//! },
//! }
//!
//! fn main() {
//! let command: Command = match serde_args::from_env() {
//! Ok(command) => command,
//! Err(error) => {
//! println!("{error}");
//! return;
//! }
//! };
//! // Execute your program with `command`...
//! }
//! ```
//!
//! For simple use cases you can also use existing types that
//! already implement `Deserialize`:
//!
//! ``` rust
//! fn main() {
//! let value: String = match serde_args::from_env() {
//! Ok(value) => value,
//! Err(error) => {
//! println!("{error}");
//! return;
//! }
//! };
//! // Execute your program with `value`...
//! }
//! ```
//!
//! Note that the only way to deserialize using this crate is through [`from_env()`] and
//! [`from_env_seed()`]. No public [`Deserializer`] is provided.
//!
//! # Error Formatting
//!
//! On failure, [`from_env()`] will return an [`Error`]. This will occur when the provided type is
//! incompatible with this crate (see [Supported `serde` Attributes](#supported-serde-attributes)
//! for common reasons why types are not compatible), when the user has input command line
//! arguments that cannot be parsed into the provided type, or when the user requests the generated
//! help message (either through the `--help` flag or by providing no arguments). In any case, the
//! returned `Error` implements the [`Display`] trait and is able to be printed and displayed to
//! the user.
//!
//! For example, a program taking a single unsigned integer value as a parameter would print an
//! error that occurred like so:
//!
//! ```rust
//! if let Err(error) = serde_args::from_env::<usize>() {
//! println!("{error}");
//! }
//! ```
//!
//! To print an error that is formatted with ANSI color sequences, use the "alternate" form of
//! printing with the `#` flag:
//!
//! ```rust
//! if let Err(error) = serde_args::from_env::<usize>() {
//! println!("{error:#}");
//! }
//! ```
//!
//! # Customization
//!
//! `serde_args` allows for customizing in the form of messages to be displayed in help output and
//! the displaying of version information. These are most easily customized using the
//! [`#[generate]`](generate) attribute (requires the `macros` feature`). This macro must be
//! combined with `serde`'s `Deserialize` derive macro.
//!
//! ## Custom Help Messages
//!
//! Descriptions for each of your fields or variants can be automatically imported from your struct
//! or enum's doc comment using `#[generate]` with `doc_help` as a parameter:
//!
//! ``` rust
//! # mod hidden {
//! use serde::Deserialize;
//! # }
//! # use serde_derive::Deserialize;
//! use std::path::PathBuf;
//!
//! /// An example program.
//! #[serde_args::generate(doc_help)]
//! #[derive(Deserialize)]
//! struct Args {
//! /// The path to operate on.
//! path: PathBuf,
//! /// Whether the program's behavior should be forced.
//! #[serde(alias = "f")]
//! force: bool,
//! }
//!
//! fn main() {
//! let args: Args = match serde_args::from_env() {
//! Ok(args) => args,
//! Err(error) => {
//! println!("{error}");
//! return;
//! }
//! };
//! // Execute your program with `args`...
//! }
//! ```
//!
//! ## Version Information
//!
//! To automatically make the version of your crate available through a `--version` flag, use
//! `#[generate]` with `version` as a parameter:
//!
//! ```rust
//! # mod hidden {
//! use serde::Deserialize;
//! # }
//! # use serde_derive::Deserialize;
//!
//! #[serde_args::generate(version)]
//! #[derive(Deserialize)]
//! struct Args {
//! foo: String,
//! bar: bool,
//! }
//!
//! fn main() {
//! let args: Args = match serde_args::from_env() {
//! Ok(args) => args,
//! Err(error) => {
//! println!("{error}");
//! return;
//! }
//! };
//! // Execute your program with `args`...
//! }
//! ```
//!
//! ## Customization Without Deriving
//!
//! To provide these customization options without deriving, see
//! [`expecting()` Option Specification](specification/index.html#expecting-option-specification).
//!
//! # Supported `serde` Attributes
//!
//! Nearly all `serde` attributes are supported. Those that are not supported are those that
//! require a self-describing deserializer (the format defined by `serde_args` is **not**
//! self-describing). Specifically, the following attributes will not work:
//!
//! - [`#[serde(flatten)]`](https://serde.rs/field-attrs.html#flatten)
//! - [`#[serde(tag = "type")]`](https://serde.rs/container-attrs.html#tag) - Doesn't work for
//! enums, but it will work for structs.
//! - [`#[serde(tag = "t", content = "c")]`](https://serde.rs/container-attrs.html#tag--content)
//! - [`#[serde(untagged)]`](https://serde.rs/container-attrs.html#untagged) - Not allowed on enums
//! or on variants.
//! - [`#[serde(other)]`](https://serde.rs/variant-attrs.html#other)
//!
//! Aside from the above list, all other attributes are supported. Some attributes are especially
//! useful for defining command line interfaces, including:
//!
//! - [`#[serde(alias)]`](https://serde.rs/field-attrs.html#alias) - Useful for defining multiple
//! names for optional fields or command variants.
//! - [`#[serde(expecting)]`](https://serde.rs/container-attrs.html#expecting) - Can be used to
//! define a description for your program. Whatever is provided here will be output at the top of
//! the generated help message.
//! - Note that many users will want to use [`#[serde_args::generate(doc_help)]`](generate) to
//! automatically populate this message from the container's doc comment instead.
//! - [`#[serde(rename_all)]`](https://serde.rs/container-attrs.html#rename_all) - Useful for
//! renaming all field names or enum variants to kebab-case, which is common for command-line
//! tools.
//!
//! [`Deserializer`]: serde::Deserializer
//! [`Display`]: std::fmt::Display
pub use Error;
pub use generate;
use Deserializer;
use parse;
use ;
use ;
use trace;
/// Deserialize from [`env::args()`] using a seed.
///
/// This function parses the command line arguments using the provided seed. On success a value of
/// type `D::Value` is returned; on failure an [`Error`] is returned instead.
///
/// Note that the type `D` must also implement [`Copy`]. This is because the deserialization
/// process requires visiting a type multiple times. If your seed type does not implement `Copy`,
/// you will not be able to use this function.
///
/// # Example
///
/// This example reads an integer from the command line and adding it to the seed value. The
/// program returns early if an error is encountered.
///
/// ``` rust
/// use serde::de::{
/// Deserialize,
/// DeserializeSeed,
/// Deserializer,
/// };
///
/// #[derive(Clone, Copy)]
/// struct Seed(u32);
///
/// impl<'de> DeserializeSeed<'de> for Seed {
/// type Value = u32;
///
/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
/// where
/// D: Deserializer<'de>,
/// {
/// u32::deserialize(deserializer).map(|value| value + self.0)
/// }
/// }
///
/// fn main() {
/// let value = match serde_args::from_env_seed(Seed(42)) {
/// Ok(value) => value,
/// Err(error) => {
/// println!("{error}");
/// return;
/// }
/// };
/// // Execute your program with `value`...
/// }
/// ```
/// Deserialize from [`env::args()`].
///
/// This functions parses the command line arguments into the provided type. On success a value of
/// type `D` is returned; on failure an [`Error`] is returned instead.
///
/// # Example
///
/// This example reads a string from the command line, returning early if an error is encountered.
///
/// ``` rust
/// fn main() {
/// let value: String = match serde_args::from_env() {
/// Ok(value) => value,
/// Err(error) => {
/// println!("{error}");
/// return;
/// }
/// };
/// // Execute your program with `value`...
/// }
/// ```
///
/// [`env::args()`]: std::env::args()