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
//!
//! ```rust
//! use env_cfg::EnvConfig;
//! use std::time::Duration;
//!
//! #[derive(Debug, EnvConfig)]
//! struct AppConfig {
//! // By default, we search for ENV variables using STRUCT_NAME_FIELD_NAME in SCREAMING_SNAKE_CASE.
//! // `database_url` will be loaded from `APP_CONFIG_DATABASE_URL`
//! url: String, // -> APP_CONFIG_URL (required)
//!
//! // if a default value is provided, that value is used as a fallback
//! #[env_cfg(default = "8080")]
//! port: u16, // -> APP_CONFIG_PORT (with default)
//!
//! timeout: Option<u64>, // -> APP_CONFIG_TIMEOUT (optional)
//!
//! // custom ENV variable keys can be provided with `env = "CUSTOM_NAME"`
//! #[env_cfg(env = "DEBUG_MODE")]
//! debug: bool, // -> DEBUG_MODE (custom name)
//!
//! // fields marked with `skip` will always use the `Default` impl for the type
//! #[env_cfg(skip)]
//! internal_state: Option<String>, // Skipped - uses Default::default()
//!
//! // fields marked with `parse_with = "my_fn_name"` will use the provided function to parse the env variable.
//! // These functions must have the signature `fn(String) -> T`
//! #[env_cfg(parse_with = "parse_point")]
//! position: Point, // -> APP_CONFIG_POSITION (with custom parser)
//!
//! // fields marked with `parse_with = "my_fn_name"` can also be optional
//! #[env_cfg(parse_with = "parse_timeout_with_default")]
//! timeout_duration: Option<Duration>, // -> APP_CONFIG_TIMEOUT_DURATION (with custom parser that provides defaults)
//!
//! #[env_cfg(nested)]
//! db_config: DatabaseConfig,
//!
//! #[env_cfg(nested)]
//! redis_config: RedisConfig,
//! }
//!
//! #[derive(Debug, EnvConfig)]
//! // Use no_prefix to disable the struct name prefix
//! #[env_cfg(no_prefix)]
//! struct DatabaseConfig {
//! postgres_url: String, // -> POSTGRES_URL
//! #[env_cfg(env = "DB_NAME", default = "mydb")]
//! database: String, // -> DB_NAME (with default)
//! }
//!
//! #[derive(Debug, EnvConfig)]
//! // Use custom prefix instead of struct name
//! #[env_cfg(prefix = "REDIS")]
//! struct RedisConfig {
//! url: String, // -> REDIS_URL
//! #[env_cfg(default = "5")]
//! cache_timeout: u64, // -> REDIS_CACHE_TIMEOUT (with default)
//! }
//!
//! #[derive(Debug)]
//! struct Point {
//! x: f64,
//! y: f64,
//! }
//!
//! fn parse_point(s: String) -> Point {
//! let (x, y) = s.split_once(',').expect("Invalid format");
//! Point {
//! x: x.trim().parse().expect("Invalid x coordinate"),
//! y: y.trim().parse().expect("Invalid y coordinate"),
//! }
//! }
//!
//! fn parse_timeout_with_default(s: String) -> Duration {
//! Duration::from_secs(s.parse::<u64>().unwrap_or(100))
//! }
//!
//! fn main() -> Result<(), env_cfg::EnvConfigError> {
//! // Set some environment variables for demonstration
//! //
//! // # Safety
//! // This example cannot run in parallel with other programs that set/remove ENV variables
//! unsafe {
//! std::env::set_var("APP_CONFIG_URL", "0.0.0.0:8080");
//! std::env::set_var("APP_CONFIG_TIMEOUT", "42");
//! std::env::set_var("DEBUG_MODE", "true");
//! std::env::set_var("APP_CONFIG_POSITION", "42.43, 893.2123");
//! std::env::set_var("APP_CONFIG_TIMEOUT_DURATION", "243");
//! std::env::set_var("POSTGRES_URL", "postgres://postgres:postgres@0.0.0.0:5432");
//! std::env::set_var("REDIS_URL", "redis://localhost:6379");
//! }
//! let config = AppConfig::from_env()?;
//! println!("AppConfig: {config:#?}");
//!
//! Ok(())
//! }
//! ```
use FromStr;
// Re-export the derive macro
pub use EnvConfig;
// Re-export tracing for use by the trace_config macro
pub use tracing;
/// Trait for loading configuration from environment variables.
///
/// This trait provides an interface for loading configuration from environment variables.
///
/// # Derive Macro Example
///
/// ```rust
/// use env_cfg::*;
///
/// #[derive(Debug, EnvConfig)]
/// struct AppConfig {
/// database_url: String, // -> APP_CONFIG_DATABASE_URL (required)
/// timeout: Option<u64>, // -> APP_CONFIG_TIMEOUT (optional)
/// #[env_cfg(env = "DEBUG_MODE")]
/// debug: bool, // -> DEBUG_MODE (custom name)
/// #[env_cfg(skip)]
/// internal_state: String, // Skipped - uses Default::default()
/// }
///
/// // Use no_prefix to disable the struct name prefix
/// #[derive(Debug, EnvConfig)]
/// #[env_cfg(no_prefix)]
/// struct SimpleConfig {
/// database_url: String, // -> DATABASE_URL (no prefix)
/// }
///
/// // Use custom prefix instead of struct name
/// #[derive(Debug, EnvConfig)]
/// #[env_cfg(prefix = "APP")]
/// struct CustomConfig {
/// database_url: String, // -> APP_DATABASE_URL (custom prefix)
/// }
/// ```
///
/// # Derive Macro Attributes
///
/// **Struct-level attributes:**
/// - **`#[env_cfg(no_prefix)]`**: Don't use struct name as prefix for field names
/// - **`#[env_cfg(prefix = "PREFIX")]`**: Use custom prefix instead of struct name
///
/// **Field-level attributes:**
/// - **No attribute**: Field name is prefixed with struct name and converted to UPPER_SNAKE_CASE
/// - **`#[env_cfg(env = "VAR_NAME")]`**: Use custom environment variable name
/// - **`#[env_cfg(default = "value")]`**: Provide default value if env var not set
/// - **`#[env_cfg(skip)]`**: Skip this field (must implement `Default`)
/// - **`#[env_cfg(parse_with = "function_name")]`**: Use custom parser function (takes `String`, returns `T`)
/// - **`#[env_cfg(nested)]`**: Treat field as nested EnvConfig struct (calls `T::from_env()`)
/// Error type for environment configuration loading.
/// Convert a `std::env::VarError` to an `EnvConfigError`.
// Helper functions for implementing the trait
/// Load a required environment variable and parse it to the target type.
/// Fails if the variable is not set or cannot be parsed.
/// Load an optional environment variable and parse it to the target type.
/// Returns `None` if the variable is not set.
/// Load an environment variable with a string default that gets parsed if env var not present.
///
/// This is used by the derive macro for `#[env_cfg(default = "value")]` attributes.
/// Load a required environment variable and parse it using a custom parser function.
/// The parser function should take a String and return the target type T.
/// Any panics or errors from the parser function will bubble up naturally.
/// Load an optional environment variable and parse it using a custom parser function.
/// Returns None if the variable is not set.
/// The parser function should take a String and return the target type T.
/// Any panics or errors from the parser function will bubble up naturally.
/// Log the loaded configuration using tracing.
///
/// This macro is called by the generated `from_env()` implementation.
/// When the `trace` feature is enabled, it emits a `tracing::trace!` event.
/// When the feature is disabled, this is a no-op.
///
/// Using a macro avoids requiring `Debug` on the config type when tracing is disabled.
/// Log the loaded configuration using tracing.
///
/// This macro is called by the generated `from_env()` implementation.
/// When the `trace` feature is enabled, it emits a `tracing::trace!` event.
/// When the feature is disabled, this is a no-op.
///
/// Using a macro avoids requiring `Debug` on the config type when tracing is disabled.