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
#![warn(
    clippy::all,
    clippy::pedantic,
    clippy::nursery,
    clippy::cargo,
    clippy::unwrap_used,
    missing_crate_level_docs,
    missing_docs
)]

//! Use this crate to parse environment variables into any type that
//! implements [`FromStr`](std::str::FromStr).
//!
//! # Basic usage
//! ```
//! # fn main() -> Result<(), strict_env::Error> {
//! std::env::set_var("PORT", "9001");
//! let port: u16 = strict_env::parse("PORT")?;
//! assert_eq!(port, 9001);
//! # Ok(())
//! # }
//! ```
//!
//! # Usage with remote types
//! If you need to parse a type that originates from an external crate
//! and does not implement [`FromStr`](std::str::FromStr), you can wrap
//! the value in a newtype that implements the trait.
//! ```
//! // std::time::Duration does not implement FromStr!
//! struct ConfigDuration(std::time::Duration);
//!
//! // Custom implementation using the awesome humantime crate
//! impl std::str::FromStr for ConfigDuration {
//!     type Err = humantime::DurationError;
//!
//!     fn from_str(s: &str) -> Result<Self, Self::Err> {
//!         let inner = humantime::parse_duration(s)?;
//!         Ok(Self(inner))
//!     }
//! }
//!
//! // Now we can use strict_env! (But we might have to use the turbofish.)
//! # fn main() -> Result<(), strict_env::Error> {
//! std::env::set_var("CACHE_DURATION", "2 minutes");
//! let cache_duration = strict_env::parse::<ConfigDuration>("CACHE_DURATION")?.0;
//! assert_eq!(cache_duration.as_secs(), 120);
//! # Ok(())
//! # }
//! ```

use std::{
    env::{self, VarError},
    ffi::OsString,
    str::FromStr,
};

/// Parse an environment variable into a value that implements
/// [`FromStr`](std::str::FromStr).
///
/// # Errors
/// Returns an error if the requested environment variable is missing
/// or empty, contains invalid UTF-8, or has a value that cannot be
/// parsed into the target type.
pub fn parse<T: FromStr>(name: &str) -> Result<T, Error>
where
    T::Err: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    let value_result = env::var(name);
    let value = match value_result {
        Ok(value) => {
            if value.is_empty() {
                return Err(Error::Missing {
                    name: name.to_owned(),
                });
            }
            value
        }
        Err(err) => match err {
            VarError::NotPresent => {
                return Err(Error::Missing {
                    name: name.to_owned(),
                })
            }
            VarError::NotUnicode(value) => {
                return Err(Error::InvalidUtf8 {
                    name: name.to_owned(),
                    value,
                })
            }
        },
    };
    let parse_result = T::from_str(&value);
    let parsed = match parse_result {
        Ok(parsed) => parsed,
        Err(err) => {
            return Err(Error::InvalidValue {
                name: name.to_owned(),
                value,
                source: err.into(),
            })
        }
    };
    Ok(parsed)
}

/// Like [`parse`](crate::parse), but allows the environment variable to
/// be missing or empty.
///
/// The parsed object is wrapped in an [`Option`](Option) to allow this.
///
/// # Errors
/// Returns an error if the requested environment variable contains invalid
/// UTF-8 or has a value that cannot be parsed into the target type.
pub fn parse_optional<T: FromStr>(name: &str) -> Result<Option<T>, Error>
where
    T::Err: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    let result = parse(name);
    match result {
        Ok(parsed) => Ok(Some(parsed)),
        Err(Error::Missing { .. }) => Ok(None),
        Err(err) => Err(err),
    }
}

/// Like [`parse`](crate::parse), but falls back to a default value when
/// the environment variable is missing or empty.
///
/// The target type must implement [`Default`](Default).
///
/// # Errors
/// Returns an error if the requested environment variable contains invalid
/// UTF-8 or has a value that cannot be parsed into the target type.
pub fn parse_or_default<T: FromStr + Default>(name: &str) -> Result<T, Error>
where
    T::Err: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    parse_optional(name).map(Option::unwrap_or_default)
}

#[derive(Debug, thiserror::Error)]
/// Error type for this library.
pub enum Error {
    /// The requested environment variable was missing or empty.
    #[error("Missing or empty environment variable {name:?}")]
    Missing {
        /// Name of the requested environment variable.
        name: String,
    },
    #[error("Invalid UTF-8 in environment variable {name:?}")]
    /// The environment variable exists, but its value is not valid
    /// UTF-8.
    InvalidUtf8 {
        /// Name of the requested environment variable.
        name: String,
        /// Value of the environment variable.
        value: OsString,
    },
    #[error("Error parsing environment variable {name:?}: {source}")]
    /// The environment variable exists and is valid UTF-8, but it
    /// could not be parsed into the target type.
    InvalidValue {
        /// Name of the requested environment variable.
        name: String,
        /// Value of the environment variable.
        value: String,
        #[source]
        /// The underlying error that occurred during parsing.
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

#[allow(
    clippy::missing_const_for_fn,
    clippy::unwrap_used,
    clippy::wildcard_imports
)]
#[cfg(test)]
mod tests {
    use crate::*;
    use os_str_bytes::OsStrBytes;
    use serial_test::serial;
    use std::ffi::OsStr;

    mod parse {
        use super::*;

        #[test]
        #[serial]
        fn valid() {
            let _guard = EnvGuard::with("TEST_VAR", "255");
            let value: u8 = parse("TEST_VAR").unwrap();
            assert_eq!(value, 255);
        }

        #[test]
        #[serial]
        fn missing() {
            let _guard = EnvGuard::without("TEST_VAR");
            let error = parse::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::Missing { .. }));
        }

        #[test]
        #[serial]
        fn empty() {
            let _guard = EnvGuard::with("TEST_VAR", "");
            let error = parse::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::Missing { .. }));
        }

        #[test]
        #[serial]
        fn invalid_utf8() {
            let value = invalid_utf8_string();
            let _guard = EnvGuard::with("TEST_VAR", value);
            let error = parse::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidUtf8 { .. }));
        }

        #[test]
        #[serial]
        fn invalid_value() {
            let _guard = EnvGuard::with("TEST_VAR", "256");
            let error = parse::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidValue { .. }));
        }
    }

    mod parse_optional {
        use super::*;

        #[test]
        #[serial]
        fn valid() {
            let _guard = EnvGuard::with("TEST_VAR", "255");
            let value: u8 = parse_optional("TEST_VAR").unwrap().unwrap();
            assert_eq!(value, 255);
        }

        #[test]
        #[serial]
        fn missing() {
            let _guard = EnvGuard::without("TEST_VAR");
            let option = parse_optional::<u8>("TEST_VAR").unwrap();
            assert_eq!(option, None);
        }

        #[test]
        #[serial]
        fn empty() {
            let _guard = EnvGuard::with("TEST_VAR", "");
            let option = parse_optional::<u8>("TEST_VAR").unwrap();
            assert_eq!(option, None);
        }

        #[test]
        #[serial]
        fn invalid_utf8() {
            let invalid_unicode_bytes = [b'f', b'o', b'o', 0x80];
            let invalid_unicode = OsStr::from_raw_bytes(&invalid_unicode_bytes[..]).unwrap();
            let _guard = EnvGuard::with("TEST_VAR", &invalid_unicode);
            let error = parse_optional::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidUtf8 { .. }));
        }

        #[test]
        #[serial]
        fn invalid_value() {
            let _guard = EnvGuard::with("TEST_VAR", "256");
            let error = parse_optional::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidValue { .. }));
        }
    }

    mod parse_or_default {
        use super::*;

        #[test]
        #[serial]
        fn valid() {
            let _guard = EnvGuard::with("TEST_VAR", "255");
            let value: u8 = parse_or_default("TEST_VAR").unwrap();
            assert_eq!(value, 255);
        }

        #[test]
        #[serial]
        fn missing() {
            let _guard = EnvGuard::without("TEST_VAR");
            let value: u8 = parse_or_default::<u8>("TEST_VAR").unwrap();
            assert_eq!(value, 0);
        }

        #[test]
        #[serial]
        fn empty() {
            let _guard = EnvGuard::with("TEST_VAR", "");
            let value: u8 = parse_or_default::<u8>("TEST_VAR").unwrap();
            assert_eq!(value, 0);
        }

        #[test]
        #[serial]
        fn invalid_utf8() {
            let invalid_unicode_bytes = [b'f', b'o', b'o', 0x80];
            let invalid_unicode = OsStr::from_raw_bytes(&invalid_unicode_bytes[..]).unwrap();
            let _guard = EnvGuard::with("TEST_VAR", &invalid_unicode);
            let error = parse_or_default::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidUtf8 { .. }));
        }

        #[test]
        #[serial]
        fn invalid_value() {
            let _guard = EnvGuard::with("TEST_VAR", "256");
            let error = parse_or_default::<u8>("TEST_VAR").unwrap_err();
            assert!(matches!(error, Error::InvalidValue { .. }));
        }
    }

    mod error {
        use super::*;

        #[test]
        fn is_send() {
            assert_send::<Error>();
        }

        #[test]
        fn is_sync() {
            assert_sync::<Error>();
        }

        #[test]
        fn is_static() {
            assert_static::<Error>();
        }

        #[test]
        fn is_into_anyhow() {
            assert_into_anyhow::<Error>();
        }

        #[test]
        fn missing() {
            let error = Error::Missing {
                name: "TEST_VAR".into(),
            };
            assert_eq!(
                error.to_string(),
                "Missing or empty environment variable \"TEST_VAR\"",
            );
        }

        #[test]
        fn invalid_utf8() {
            let error = Error::InvalidUtf8 {
                name: "TEST_VAR".into(),
                value: invalid_utf8_string(),
            };
            assert_eq!(
                error.to_string(),
                "Invalid UTF-8 in environment variable \"TEST_VAR\"",
            );
        }

        #[test]
        fn invalid_value() {
            let source = "".parse::<u8>().unwrap_err();
            let error = Error::InvalidValue {
                name: "TEST_VAR".into(),
                value: "".into(),
                source: source.into(),
            };
            assert_eq!(
                error.to_string(),
                "Error parsing environment variable \"TEST_VAR\": cannot parse integer from empty string",
            );
        }
    }

    // utils

    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    fn assert_static<T: 'static>() {}
    fn assert_into_anyhow<T: Into<anyhow::Error>>() {}

    fn invalid_utf8_string() -> OsString {
        let bytes = [b'f', b'o', b'o', 0x80];
        std::str::from_utf8(&bytes).unwrap_err();
        OsStr::from_raw_bytes(&bytes[..]).unwrap().to_os_string()
    }

    struct EnvGuard {
        vars: Vec<(OsString, OsString)>,
    }

    impl EnvGuard {
        fn new() -> Self {
            Self {
                vars: std::env::vars_os().collect(),
            }
        }
        fn with(name: &str, value: impl AsRef<OsStr>) -> Self {
            let guard = Self::new();
            std::env::set_var(name, value);
            guard
        }
        fn without(name: impl AsRef<OsStr>) -> Self {
            let guard = Self::new();
            std::env::remove_var(name);
            guard
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (var, _) in std::env::vars_os() {
                std::env::remove_var(var);
            }
            assert_eq!(std::env::vars_os().count(), 0);
            for (var, value) in &self.vars {
                std::env::set_var(var, value);
            }
        }
    }
}