tenvy 1.0.0

Parse environment variables into type-safe structures
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
//! Parse environment variables into type-safe structures.
//!
//! ```no_run
//! use tenvy::Tenvy;
//!
//! #[derive(Debug, Tenvy)]
//! struct Environment {
//!     database_url: String,
//!     server: Server,
//! }
//!
//! #[derive(Debug, Tenvy)]
//! struct Server {
//!     addr: std::net::SocketAddr,
//!     workers: Option<std::num::NonZeroUsize>,
//! }
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let env: Environment = tenvy::from_env()?;
//!     println!("{env:#?}");
//!     Ok(())
//! }
//! ```

#![cfg_attr(docsrs, feature(doc_auto_cfg))]

use std::{
    ffi::{OsStr, OsString},
    marker::PhantomData,
    path::PathBuf,
};

#[cfg(feature = "derive")]
pub use tenvy_derive::Tenvy;

/// An error during parsing of environment variables.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// This environment variable is missing.
    #[error("environment variable `{}` is missing", .0.display())]
    Missing(OsString),
    /// This environment variable failed to parse to some expected type.
    #[error("cannot parse `{}`", var.display())]
    InvalidValue {
        var: OsString,
        #[source]
        error: Box<dyn std::error::Error + Send + Sync>,
    },
}

/// Current context of environment variable parsing.
///
/// `Env` keeps track of nesting by storing the name of the “current” variable. A type's parser may
/// choose to read the value of the current variable using [`value`], or use it to parse
/// its fields using [`nest`] and [`field`].
///
/// [`value`]: Self::value
/// [`nest`]: Self::nest
/// [`field`]: Self::field
#[derive(Debug)]
pub struct Env {
    var: OsString,
}

/// Parse a value from environment variables.
///
/// This trait covers both basic types that only read the value of the current variable (e.g.
/// numbers, [`bool`], [`String`]) as well as structures that have fields parsed from different
/// variables.
///
/// Usually, a type parses itself, hence `T` defaults to `Self`. However, some types do not parse
/// themselves but other types—they are called _adapters_. Notable adapters are
/// [`tenvy::From<T>`](From), [`tenvy::TryFrom<T>`](TryFrom), and [`tenvy::FromStr`](FromStr) which
/// can parse any type if they implement a corresponding trait.
///
/// You can derive this trait using the [`Tenvy`] derive macro.
///
/// [`Tenvy`]: derive@Tenvy
///
/// # Examples
///
/// Implementation for a basic type:
///
/// ```
/// # use tenvy::*;
/// enum Color {
///     Orange,
///     Blue,
/// }
///
/// impl Tenvy for Color {
///    fn from_env(env: &Env) -> Result<Self, Error> {
///       #[derive(Debug, thiserror::Error)]
///       #[error("expected `orange` or `blue`")]
///       struct InvalidColor;
///
///       match env.value()?.to_str() {
///           Some("orange") => Ok(Self::Orange),
///           Some("blue") => Ok(Self::Blue),
///           _ => Err(Error::invalid_value(env, InvalidColor)),
///       }
///    }
/// }
/// ```
///
/// Implementation for a structure:
///
/// ```
/// # use tenvy::*;
/// # struct Database { url: String }
/// impl Tenvy for Database {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         Ok(Self {
///             url: env.field("URL")?,
///         })
///     }
/// }
/// ```
pub trait Tenvy<T = Self> {
    /// Parse a value in the current context. You can either use [`Env::value`] to read the current
    /// variable, or [`Env::field`] to parse fields.
    fn from_env(env: &Env) -> Result<T, Error>;
}

/// Parse environment variables into `T`.
///
/// # Examples
///
/// ```no_run
/// # use tenvy::*;
/// #[derive(Debug, Tenvy)]
/// struct Environment {
///     database_url: String,
/// }
///
/// fn main() -> Result<(), Error> {
///     let environment: Environment = tenvy::from_env()?;
///     run_server(environment.database_url)
/// }
///
/// # fn run_server<T>(_: T) -> ! { loop {} }
/// ```
pub fn from_env<T: Tenvy>() -> Result<T, Error> {
    T::from_env(&Env {
        var: OsString::default(),
    })
}

impl Error {
    /// Construct an [`InvalidValue`], extracting the name of the expected variable name from the
    /// [`Env`].
    ///
    /// [`InvalidValue`]: Error::InvalidValue
    ///
    /// # Examples
    ///
    /// ```
    /// # use tenvy::*;
    /// enum Color {
    ///     Orange,
    ///     Blue,
    /// }
    ///
    /// impl Tenvy for Color {
    ///    fn from_env(env: &Env) -> Result<Self, Error> {
    ///       #[derive(Debug, thiserror::Error)]
    ///       #[error("expected `orange` or `blue`")]
    ///       struct InvalidColor;
    ///
    ///       match env.value()?.to_str() {
    ///           Some("orange") => Ok(Self::Orange),
    ///           Some("blue") => Ok(Self::Blue),
    ///           _ => Err(Error::invalid_value(env, InvalidColor)),
    ///       }
    ///    }
    /// }
    /// ```
    pub fn invalid_value<E: std::error::Error + Send + Sync + 'static>(
        env: &Env,
        error: E,
    ) -> Self {
        Self::InvalidValue {
            var: env.var.clone(),
            error: Box::new(error),
        }
    }

    /// Replace [`Error::Missing`] with the provided value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tenvy::*;
    /// use std::num::NonZeroU8;
    ///
    /// pub struct Workers(NonZeroU8);
    ///
    /// impl Tenvy for Workers {
    ///     fn from_env(env: &Env) -> Result<Self, Error> {
    ///         NonZeroU8::from_env(env).map(Workers).or_else(|error| {
    ///             error.replace_missing(|| Workers(NonZeroU8::new(1).unwrap()))
    ///         })
    ///     }
    /// }
    /// ```
    pub fn replace_missing<T>(self, f: impl FnOnce() -> T) -> Result<T, Error> {
        match self {
            Error::Missing(_) => Ok(f()),
            other => Err(other),
        }
    }
}

impl Env {
    /// Read the value of the current variable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Missing`] if the current variable is missing.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tenvy::*;
    /// enum Color {
    ///     Orange,
    ///     Blue,
    /// }
    ///
    /// impl Tenvy for Color {
    ///    fn from_env(env: &Env) -> Result<Self, Error> {
    ///       #[derive(Debug, thiserror::Error)]
    ///       #[error("expected `orange` or `blue`")]
    ///       struct InvalidColor;
    ///
    ///       match env.value()?.to_str() {
    ///           Some("orange") => Ok(Self::Orange),
    ///           Some("blue") => Ok(Self::Blue),
    ///           _ => Err(Error::invalid_value(env, InvalidColor)),
    ///       }
    ///    }
    /// }
    /// ```
    pub fn value(&self) -> Result<OsString, Error> {
        std::env::var_os(&self.var).ok_or_else(|| Error::Missing(self.var.clone()))
    }

    /// Construct a new context for a `field`, i.e. append `field` to the current variable name.
    /// The separator `_` is added automatically.
    pub fn nest<K: AsRef<OsStr>>(&self, field: K) -> Self {
        let mut var = self.var.clone();
        if !var.is_empty() && !field.as_ref().is_empty() {
            var.push("_");
        }
        var.push(field);

        Self { var }
    }

    /// Parse a value in a [`nest`]ed context.
    ///
    /// [`nest`]: Self::nest
    ///
    /// # Examples
    ///
    /// ```
    /// # use tenvy::*;
    /// # struct Database { url: String }
    /// impl Tenvy for Database {
    ///     fn from_env(env: &Env) -> Result<Self, Error> {
    ///         Ok(Self {
    ///             url: env.field("URL")?,
    ///         })
    ///     }
    /// }
    /// ```
    pub fn field<K: AsRef<OsStr>, T: Tenvy>(&self, field: K) -> Result<T, Error> {
        T::from_env(&self.nest(field))
    }
}

/// Adapter that parses `T` using its `FromStr` implementation.
///
/// This adapter is most useful with [`#[derive(Tenvy)]`][derive] and `#[tenvy(via)]`:
///
/// ```
/// # use tenvy::*;
/// use std::str::FromStr;
///
/// #[derive(Tenvy)]
/// #[tenvy(via = tenvy::FromStr)]
/// enum Color {
///     Orange,
///     Blue,
/// };
///
/// #[derive(Debug, thiserror::Error)]
/// #[error("expected `orange` or `blue`")]
/// struct InvalidColor;
///
/// impl FromStr for Color {
///     type Err = InvalidColor;
///
///     fn from_str(color: &str) -> Result<Self, Self::Err> {
///         match color {
///             "orange" => Ok(Self::Orange),
///             "blue" => Ok(Self::Blue),
///             _ => Err(InvalidColor),
///         }
///     }
/// }
/// ```
///
/// [derive]: derive@Tenvy
///
/// However, it also simplifies manual implementation:
///
/// ```
/// # use tenvy::*;
/// # enum Color { Orange, Blue }
/// # impl FromStr for Color {
/// #   type Err = std::convert::Infallible;
/// #   fn from_str(_: &str) -> Result<Self, Self::Err> { Ok(Self::Orange) }
/// # }
/// use std::str::FromStr;
///
/// impl Tenvy for Color {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         tenvy::FromStr::from_env(env)
///     }
/// }
/// ```
#[derive(Debug)]
pub struct FromStr(std::convert::Infallible);

/// Adapter that parses `U` and then transforms it into `T` using `From`.
///
/// This adapter is most useful with [`#[derive(Tenvy)]`][derive] and `#[tenvy(via)]`:
///
/// ```
/// # use tenvy::Tenvy;
/// use std::time::Duration;
///
/// #[derive(Tenvy)]
/// struct Seconds(u64);
///
/// impl From<Seconds> for Duration {
///     fn from(Seconds(seconds): Seconds) -> Self {
///         Self::from_secs(seconds)
///     }
/// }
///
/// #[derive(Tenvy)]
/// struct Environment {
///     #[tenvy(rename = "TIMEOUT_SECONDS", via = tenvy::From<Seconds>)]
///     timeout: Duration,
/// }
/// ```
///
/// [derive]: derive@Tenvy
#[derive(Debug)]
pub struct From<U>(PhantomData<U>);

/// Adapter that parses `U` and then transforms it into `T` using `TryFrom`.
///
/// This adapter is most useful with [`#[derive(Tenvy)]`][derive] and `#[tenvy(via)]`:
///
/// ```
/// # use tenvy::Tenvy;
/// #[derive(Tenvy)]
/// #[tenvy(via = tenvy::TryFrom<u8>)]
/// struct Percent(u8);
///
/// #[derive(Debug, thiserror::Error)]
/// #[error("Invalid percent")]
/// struct InvalidPercent;
///
/// impl TryFrom<u8> for Percent {
///     type Error = InvalidPercent;
///
///     fn try_from(percent: u8) -> Result<Self, Self::Error> {
///         match percent {
///             0..=100 => Ok(Self(percent)),
///             _ => Err(InvalidPercent),
///         }
///     }
/// }
/// ```
///
/// [derive]: derive@Tenvy
#[derive(Debug)]
pub struct TryFrom<U>(PhantomData<U>);

impl<T> Tenvy<T> for FromStr
where
    T: std::str::FromStr,
    T::Err: std::error::Error + Send + Sync + 'static,
{
    fn from_env(env: &Env) -> Result<T, Error> {
        String::from_env(env)
            .and_then(|value| T::from_str(&value).map_err(|error| Error::invalid_value(env, error)))
    }
}

impl<U, T> Tenvy<T> for From<U>
where
    T: std::convert::From<U>,
    U: Tenvy,
{
    fn from_env(env: &Env) -> Result<T, Error> {
        U::from_env(env).map(T::from)
    }
}

impl<U, T> Tenvy<T> for TryFrom<U>
where
    T: std::convert::TryFrom<U>,
    T::Error: std::error::Error + Send + Sync + 'static,
    U: Tenvy,
{
    fn from_env(env: &Env) -> Result<T, Error> {
        U::from_env(env)
            .and_then(|value| T::try_from(value).map_err(|error| Error::invalid_value(env, error)))
    }
}

/// Immediately succeeds.
impl Tenvy for () {
    fn from_env(_: &Env) -> Result<Self, Error> {
        Ok(())
    }
}

/// Immediately fails.
impl Tenvy for std::convert::Infallible {
    fn from_env(env: &Env) -> Result<Self, Error> {
        Err(Error::Missing(env.var.clone()))
    }
}

impl<T> Tenvy for std::marker::PhantomData<T> {
    fn from_env(_: &Env) -> Result<Self, Error> {
        Ok(Self)
    }
}

impl Tenvy for std::marker::PhantomPinned {
    fn from_env(_: &Env) -> Result<Self, Error> {
        Ok(Self)
    }
}

impl<T: Tenvy> Tenvy for std::num::Saturating<T> {
    fn from_env(env: &Env) -> Result<Self, Error> {
        T::from_env(env).map(std::num::Saturating)
    }
}

impl<T: Tenvy> Tenvy for std::num::Wrapping<T> {
    fn from_env(env: &Env) -> Result<Self, Error> {
        T::from_env(env).map(std::num::Wrapping)
    }
}

/// Parses a value that may be missing by transforming [`Error::Missing`] into [`None`].
impl<T: Tenvy> Tenvy for Option<T> {
    fn from_env(env: &Env) -> Result<Self, Error> {
        T::from_env(env)
            .map(Some)
            .or_else(|error| error.replace_missing(|| None))
    }
}

impl Tenvy for OsString {
    fn from_env(env: &Env) -> Result<Self, Error> {
        env.value()
    }
}

impl Tenvy for PathBuf {
    fn from_env(env: &Env) -> Result<Self, Error> {
        env.value().map(PathBuf::from)
    }
}

impl Tenvy for String {
    fn from_env(env: &Env) -> Result<Self, Error> {
        #[derive(Debug, thiserror::Error)]
        #[error("value contains invalid Unicode data: {}", .0.display())]
        struct UnicodeError(OsString);

        env.value().and_then(|value| {
            value
                .into_string()
                .map_err(|value| Error::invalid_value(env, UnicodeError(value)))
        })
    }
}

macro_rules! wrap_with_new {
    ($t:ident, $typ:ty) => {
        impl<$t: Tenvy> Tenvy for $typ {
            fn from_env(env: &Env) -> Result<Self, Error> {
                $t::from_env(env).map(Self::new)
            }
        }
    };
}

wrap_with_new!(T, Box<T>);
wrap_with_new!(T, std::cell::Cell<T>);
wrap_with_new!(T, std::cell::RefCell<T>);
wrap_with_new!(T, std::cell::UnsafeCell<T>);
wrap_with_new!(T, std::rc::Rc<T>);
wrap_with_new!(T, std::sync::Arc<T>);
wrap_with_new!(T, std::sync::Mutex<T>);
wrap_with_new!(T, std::sync::RwLock<T>);

macro_rules! delegate_to_from_str {
    ($typ:ty) => {
        impl Tenvy for $typ {
            fn from_env(env: &Env) -> Result<Self, Error> {
                FromStr::from_env(env)
            }
        }
    };
}

delegate_to_from_str!(f32);
delegate_to_from_str!(f64);
delegate_to_from_str!(bool);
delegate_to_from_str!(char);
delegate_to_from_str!(i8);
delegate_to_from_str!(i16);
delegate_to_from_str!(i32);
delegate_to_from_str!(i64);
delegate_to_from_str!(i128);
delegate_to_from_str!(isize);
delegate_to_from_str!(u8);
delegate_to_from_str!(u16);
delegate_to_from_str!(u32);
delegate_to_from_str!(u64);
delegate_to_from_str!(u128);
delegate_to_from_str!(usize);
delegate_to_from_str!(std::net::IpAddr);
delegate_to_from_str!(std::net::Ipv4Addr);
delegate_to_from_str!(std::net::Ipv6Addr);
delegate_to_from_str!(std::net::SocketAddr);
delegate_to_from_str!(std::net::SocketAddrV4);
delegate_to_from_str!(std::net::SocketAddrV6);
delegate_to_from_str!(std::num::NonZeroI8);
delegate_to_from_str!(std::num::NonZeroI16);
delegate_to_from_str!(std::num::NonZeroI32);
delegate_to_from_str!(std::num::NonZeroI64);
delegate_to_from_str!(std::num::NonZeroI128);
delegate_to_from_str!(std::num::NonZeroIsize);
delegate_to_from_str!(std::num::NonZeroU8);
delegate_to_from_str!(std::num::NonZeroU16);
delegate_to_from_str!(std::num::NonZeroU32);
delegate_to_from_str!(std::num::NonZeroU64);
delegate_to_from_str!(std::num::NonZeroU128);
delegate_to_from_str!(std::num::NonZeroUsize);