lib.rs 6.35 KB
Newer Older
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
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Configuration utilities and trait re-exports.
//!
//! This module provides utility functions for parsing configuration values
//! and re-exports the core configuration traits from the integrations module.

// ===== Environment Variable Utilities =====

/// Check if a string is truthy.
///
/// This will be used to evaluate environment variables or any other subjective
/// configuration parameters that can be set by the user that should be evaluated
/// as a boolean value.
///
/// Truthy values: "1", "true", "on", "yes" (case-insensitive)
///
/// Returns `false` for invalid values. Use [`parse_bool`] if you need to error on invalid values.
pub fn is_truthy(val: &str) -> bool {
    matches!(val.to_lowercase().as_str(), "1" | "true" | "on" | "yes")
}

/// Check if a string is falsey.
///
/// This will be used to evaluate environment variables or any other subjective
/// configuration parameters that can be set by the user that should be evaluated
/// as a boolean value (opposite of is_truthy).
///
/// Falsey values: "0", "false", "off", "no" (case-insensitive)
///
/// Returns `false` for invalid values. Use [`parse_bool`] if you need to error on invalid values.
pub fn is_falsey(val: &str) -> bool {
    matches!(val.to_lowercase().as_str(), "0" | "false" | "off" | "no")
}

/// Parse a string as a boolean value, returning an error if invalid.
///
/// This function strictly validates that the input is a valid boolean representation.
///
/// # Arguments
/// * `val` - The string value to parse
///
/// # Returns
/// * `Ok(true)` - For truthy values: "1", "true", "on", "yes" (case-insensitive)
/// * `Ok(false)` - For falsey values: "0", "false", "off", "no" (case-insensitive)
/// * `Err(_)` - For any other value
///
/// # Example
/// ```ignore
/// assert_eq!(parse_bool("true")?, true);
/// assert_eq!(parse_bool("0")?, false);
/// assert!(parse_bool("maybe").is_err());
/// ```
pub fn parse_bool(val: &str) -> anyhow::Result<bool> {
    if is_truthy(val) {
        Ok(true)
    } else if is_falsey(val) {
        Ok(false)
    } else {
        anyhow::bail!(
            "Invalid boolean value: '{}'. Expected one of: true/false, 1/0, on/off, yes/no",
            val
        )
    }
}

/// Check if an environment variable is truthy.
///
/// Returns `false` if the environment variable is not set or is invalid.
/// Use [`env_parse_bool`] if you need to distinguish between unset, valid, and invalid values.
pub fn env_is_truthy(env: &str) -> bool {
    match std::env::var(env) {
        Ok(val) => is_truthy(val.as_str()),
        Err(_) => false,
    }
}

/// Check if an environment variable is falsey.
///
/// Returns `false` if the environment variable is not set or is invalid.
/// Use [`env_parse_bool`] if you need to distinguish between unset, valid, and invalid values.
pub fn env_is_falsey(env: &str) -> bool {
    match std::env::var(env) {
        Ok(val) => is_falsey(val.as_str()),
        Err(_) => false,
    }
}

/// Parse an environment variable as a boolean, returning an error if invalid.
///
/// # Arguments
/// * `env` - The environment variable name
///
/// # Returns
/// * `Ok(Some(true))` - If the env var is set to a truthy value
/// * `Ok(Some(false))` - If the env var is set to a falsey value
/// * `Ok(None)` - If the env var is not set
/// * `Err(_)` - If the env var is set to an invalid value
///
/// # Example
/// ```ignore
/// match env_parse_bool("MY_FLAG")? {
///     Some(true) => println!("enabled"),
///     Some(false) => println!("disabled"),
///     None => println!("not configured"),
/// }
/// ```
pub fn env_parse_bool(env: &str) -> anyhow::Result<Option<bool>> {
    match std::env::var(env) {
        Ok(val) => parse_bool(&val).map(Some),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(e) => anyhow::bail!("Failed to read environment variable {}: {}", env, e),
    }
}

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

    #[test]
    fn test_is_truthy() {
        assert!(is_truthy("1"));
        assert!(is_truthy("true"));
        assert!(is_truthy("True"));
        assert!(is_truthy("TRUE"));
        assert!(is_truthy("on"));
        assert!(is_truthy("ON"));
        assert!(is_truthy("yes"));
        assert!(is_truthy("YES"));

        assert!(!is_truthy("0"));
        assert!(!is_truthy("false"));
        assert!(!is_truthy("off"));
        assert!(!is_truthy("no"));
        assert!(!is_truthy(""));
        assert!(!is_truthy("random"));
    }

    #[test]
    fn test_is_falsey() {
        assert!(is_falsey("0"));
        assert!(is_falsey("false"));
        assert!(is_falsey("False"));
        assert!(is_falsey("FALSE"));
        assert!(is_falsey("off"));
        assert!(is_falsey("OFF"));
        assert!(is_falsey("no"));
        assert!(is_falsey("NO"));

        assert!(!is_falsey("1"));
        assert!(!is_falsey("true"));
        assert!(!is_falsey("on"));
        assert!(!is_falsey("yes"));
        assert!(!is_falsey(""));
        assert!(!is_falsey("random"));
    }

    #[test]
    fn test_env_is_truthy_not_set() {
        // Test with a variable that definitely doesn't exist
        assert!(!env_is_truthy("DEFINITELY_NOT_SET_VAR_12345"));
    }

    #[test]
    fn test_env_is_falsey_not_set() {
        // Test with a variable that definitely doesn't exist
        assert!(!env_is_falsey("DEFINITELY_NOT_SET_VAR_12345"));
    }

    #[test]
    fn test_parse_bool() {
        // Truthy values
        assert!(parse_bool("1").unwrap());
        assert!(parse_bool("true").unwrap());
        assert!(parse_bool("TRUE").unwrap());
        assert!(parse_bool("on").unwrap());
        assert!(parse_bool("yes").unwrap());

        // Falsey values
        assert!(!parse_bool("0").unwrap());
        assert!(!parse_bool("false").unwrap());
        assert!(!parse_bool("FALSE").unwrap());
        assert!(!parse_bool("off").unwrap());
        assert!(!parse_bool("no").unwrap());

        // Invalid values
        assert!(parse_bool("").is_err());
        assert!(parse_bool("maybe").is_err());
        assert!(parse_bool("2").is_err());
        assert!(parse_bool("random").is_err());
    }

    #[test]
    fn test_env_parse_bool_not_set() {
        // Test with a variable that definitely doesn't exist
        assert_eq!(
            env_parse_bool("DEFINITELY_NOT_SET_VAR_12345").unwrap(),
            None
        );
    }
}