argx 0.3.0

Expressive command-line parsing and configuration for Rust.
Documentation
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Environment snapshots, binding contracts, and scalar decoding.

use std::{
    collections::{BTreeMap, HashMap},
    env,
    ffi::{OsStr, OsString},
    fmt,
    str::FromStr,
};

use serde::{
    Deserializer,
    de::{self, DeserializeOwned, Visitor, value::StrDeserializer},
};

/// Snapshot of one environment-like configuration scope.
///
/// The type is public only because generated downstream code receives it through
/// Argx's hidden derive protocol.
#[derive(Debug, Default)]
pub struct Environment {
    /// Raw operating-system key/value pairs in this scope.
    values: HashMap<OsString, OsString>,
}

impl Environment {
    /// Captures the process environment without mutating it.
    pub(crate) fn process() -> Self {
        Self { values: env::vars_os().collect() }
    }

    /// Builds an environment scope from UTF-8 dotenv assignments.
    pub(crate) fn from_utf8(values: HashMap<String, String>) -> Self {
        Self {
            values: values
                .into_iter()
                .map(|(key, value)| (OsString::from(key), OsString::from(value)))
                .collect(),
        }
    }

    /// Returns the raw value associated with one known environment variable.
    pub(crate) fn raw(&self, name: &str) -> Option<&OsStr> {
        self.values.get(OsStr::new(name)).map(OsString::as_os_str)
    }

    /// Returns one mapped value as UTF-8 while preserving field-aware diagnostics.
    fn utf8<'a>(
        &'a self,
        field: &'static str,
        variable: &str,
    ) -> Result<Option<&'a str>, EnvironmentError> {
        let Some(value) = self.raw(variable) else {
            return Ok(None);
        };
        value
            .to_str()
            .map(Some)
            .ok_or_else(|| EnvironmentError::new(field, variable, EnvironmentValueError::NonUtf8))
    }

    /// Builds a deterministic environment scope from UTF-8 string pairs for tests.
    #[cfg(test)]
    pub(super) fn from_pairs(values: &[(&str, &str)]) -> Self {
        Self::from_utf8(
            values.iter().map(|(key, value)| (String::from(*key), String::from(*value))).collect(),
        )
    }

    /// Overlays another environment-like scope for later interpolation.
    pub(crate) fn overlay(&mut self, higher: Self) {
        self.values.extend(higher.values);
    }
}

/// Environment bindings generated for one configuration contract.
///
/// The type is public only because downstream derive expansions build it through
/// Argx's hidden protocol.
#[derive(Debug, Default)]
pub struct EnvironmentContract {
    /// Field-to-variable bindings in declaration order.
    bindings: Vec<EnvironmentBinding>,
}

/// One resolved environment binding.
#[derive(Debug)]
struct EnvironmentBinding {
    /// Dot-qualified Rust configuration field.
    field: String,
    /// Concrete environment variable name.
    variable: String,
}

impl EnvironmentContract {
    /// Registers one concrete field-to-variable binding.
    #[doc(hidden)]
    pub fn __binding(&mut self, field: &'static str, variable: impl Into<String>) {
        self.bindings
            .push(EnvironmentBinding { field: String::from(field), variable: variable.into() });
    }

    /// Extends this contract with a nested configuration under `parent`.
    #[doc(hidden)]
    pub fn __extend_within(&mut self, mut nested: Self, parent: &'static str) {
        for binding in &mut nested.bindings {
            binding.field.insert(0, '.');
            binding.field.insert_str(0, parent);
        }
        self.bindings.extend(nested.bindings);
    }

    /// Rejects ambiguous environment mappings in a generated contract.
    pub(crate) fn validate(&self) -> Result<(), EnvironmentContractError> {
        let mut seen = BTreeMap::<&str, &str>::new();
        for binding in &self.bindings {
            if let Some(first_field) = seen.insert(&binding.variable, &binding.field) {
                return Err(EnvironmentContractError {
                    variable: binding.variable.clone(),
                    first_field: String::from(first_field),
                    second_field: binding.field.clone(),
                });
            }
        }
        Ok(())
    }
}

/// Invalid generated environment contract.
#[derive(Debug, thiserror::Error)]
#[error(
    "environment variable `{variable}` maps to both configuration fields `{first_field}` and `{second_field}`"
)]
pub(crate) struct EnvironmentContractError {
    /// Environment variable mapped more than once.
    variable: String,
    /// First field mapped to the variable.
    first_field: String,
    /// Second field mapped to the variable.
    second_field: String,
}

impl EnvironmentContractError {
    /// Returns the ambiguous environment variable.
    pub(crate) fn variable(&self) -> &str {
        &self.variable
    }
}

/// Typed environment conversion failure returned through the derive protocol.
#[derive(Debug, thiserror::Error)]
#[error(
    "invalid value from environment variable `{variable}` for configuration field `{field}`: {source}"
)]
pub struct EnvironmentError {
    /// Rust configuration field receiving the value.
    field: String,
    /// Environment variable mapped to the field.
    variable: String,
    /// Underlying typed conversion failure.
    source: EnvironmentValueError,
}

impl EnvironmentError {
    /// Builds one field-aware conversion failure.
    fn new(field: &'static str, variable: &str, source: EnvironmentValueError) -> Self {
        Self { field: String::from(field), variable: String::from(variable), source }
    }

    /// Qualifies an environment conversion error with one nested parent field.
    #[doc(hidden)]
    #[must_use]
    pub fn __within(mut self, parent: &'static str) -> Self {
        self.field.insert(0, '.');
        self.field.insert_str(0, parent);
        self
    }

    /// Returns the dot-qualified configuration field path.
    pub(crate) fn field(&self) -> &str {
        &self.field
    }

    /// Returns the environment variable mapped to the field.
    pub(crate) fn variable(&self) -> &str {
        &self.variable
    }
}

/// Reads and decodes one mapped field from an environment scope.
///
/// # Errors
///
/// Returns an error when a present value is not valid UTF-8 or cannot be
/// deserialized as the requested configuration field type.
pub fn parse_environment_field<T: DeserializeOwned>(
    environment: &Environment,
    field: &'static str,
    variable: &str,
) -> Result<Option<T>, EnvironmentError> {
    let Some(value) = environment.utf8(field, variable)? else {
        return Ok(None);
    };

    T::deserialize(EnvironmentValueDeserializer { input: value })
        .map(Some)
        .map_err(|source| EnvironmentError::new(field, variable, source))
}

/// Reads and decodes one comma-delimited collection field from an environment scope.
///
/// # Errors
///
/// Returns an error when a present value is not valid UTF-8 or any comma-delimited element cannot
/// be deserialized as the requested scalar element type.
pub fn parse_environment_delimited_field<T: DeserializeOwned>(
    environment: &Environment,
    field: &'static str,
    variable: &str,
) -> Result<Option<Vec<T>>, EnvironmentError> {
    let Some(value) = environment.utf8(field, variable)? else {
        return Ok(None);
    };

    value
        .split(',')
        .map(str::trim)
        .map(|input| T::deserialize(EnvironmentValueDeserializer { input }))
        .collect::<Result<Vec<_>, _>>()
        .map(Some)
        .map_err(|source| EnvironmentError::new(field, variable, source))
}

/// Error produced by the scalar environment deserializer.
///
/// Variants deliberately carry no downstream deserializer message. A custom
/// `Deserialize` implementation is allowed to include its input in a Serde
/// error, so retaining arbitrary messages here would make environment-backed
/// credentials observable through Argx diagnostics.
#[derive(Clone, Copy, Debug, thiserror::Error)]
enum EnvironmentValueError {
    /// A present operating-system value was not valid UTF-8.
    #[error("value is not valid UTF-8")]
    NonUtf8,
    /// The scalar could not be decoded as the requested Rust type.
    #[error("value is not valid for the configuration field type")]
    Invalid,
    /// The requested type requires structured environment syntax Argx has not defined.
    #[error("structured environment values are not supported; use a TOML layer instead")]
    Structured,
}

impl de::Error for EnvironmentValueError {
    fn custom<T: fmt::Display>(_message: T) -> Self {
        Self::Invalid
    }
}

/// Serde deserializer for one UTF-8 environment value.
///
/// Environment variables are scalar strings. Scalar Rust values are decoded
/// according to the type requested by Serde. Structured values deliberately
/// remain unsupported until Argx defines an explicit environment syntax for
/// them.
#[derive(Clone, Copy, Debug)]
struct EnvironmentValueDeserializer<'de> {
    /// Raw UTF-8 environment text.
    input: &'de str,
}

impl EnvironmentValueDeserializer<'_> {
    /// Parses the raw text as one scalar type.
    fn parse<T>(&self) -> Result<T, EnvironmentValueError>
    where
        T: FromStr,
    {
        self.input.parse::<T>().map_err(|_| EnvironmentValueError::Invalid)
    }

    /// Returns the common unsupported-structured-value error.
    const fn structured() -> EnvironmentValueError {
        EnvironmentValueError::Structured
    }
}

impl<'de> Deserializer<'de> for EnvironmentValueDeserializer<'de> {
    type Error = EnvironmentValueError;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_borrowed_str(self.input)
    }

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_bool(self.parse()?)
    }

    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i8(self.parse()?)
    }

    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i16(self.parse()?)
    }

    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i32(self.parse()?)
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(self.parse()?)
    }

    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i128(self.parse()?)
    }

    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u8(self.parse()?)
    }

    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u16(self.parse()?)
    }

    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u32(self.parse()?)
    }

    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u64(self.parse()?)
    }

    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u128(self.parse()?)
    }

    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_f32(self.parse()?)
    }

    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_f64(self.parse()?)
    }

    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut chars = self.input.chars();
        let Some(value) = chars.next() else {
            return Err(EnvironmentValueError::Invalid);
        };
        if chars.next().is_some() {
            return Err(EnvironmentValueError::Invalid);
        }
        visitor.visit_char(value)
    }

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_borrowed_str(self.input)
    }

    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_string(self.input.to_owned())
    }

    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_borrowed_bytes(self.input.as_bytes())
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_byte_buf(self.input.as_bytes().to_vec())
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_some(self)
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        if self.input.is_empty() {
            visitor.visit_unit()
        } else {
            Err(EnvironmentValueError::Invalid)
        }
    }

    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(Self::structured())
    }

    fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(Self::structured())
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        _visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(Self::structured())
    }

    fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(Self::structured())
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        Err(Self::structured())
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_enum(StrDeserializer::<EnvironmentValueError>::new(self.input))
    }

    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_unit()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Unit enum used to exercise Serde's string enum path.
    #[derive(Debug, PartialEq, Eq, serde::Deserialize)]
    enum Mode {
        /// Development mode.
        Development,
        /// Production mode.
        Production,
    }

    /// Type whose custom deserializer deliberately tries to echo its input.
    #[derive(Debug)]
    struct EchoingSecret;

    impl<'de> serde::Deserialize<'de> for EchoingSecret {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let value = <String as serde::Deserialize>::deserialize(deserializer)?;
            Err(<D::Error as de::Error>::custom(format!("rejected secret `{value}`")))
        }
    }

    #[test]
    fn scalar_environment_values_follow_the_requested_serde_type() {
        let environment = Environment::from_pairs(&[
            ("BOOL", "true"),
            ("COUNT", "42"),
            ("TEXT", "hello"),
            ("MODE", "Production"),
        ]);

        assert_eq!(
            parse_environment_field::<bool>(&environment, "enabled", "BOOL")
                .expect("bool should parse"),
            Some(true)
        );
        assert_eq!(
            parse_environment_field::<usize>(&environment, "count", "COUNT")
                .expect("integer should parse"),
            Some(42)
        );
        assert_eq!(
            parse_environment_field::<Option<String>>(&environment, "text", "TEXT")
                .expect("optional strings should parse"),
            Some(Some(String::from("hello")))
        );
        assert_eq!(
            parse_environment_field::<Mode>(&environment, "mode", "MODE")
                .expect("unit enum should parse"),
            Some(Mode::Production)
        );
    }

    #[test]
    fn structured_environment_values_fail_explicitly() {
        let environment = Environment::from_pairs(&[("TAGS", "one,two")]);
        let error = parse_environment_field::<Vec<String>>(&environment, "tags", "TAGS")
            .expect_err("Argx has not declared an environment collection syntax");

        assert!(error.to_string().contains("structured environment values are not supported"));
    }

    #[test]
    fn custom_deserializer_errors_cannot_echo_environment_values() {
        const SECRET: &str = "credential-that-must-not-appear";
        let environment = Environment::from_pairs(&[("SECRET", SECRET)]);
        let error = parse_environment_field::<EchoingSecret>(&environment, "secret", "SECRET")
            .expect_err("custom deserializer should reject the value");

        assert!(!error.to_string().contains(SECRET));
        assert!(!format!("{error:?}").contains(SECRET));
        let source =
            std::error::Error::source(&error).expect("conversion error should be retained");
        assert!(!source.to_string().contains(SECRET));
        assert_eq!(source.to_string(), "value is not valid for the configuration field type");
    }
}