nautilus_core/env.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Cross-platform environment variable utilities.
17//!
18//! This module provides functions for safely accessing environment variables
19//! with proper error handling.
20
21/// Returns the value of the environment variable for the given `key`.
22///
23/// # Errors
24///
25/// Returns an error if the environment variable is not set.
26pub fn get_env_var(key: &str) -> anyhow::Result<String> {
27 match std::env::var(key) {
28 Ok(var) => Ok(var),
29 Err(_) => anyhow::bail!("environment variable '{key}' must be set"),
30 }
31}
32
33/// Returns the provided `value` if `Some`, otherwise falls back to reading
34/// the environment variable for the given `key`.
35///
36/// Only attempts to read the environment variable when `value` is `None`,
37/// avoiding unnecessary environment variable lookups and errors.
38///
39/// # Errors
40///
41/// Returns an error if `value` is `None` and the environment variable is not set.
42pub fn get_or_env_var(value: Option<String>, key: &str) -> anyhow::Result<String> {
43 match value {
44 Some(v) => Ok(v),
45 None => get_env_var(key),
46 }
47}
48
49////////////////////////////////////////////////////////////////////////////////
50// Tests
51////////////////////////////////////////////////////////////////////////////////
52
53#[cfg(test)]
54mod tests {
55 use rstest::*;
56
57 use super::*;
58
59 #[rstest]
60 fn test_get_env_var_success() {
61 // Test with a commonly available environment variable
62 if let Ok(path) = std::env::var("PATH") {
63 let result = get_env_var("PATH");
64 assert!(result.is_ok());
65 assert_eq!(result.unwrap(), path);
66 }
67 }
68
69 #[rstest]
70 fn test_get_env_var_not_set() {
71 // Use a highly unlikely environment variable name
72 let result = get_env_var("NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_12345");
73 assert!(result.is_err());
74 assert!(result.unwrap_err().to_string().contains(
75 "environment variable 'NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_12345' must be set"
76 ));
77 }
78
79 #[rstest]
80 fn test_get_env_var_error_message_format() {
81 let var_name = "DEFINITELY_NONEXISTENT_VAR_123456789";
82 let result = get_env_var(var_name);
83 assert!(result.is_err());
84 let error_msg = result.unwrap_err().to_string();
85 assert!(error_msg.contains(var_name));
86 assert!(error_msg.contains("must be set"));
87 }
88
89 #[rstest]
90 fn test_get_or_env_var_with_some_value() {
91 let provided_value = Some("provided_value".to_string());
92 let result = get_or_env_var(provided_value, "PATH");
93 assert!(result.is_ok());
94 assert_eq!(result.unwrap(), "provided_value");
95 }
96
97 #[rstest]
98 fn test_get_or_env_var_with_none_and_env_var_set() {
99 // Test with a commonly available environment variable
100 if let Ok(path) = std::env::var("PATH") {
101 let result = get_or_env_var(None, "PATH");
102 assert!(result.is_ok());
103 assert_eq!(result.unwrap(), path);
104 }
105 }
106
107 #[rstest]
108 fn test_get_or_env_var_with_none_and_env_var_not_set() {
109 let result = get_or_env_var(None, "NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_67890");
110 assert!(result.is_err());
111 assert!(result.unwrap_err().to_string().contains(
112 "environment variable 'NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_67890' must be set"
113 ));
114 }
115
116 #[rstest]
117 fn test_get_or_env_var_empty_string_value() {
118 // Empty string is still a valid value that should be returned
119 let provided_value = Some(String::new());
120 let result = get_or_env_var(provided_value, "PATH");
121 assert!(result.is_ok());
122 assert_eq!(result.unwrap(), "");
123 }
124
125 #[rstest]
126 fn test_get_or_env_var_priority() {
127 // When both value and env var are available, value takes precedence
128 // Using PATH as it should be available in most environments
129 if std::env::var("PATH").is_ok() {
130 let provided = Some("custom_value_takes_priority".to_string());
131 let result = get_or_env_var(provided, "PATH");
132 assert!(result.is_ok());
133 assert_eq!(result.unwrap(), "custom_value_takes_priority");
134 }
135 }
136}