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
//! Fluent builder methods for SuperConfig
//!
//! This module provides the fluent builder methods that were previously
//! available as extension traits. Now they're native SuperConfig methods.
use crate::SuperConfig;
use crate::verbosity::{DebugCollector, VerbosityLevel};
use figment::providers::Serialized;
impl SuperConfig {
/// Set the verbosity level for configuration debugging
///
/// Controls the amount of debug information displayed during configuration loading.
/// Higher levels include all information from lower levels.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::{SuperConfig, VerbosityLevel};
///
/// let config = SuperConfig::new()
/// .with_verbosity(VerbosityLevel::Debug) // -vv level debugging
/// .with_file("config.toml");
/// ```
pub fn with_verbosity(mut self, level: VerbosityLevel) -> Self {
self.verbosity = level;
self.debug(
VerbosityLevel::Info,
"verbosity",
&format!("Set verbosity level to: {level}"),
);
self
}
/// Enable basic configuration loading progress (equivalent to -v)
///
/// Shows which providers are being loaded and final success/failure.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_info_verbosity() // -v level
/// .with_file("config.toml");
/// ```
pub fn with_info_verbosity(self) -> Self {
self.with_verbosity(VerbosityLevel::Info)
}
/// Enable detailed step-by-step information (equivalent to -vv)
///
/// Shows file discovery, individual provider results, and merge operations.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_debug_verbosity() // -vv level
/// .with_hierarchical_config("myapp");
/// ```
pub fn with_debug_verbosity(self) -> Self {
self.with_verbosity(VerbosityLevel::Debug)
}
/// Enable full introspection with configuration values (equivalent to -vvv)
///
/// Shows actual configuration values at each step and final merged result.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_trace_verbosity() // -vvv level
/// .with_env("APP_");
/// ```
pub fn with_trace_verbosity(self) -> Self {
self.with_verbosity(VerbosityLevel::Trace)
}
/// Add a configuration file with smart format detection
///
/// Uses the Universal provider for automatic format detection and caching.
/// Supports .toml, .yaml/.yml, .json files with fallback chains.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_file("config") // Auto-detects config.toml, config.yaml, etc.
/// .with_file("app.json"); // Explicit JSON file
/// ```
pub fn with_file<P: AsRef<std::path::Path>>(self, path: P) -> Self {
let path_str = path.as_ref().to_string_lossy();
let step = self.next_step();
self.debug_step(
VerbosityLevel::Info,
"file",
step,
&format!("Loading configuration file: {path_str}"),
);
// Check if file exists for debug output
if path.as_ref().exists() {
self.debug_step_result(
VerbosityLevel::Debug,
"file",
step,
&format!("File found: {path_str}"),
true,
);
} else {
self.debug_step_result(
VerbosityLevel::Debug,
"file",
step,
&format!("File not found: {path_str}"),
false,
);
}
// Add trace-level content inspection
if self.verbosity >= VerbosityLevel::Trace && path.as_ref().exists() {
if let Ok(content) = std::fs::read_to_string(&path) {
let preview = if content.len() > 200 {
format!("{}... ({} chars total)", &content[..200], content.len())
} else {
content
};
self.debug(
VerbosityLevel::Trace,
"file",
&format!("File content preview: {preview}"),
);
}
}
self.merge(crate::providers::Universal::file(path))
}
/// Add environment variables with a prefix
///
/// Uses the Nested provider for JSON parsing and automatic nesting.
/// Supports complex structures like arrays and objects in environment variables.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_env("APP_") // APP_DATABASE_HOST, APP_FEATURES, etc.
/// .with_env("MYAPP_"); // Multiple prefixes supported
/// ```
pub fn with_env<S: AsRef<str>>(self, prefix: S) -> Self {
let prefix_str = prefix.as_ref();
let step = self.next_step();
self.debug_step(
VerbosityLevel::Info,
"env",
step,
&format!("Loading environment variables with prefix: {prefix_str}"),
);
// Collect matching environment variables for debug output
let env_vars: Vec<(String, String)> = std::env::vars()
.filter(|(key, _)| key.starts_with(prefix_str))
.collect();
if env_vars.is_empty() {
self.debug_step_result(
VerbosityLevel::Debug,
"env",
step,
&format!("No environment variables found with prefix: {prefix_str}"),
false,
);
} else {
self.debug_step_result(
VerbosityLevel::Debug,
"env",
step,
&format!(
"Found {} environment variables with prefix: {prefix_str}",
env_vars.len()
),
true,
);
// Show individual env vars at trace level
if self.verbosity >= VerbosityLevel::Trace {
for (key, value) in &env_vars {
// Mask sensitive values (anything with 'password', 'secret', 'token', 'key' in name)
let display_value = if key.to_lowercase().contains("password")
|| key.to_lowercase().contains("secret")
|| key.to_lowercase().contains("token")
|| key.to_lowercase().contains("key")
{
"***MASKED***".to_string()
} else {
value.clone()
};
self.debug(
VerbosityLevel::Trace,
"env",
&format!(" {key}={display_value}"),
);
}
}
}
self.merge(crate::providers::Nested::prefixed(prefix))
}
/// Add hierarchical configuration cascade
///
/// Uses the Wildcard provider for Git-like config inheritance:
/// system → user → project levels with automatic discovery.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_hierarchical_config("myapp"); // Loads system, user, project configs
/// ```
pub fn with_hierarchical_config<S: AsRef<str>>(self, base_name: S) -> Self {
let base_name_str = base_name.as_ref();
let step = self.next_step();
self.debug_step(
VerbosityLevel::Info,
"hierarchical",
step,
&format!("Loading hierarchical config for: {base_name_str}"),
);
// Show the discovery paths at debug level
if self.verbosity >= VerbosityLevel::Debug {
let potential_paths = vec![
format!("/etc/{base_name_str}/config.toml"),
format!("/etc/{base_name_str}.toml"),
dirs::config_dir()
.map(|p| {
p.join(base_name_str)
.join("config.toml")
.to_string_lossy()
.to_string()
})
.unwrap_or_else(|| "~/.config/<app>/config.toml".to_string()),
format!("./{base_name_str}.toml"),
format!("./config/{base_name_str}.toml"),
];
self.debug(
VerbosityLevel::Debug,
"hierarchical",
"Checking hierarchical config paths:",
);
for path in &potential_paths {
let exists = std::path::Path::new(path).exists();
self.debug_result(
VerbosityLevel::Debug,
"hierarchical",
&format!(" - {path}"),
exists,
);
}
}
self.merge(crate::providers::Wildcard::hierarchical(
"config",
base_name_str,
))
}
/// Add default configuration values from a serializable struct
///
/// Uses Figment's Serialized provider to set defaults that can be overridden
/// by other configuration sources.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize, Default)]
/// struct Config {
/// host: String,
/// port: u16,
/// }
///
/// let config = SuperConfig::new()
/// .with_defaults(Config::default())
/// .with_file("config.toml");
/// ```
pub fn with_defaults<T: serde::Serialize>(self, defaults: T) -> Self {
self.merge(Serialized::defaults(defaults))
}
/// Add default configuration from a raw string (TOML, JSON, or YAML)
///
/// Uses the Universal provider to parse the string content with automatic
/// format detection. Perfect for embedded configuration strings.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct CliArgs { host: Option<String> }
///
/// // Embedded default configuration (common pattern)
/// const DEFAULT_CONFIG: &str = r#"
/// host = "localhost"
/// port = 8080
///
/// [database]
/// url = "postgres://localhost"
/// timeout = 30
/// "#;
///
/// let cli_args = CliArgs { host: None };
/// let config = SuperConfig::new()
/// .with_defaults_string(DEFAULT_CONFIG) // Load TOML string as defaults
/// .with_hierarchical_config("myapp") // Apply hierarchical configs
/// .with_env("APP_") // Apply env variables
/// .with_cli_opt(Some(cli_args)); // Apply CLI overrides
/// ```
pub fn with_defaults_string(self, content: &str) -> Self {
let step = self.next_step();
self.debug_step(
VerbosityLevel::Info,
"defaults",
step,
"Loading embedded default configuration",
);
if self.verbosity >= VerbosityLevel::Debug {
let lines = content.lines().count();
let chars = content.len();
self.debug(
VerbosityLevel::Debug,
"defaults",
&format!("Embedded config: {lines} lines, {chars} characters"),
);
}
if self.verbosity >= VerbosityLevel::Trace {
let preview = if content.len() > 300 {
format!("{}... ({} chars total)", &content[..300], content.len())
} else {
content.to_string()
};
self.debug(
VerbosityLevel::Trace,
"defaults",
&format!("Default config content:\n{preview}"),
);
}
self.merge(crate::providers::Universal::string(content))
}
/// Add CLI option values with empty value filtering
///
/// Uses the Empty provider to filter out empty values while preserving
/// meaningful falsy values (false, 0, etc.).
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct CliArgs {
/// host: Option<String>,
/// port: Option<u16>,
/// }
///
/// let cli_args = CliArgs { host: Some("localhost".to_string()), port: None };
/// let config = SuperConfig::new()
/// .with_file("config.toml")
/// .with_cli_opt(Some(cli_args));
/// ```
pub fn with_cli_opt<T: serde::Serialize>(self, cli_opt: Option<T>) -> Self {
let step = self.next_step();
if let Some(cli_values) = cli_opt {
self.debug_step(
VerbosityLevel::Info,
"cli",
step,
"Loading CLI argument overrides",
);
// Try to serialize to JSON for debug inspection
if self.verbosity >= VerbosityLevel::Trace {
if let Ok(json_value) = serde_json::to_value(&cli_values) {
if let Ok(pretty_json) = serde_json::to_string_pretty(&json_value) {
self.debug(
VerbosityLevel::Trace,
"cli",
&format!("CLI overrides:\n{pretty_json}"),
);
}
}
}
self.merge(crate::providers::Empty::new(Serialized::defaults(
cli_values,
)))
} else {
self.debug_step_result(
VerbosityLevel::Debug,
"cli",
step,
"No CLI arguments provided",
false,
);
self
}
}
/// Add an optional configuration file with smart format detection
///
/// Uses the Universal provider for automatic format detection and caching.
/// Only adds the file if the path is Some, otherwise returns self unchanged.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
/// use std::path::PathBuf;
///
/// let optional_config: Option<PathBuf> = Some("config.toml".into());
/// let config = SuperConfig::new()
/// .with_file_opt(optional_config) // Only loads if Some
/// .with_env("APP_");
/// ```
pub fn with_file_opt<P: AsRef<std::path::Path>>(self, path: Option<P>) -> Self {
if let Some(file_path) = path {
self.with_file(file_path)
} else {
self
}
}
/// Add environment variables with a prefix and empty value filtering
///
/// Combines the Nested provider for JSON parsing and automatic nesting
/// with the Empty provider to filter out empty values.
///
/// # Examples
/// ```rust,no_run
/// use superconfig::SuperConfig;
///
/// let config = SuperConfig::new()
/// .with_env_ignore_empty("APP_"); // Filters empty env vars
/// ```
pub fn with_env_ignore_empty<S: AsRef<str>>(self, prefix: S) -> Self {
let prefix_str = prefix.as_ref();
let step = self.next_step();
self.debug_step(
VerbosityLevel::Info,
"env",
step,
&format!("Loading environment variables with prefix: {prefix_str} (ignore empty)"),
);
// Collect matching environment variables for debug output
let env_vars: Vec<(String, String)> = std::env::vars()
.filter(|(key, _)| key.starts_with(prefix_str))
.collect();
if env_vars.is_empty() {
self.debug_step_result(
VerbosityLevel::Debug,
"env",
step,
&format!("No environment variables found with prefix: {prefix_str}"),
false,
);
} else {
self.debug_step_result(
VerbosityLevel::Debug,
"env",
step,
&format!(
"Found {} environment variables with prefix: {prefix_str}",
env_vars.len()
),
true,
);
// Show individual env vars at trace level
if self.verbosity >= VerbosityLevel::Trace {
for (key, value) in &env_vars {
// Mask sensitive values (anything with 'password', 'secret', 'token', 'key' in name)
let display_value = if key.to_lowercase().contains("password")
|| key.to_lowercase().contains("secret")
|| key.to_lowercase().contains("token")
|| key.to_lowercase().contains("key")
{
"***MASKED***".to_string()
} else {
value.clone()
};
self.debug(
VerbosityLevel::Trace,
"env",
&format!(" {key}={display_value}"),
);
}
}
}
self.merge(crate::providers::Empty::new(
crate::providers::Nested::prefixed(prefix),
))
}
}