envigil 0.2.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
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
//! Validation primitives for environment variable values.
//!
//! A [`Validator`] checks a parsed value and returns a human-readable
//! message on failure. Built-in constructors cover the common cases;
//! any closure `Fn(&T) -> Result<(), String>` is also a `Validator`.
//!
//! # Examples
//!
//! ```
//! use envigil::validate::{self, Validator};
//!
//! let v = validate::range(1..=65535);
//! assert!(v.validate(&8080u16).is_ok());
//! assert!(v.validate(&0u16).is_err());
//!
//! // Closures work directly:
//! let even = |n: &u32| {
//!     if n % 2 == 0 { Ok(()) }
//!     else { Err(format!("{n} is odd")) }
//! };
//! assert!(even.validate(&4).is_ok());
//! assert!(even.validate(&3).is_err());
//! ```

use std::fmt;
use std::ops::RangeInclusive;

/// A validation rule for a parsed value of type `T`.
///
/// Return `Ok(())` if the value is acceptable, or `Err(message)`
/// with a lowercase description of what went wrong.
pub trait Validator<T: ?Sized> {
    /// Check `value`. The error string should be lowercase, no
    /// trailing period.
    fn validate(&self, value: &T) -> Result<(), String>;
}

/// Any closure `Fn(&T) -> Result<(), String>` is a `Validator`.
///
/// # Examples
///
/// ```
/// use envigil::validate::Validator;
///
/// let positive = |n: &i32| {
///     if *n > 0 { Ok(()) }
///     else { Err("must be positive".to_owned()) }
/// };
///
/// assert!(positive.validate(&5).is_ok());
/// assert_eq!(
///     positive.validate(&-1).unwrap_err(),
///     "must be positive"
/// );
/// ```
impl<T: ?Sized, F> Validator<T> for F
where
    F: Fn(&T) -> Result<(), String>,
{
    fn validate(&self, value: &T) -> Result<(), String> {
        self(value)
    }
}

/// Checks that a value falls within an inclusive range.
///
/// Created by [`range`].
#[derive(Debug, Clone)]
pub struct RangeValidator<T> {
    range: RangeInclusive<T>,
    description: String,
}

/// Require a value to be within `range` (inclusive).
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::range(1..=100);
/// assert!(v.validate(&50).is_ok());
/// assert!(v.validate(&0).is_err());
/// assert!(v.validate(&101).is_err());
/// ```
pub fn range<T>(range: RangeInclusive<T>) -> RangeValidator<T>
where
    T: PartialOrd + Clone + fmt::Display,
{
    let description = format!("{}..={}", range.start(), range.end());
    RangeValidator { range, description }
}

impl<T> Validator<T> for RangeValidator<T>
where
    T: PartialOrd + Clone + fmt::Display,
{
    fn validate(&self, value: &T) -> Result<(), String> {
        if self.range.contains(value) {
            Ok(())
        } else {
            Err(format!(
                "value {value} is out of range {}",
                self.description
            ))
        }
    }
}

/// Checks that a string-like value is not empty.
///
/// Created by [`not_empty`].
#[derive(Debug, Clone, Copy)]
pub struct NotEmpty;

/// Require a non-empty string.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::not_empty();
/// assert!(v.validate(&"hello".to_owned()).is_ok());
/// assert!(v.validate(&String::new()).is_err());
/// ```
pub fn not_empty() -> NotEmpty {
    NotEmpty
}

impl Validator<String> for NotEmpty {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.is_empty() {
            Err("must not be empty".to_owned())
        } else {
            Ok(())
        }
    }
}

impl Validator<str> for NotEmpty {
    fn validate(&self, value: &str) -> Result<(), String> {
        if value.is_empty() {
            Err("must not be empty".to_owned())
        } else {
            Ok(())
        }
    }
}

/// Checks that a string contains a substring.
///
/// Created by [`contains`].
#[derive(Debug, Clone)]
pub struct Contains {
    substring: String,
}

/// Require the value to contain `substring`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::contains("@");
/// assert!(v.validate(&"user@example.com".to_owned()).is_ok());
/// assert!(v.validate(&"invalid".to_owned()).is_err());
/// ```
pub fn contains(substring: impl Into<String>) -> Contains {
    Contains {
        substring: substring.into(),
    }
}

impl Validator<String> for Contains {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.contains(&self.substring) {
            Ok(())
        } else {
            Err(format!("must contain {:?}", self.substring))
        }
    }
}

/// Checks that a string starts with a prefix.
///
/// Created by [`starts_with`].
#[derive(Debug, Clone)]
pub struct StartsWith {
    prefix: String,
}

/// Require the value to start with `prefix`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::starts_with("postgres://");
/// assert!(v.validate(&"postgres://localhost/db".to_owned()).is_ok());
/// assert!(v.validate(&"mysql://localhost/db".to_owned()).is_err());
/// ```
pub fn starts_with(prefix: impl Into<String>) -> StartsWith {
    StartsWith {
        prefix: prefix.into(),
    }
}

impl Validator<String> for StartsWith {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.starts_with(&self.prefix) {
            Ok(())
        } else {
            Err(format!("must start with {:?}", self.prefix))
        }
    }
}

/// Checks that a string ends with a suffix.
///
/// Created by [`ends_with`].
#[derive(Debug, Clone)]
pub struct EndsWith {
    suffix: String,
}

/// Require the value to end with `suffix`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::ends_with(".rs");
/// assert!(v.validate(&"main.rs".to_owned()).is_ok());
/// assert!(v.validate(&"main.py".to_owned()).is_err());
/// ```
pub fn ends_with(suffix: impl Into<String>) -> EndsWith {
    EndsWith {
        suffix: suffix.into(),
    }
}

impl Validator<String> for EndsWith {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.ends_with(&self.suffix) {
            Ok(())
        } else {
            Err(format!("must end with {:?}", self.suffix))
        }
    }
}

/// Checks that a string's or collection's length falls within a range.
///
/// Created by [`length`].
#[derive(Debug, Clone)]
pub struct LengthValidator {
    range: RangeInclusive<usize>,
    description: String,
}

/// Require the length of a string or collection to be within `range`
/// (inclusive).
///
/// Implemented for `String`, `str`, and `Vec<T>`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::length(1..=255);
/// assert!(v.validate(&"hello".to_owned()).is_ok());
/// assert!(v.validate(&String::new()).is_err());
/// assert!(v.validate(&vec![1, 2, 3]).is_ok());
/// ```
pub fn length(range: RangeInclusive<usize>) -> LengthValidator {
    let description = format!("{}..={}", range.start(), range.end());
    LengthValidator { range, description }
}

impl LengthValidator {
    fn check_len(&self, len: usize) -> Result<(), String> {
        if self.range.contains(&len) {
            Ok(())
        } else {
            Err(format!("length {len} is out of range {}", self.description))
        }
    }
}

impl Validator<String> for LengthValidator {
    fn validate(&self, value: &String) -> Result<(), String> {
        self.check_len(value.len())
    }
}

impl Validator<str> for LengthValidator {
    fn validate(&self, value: &str) -> Result<(), String> {
        self.check_len(value.len())
    }
}

impl<T> Validator<Vec<T>> for LengthValidator {
    fn validate(&self, value: &Vec<T>) -> Result<(), String> {
        self.check_len(value.len())
    }
}

/// Checks that a string is a valid IP address (v4 or v6).
///
/// Created by [`ip`].
#[derive(Debug, Clone, Copy)]
pub struct Ip;

/// Require the value to parse as a [`std::net::IpAddr`].
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::ip();
/// assert!(v.validate(&"127.0.0.1".to_owned()).is_ok());
/// assert!(v.validate(&"::1".to_owned()).is_ok());
/// assert!(v.validate(&"999.999.999.999".to_owned()).is_err());
/// ```
pub fn ip() -> Ip {
    Ip
}

impl Validator<String> for Ip {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.parse::<std::net::IpAddr>().is_ok() {
            Ok(())
        } else {
            Err("must be a valid IP address".to_owned())
        }
    }
}

impl Validator<str> for Ip {
    fn validate(&self, value: &str) -> Result<(), String> {
        if value.parse::<std::net::IpAddr>().is_ok() {
            Ok(())
        } else {
            Err("must be a valid IP address".to_owned())
        }
    }
}

/// Checks that a path exists on the filesystem.
///
/// Created by [`file_exists`].
#[derive(Debug, Clone, Copy)]
pub struct FileExists;

/// Require the path to exist (`Path::exists()`).
///
/// Implemented for `String` and `PathBuf`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::file_exists();
/// // The current directory always exists.
/// assert!(v.validate(&".".to_owned()).is_ok());
/// assert!(v.validate(&"definitely_missing_envigil_file".to_owned()).is_err());
/// ```
pub fn file_exists() -> FileExists {
    FileExists
}

impl Validator<String> for FileExists {
    fn validate(&self, value: &String) -> Result<(), String> {
        if std::path::Path::new(value).exists() {
            Ok(())
        } else {
            Err("file does not exist".to_owned())
        }
    }
}

impl Validator<std::path::PathBuf> for FileExists {
    fn validate(&self, value: &std::path::PathBuf) -> Result<(), String> {
        if value.exists() {
            Ok(())
        } else {
            Err("file does not exist".to_owned())
        }
    }
}

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

    #[test]
    fn range_accepts_in_bounds() {
        let v = range(1..=65535);
        assert!(v.validate(&1u16).is_ok());
        assert!(v.validate(&8080u16).is_ok());
        assert!(v.validate(&65535u16).is_ok());
    }

    #[test]
    fn range_rejects_out_of_bounds() {
        let v = range(1..=65535);
        assert!(v.validate(&0u16).is_err());
    }

    #[test]
    fn range_error_message() {
        let v = range(1..=100);
        let msg = v.validate(&200).unwrap_err();
        assert!(msg.contains("200"), "message: {msg}");
        assert!(msg.contains("1..=100"), "message: {msg}");
    }

    #[test]
    fn not_empty_accepts_nonempty() {
        let v = not_empty();
        assert!(v.validate(&"x".to_owned()).is_ok());
    }

    #[test]
    fn not_empty_rejects_empty_string() {
        let v = not_empty();
        let msg = v.validate(&String::new()).unwrap_err();
        assert_eq!(msg, "must not be empty");
    }

    #[test]
    fn not_empty_rejects_empty_str() {
        let v = not_empty();
        assert!(v.validate("").is_err());
        assert!(v.validate("ok").is_ok());
    }

    #[test]
    fn contains_match() {
        let v = contains("@");
        assert!(v.validate(&"a@b.com".to_owned()).is_ok());
    }

    #[test]
    fn contains_no_match() {
        let v = contains("@");
        let msg = v.validate(&"nope".to_owned()).unwrap_err();
        assert!(msg.contains("@"), "message: {msg}");
    }

    #[test]
    fn starts_with_match() {
        let v = starts_with("postgres://");
        assert!(v.validate(&"postgres://localhost".to_owned()).is_ok());
    }

    #[test]
    fn starts_with_no_match() {
        let v = starts_with("postgres://");
        let msg = v.validate(&"mysql://localhost".to_owned()).unwrap_err();
        assert!(msg.contains("postgres://"), "message: {msg}");
    }

    #[test]
    fn ends_with_match() {
        let v = ends_with(".rs");
        assert!(v.validate(&"lib.rs".to_owned()).is_ok());
    }

    #[test]
    fn ends_with_no_match() {
        let v = ends_with(".rs");
        let msg = v.validate(&"lib.py".to_owned()).unwrap_err();
        assert!(msg.contains(".rs"), "message: {msg}");
    }

    #[test]
    fn closure_validator() {
        let even = |n: &u32| {
            if n % 2 == 0 {
                Ok(())
            } else {
                Err(format!("{n} is odd"))
            }
        };

        assert!(even.validate(&4).is_ok());
        assert_eq!(even.validate(&3).unwrap_err(), "3 is odd");
    }

    #[test]
    fn works_as_trait_object() {
        let validators: Vec<Box<dyn Validator<String>>> =
            vec![Box::new(not_empty()), Box::new(contains("@"))];

        let value = "user@example.com".to_owned();
        for v in &validators {
            assert!(v.validate(&value).is_ok());
        }

        let bad = String::new();
        assert!(validators[0].validate(&bad).is_err());
    }

    #[test]
    fn length_accepts_string_in_range() {
        let v = length(1..=5);
        assert!(v.validate(&"abc".to_owned()).is_ok());
        assert!(v.validate(&"a".to_owned()).is_ok());
        assert!(v.validate(&"abcde".to_owned()).is_ok());
    }

    #[test]
    fn length_rejects_too_short() {
        let v = length(2..=5);
        assert!(v.validate(&"a".to_owned()).is_err());
        assert!(v.validate(&String::new()).is_err());
    }

    #[test]
    fn length_rejects_too_long() {
        let v = length(1..=3);
        assert!(v.validate(&"abcdef".to_owned()).is_err());
    }

    #[test]
    fn length_works_on_str() {
        let v = length(1..=5);
        assert!(v.validate("abc").is_ok());
        assert!(v.validate("").is_err());
    }

    #[test]
    fn length_works_on_vec() {
        let v = length(1..=3);
        assert!(v.validate(&vec![1, 2]).is_ok());
        assert!(v.validate(&Vec::<u8>::new()).is_err());
        assert!(v.validate(&vec![1, 2, 3, 4]).is_err());
    }

    #[test]
    fn length_error_message() {
        let v = length(2..=5);
        let msg = v.validate(&"a".to_owned()).unwrap_err();
        assert!(msg.contains("length 1"), "message: {msg}");
        assert!(msg.contains("2..=5"), "message: {msg}");
    }

    #[test]
    fn ip_accepts_ipv4() {
        let v = ip();
        assert!(v.validate(&"127.0.0.1".to_owned()).is_ok());
        assert!(v.validate(&"192.168.1.1".to_owned()).is_ok());
        assert!(v.validate(&"0.0.0.0".to_owned()).is_ok());
    }

    #[test]
    fn ip_accepts_ipv6() {
        let v = ip();
        assert!(v.validate(&"::1".to_owned()).is_ok());
        assert!(v.validate(&"2001:db8::1".to_owned()).is_ok());
    }

    #[test]
    fn ip_rejects_invalid() {
        let v = ip();
        assert!(v.validate(&"999.999.999.999".to_owned()).is_err());
        assert!(v.validate(&"not-an-ip".to_owned()).is_err());
        assert!(v.validate(&"1.2.3".to_owned()).is_err());
        assert!(v.validate(&String::new()).is_err());
    }

    #[test]
    fn ip_works_on_str() {
        let v = ip();
        assert!(v.validate("10.0.0.1").is_ok());
        assert!(v.validate("nope").is_err());
    }

    #[test]
    fn ip_error_message() {
        let v = ip();
        let msg = v.validate(&"bad".to_owned()).unwrap_err();
        assert!(msg.contains("IP address"), "message: {msg}");
    }

    #[test]
    fn file_exists_accepts_existing_path() {
        let v = file_exists();
        // The current directory always exists.
        assert!(v.validate(&".".to_owned()).is_ok());
    }

    #[test]
    fn file_exists_rejects_missing_path() {
        let v = file_exists();
        assert!(v.validate(&"definitely_missing_envigil_file_xyz".to_owned()).is_err());
    }

    #[test]
    fn file_exists_error_message() {
        let v = file_exists();
        let msg = v
            .validate(&"definitely_missing_envigil_file_xyz".to_owned())
            .unwrap_err();
        assert!(msg.contains("does not exist"), "message: {msg}");
    }

    #[test]
    fn file_exists_works_on_pathbuf() {
        let v = file_exists();
        assert!(v.validate(&std::path::PathBuf::from(".")).is_ok());
        assert!(v.validate(&std::path::PathBuf::from("definitely_missing_envigil_file_xyz")).is_err());
    }
}