trail-config 0.3.0

Simple library to help with reading (and formatting) values from config files
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
# Trail Config


Simple [Rust](https://www.rust-lang.org/) library to help with reading (and formatting) values from config files.
Supports YAML format (uses [serde_yaml_bw](https://github.com/bourumir-wyngs/serde-yaml-bw) library).

## Features


- 📖 Simple path-based config value access
- 🔧 Customizable path separators (`/`, `::`, etc.)
- 🌍 Environment-specific config files
- 📝 String formatting and interpolation
- ✅ Comprehensive error handling with custom `ConfigError` type
- 📋 Type conversion for strings, numbers, booleans, and sequences
- 🔐 Escape sequence support for keys containing separators
- 🔄 Hot reload support for detecting configuration changes at runtime

## Quick Start


```rust
use trail_config::Config;

// Load config.yaml file
let config = Config::default();

// Get values with lenient API (returns empty/None on missing)
let port = config.str("app/port");          // -> "8080"
let timeout = config.get_int("app/timeout"); // -> Some(30)

// Or use strict API for explicit error handling
match config.str_strict("database/host") {
    Ok(host) => println!("Connecting to {}", host),
    Err(e) => eprintln!("Config error: {}", e),
}
```

## Loading Configuration


Trail Config provides different loading strategies for different use cases:

### Production Code (Strict)


Use `Config::load_required()` when the configuration file **must** exist:

```rust
use trail_config::Config;

let config = Config::load_required("config.yaml", "/", None)?;
// Will error if file is missing, invalid YAML, or permission denied
```

### Testing/Optional Configs (Lenient)


Use `Config::default()` when missing config is acceptable:

```rust
let config = Config::default(); // Never panics, gracefully handles missing config.yaml
```

### Custom Loading


```rust
// With custom separator
let config = Config::new("config.yaml", "::", None)?;

// With environment substitution
let config = Config::new("config.{env}.yaml", "/", Some("dev"))?; // Loads config.dev.yaml

// From YAML string
let config = Config::load_yaml("app:\n  port: 8080", "/")?;
```

## API Overview


Trail Config organizes methods into two API styles:

| Goal | Method Style | Returns |
|------|--------------|---------|
| Lenient access (handles missing gracefully) | `get()`, `str()`, `list()`, etc. | `Option<T>` or empty defaults |
| Strict access (explicit error handling) | `get_strict()`, `str_strict()`, etc. | `Result<T, ConfigError>` |

Both styles share the same path syntax and navigate nested YAML using separators (default: `/`).

## Main Methods (Lenient API)


Lenient methods return `None` or empty values for missing paths or type mismatches.

### Reading Values


- `get(path)``Option<Value>` - Get raw `serde_yaml::Value`
- `str(path)``String` - Get string representation (empty if missing)
- `list(path)``Vec<String>` - Get sequence as vector (empty if missing)
- `contains(path)``bool` - Check if path exists

### Type Conversion


- `get_int(path)``Option<i64>` - Get integer value
- `get_float(path)``Option<f64>` - Get floating-point value
- `get_bool(path)``Option<bool>` - Get boolean value

### Formatting


- `fmt(format, path)``String` - Format multiple values (empty on any error)

### Configuration Metadata


- `get_filename()``&str` - Get loaded config filename
- `environment()``Option<&str>` - Get environment name (if used)

### Hot Reload


- `reload()``Result<(), ConfigError>` - Reload from current file
- `reload_from(filename)``Result<(), ConfigError>` - Load from different file

## Strict Methods (Error Handling API)


Strict methods return `Result<T, ConfigError>` for explicit error handling.

- `get_strict(path)` - Get value, fails with `PathNotFound` if missing
- `str_strict(path)` - Get string, fails with `PathNotFound` if missing
- `list_strict(path)` - Get sequence, fails with `PathNotFound` if missing
- `fmt_strict(format, path)` - Format values, fails with `PathNotFound` or `FormatError`
- `get_int_strict(path)` - Get integer, fails with `PathNotFound` or `FormatError` on type mismatch
- `get_float_strict(path)` - Get float, fails with `PathNotFound` or `FormatError` on type mismatch
- `get_bool_strict(path)` - Get boolean, fails with `PathNotFound` or `FormatError` on type mismatch

## Type Conversion


Convert config values to typed Rust values safely:

```rust
let config = Config::default();

// Lenient - returns None on missing or type mismatch
let port = config.get_int("app/port");
let timeout = config.get_float("app/timeout");
let debug = config.get_bool("app/debug");

if let Some(port) = port {
    println!("Listening on port {}", port);
}

// Strict - returns error details
match config.get_int_strict("app/port") {
    Ok(port) => println!("Port: {}", port),
    Err(e) => eprintln!("Failed to read port: {}", e),
}
```

Example config (YAML):
```yaml
app:
  port: 8080
  timeout: 30.5
  debug: true
```

## Error Handling


Trail Config uses a custom `ConfigError` enum for precise error handling:

### Error Types


```rust
use trail_config::ConfigError;

// Four error variants:
// - IoError(io::Error)       - File I/O errors (missing file, permission denied, etc.)
// - YamlError(String)        - YAML parsing errors
// - PathNotFound(String)     - Configuration path not found in document
// - FormatError(String)      - String formatting or configuration errors
```

### Basic Error Handling


```rust
use trail_config::{Config, ConfigError};

match Config::load_required("config.yaml", "/", None) {
    Ok(config) => {
        let host = config.str("database/host");
        println!("Connecting to {}", host);
    }
    Err(ConfigError::IoError(e)) => {
        eprintln!("Config file error: {}", e);
    }
    Err(ConfigError::YamlError(msg)) => {
        eprintln!("Invalid YAML: {}", msg);
    }
    Err(e) => eprintln!("Config error: {}", e),
}
```

### Strict Method Error Handling


```rust
use trail_config::{Config, ConfigError};

let config = Config::default();

match config.str_strict("database/host") {
    Ok(host) => println!("Connecting to {}", host),
    Err(ConfigError::PathNotFound(path)) => {
        eprintln!("Missing required config: {}", path);
    }
    Err(e) => eprintln!("Config error: {}", e),
}

// Type conversion with error details
match config.get_int_strict("app/port") {
    Ok(port) => println!("Port: {}", port),
    Err(ConfigError::FormatError(msg)) => {
        eprintln!("Port value has wrong type: {}", msg);
    }
    Err(ConfigError::PathNotFound(path)) => {
        eprintln!("Port config not found: {}", path);
    }
    Err(e) => eprintln!("Unexpected error: {}", e),
}
```

## Hot Reload


Detect and apply configuration changes at runtime without restarting:

```rust
let mut config = Config::load_required("config.yaml", "/", None)?;

// Reload from the same file
config.reload()?; // Updates content from disk

// Or switch to a different config file
config.reload_from("other_config.yaml")?;
```

### Server Loop Example


```rust
use trail_config::Config;
use std::thread;
use std::time::Duration;

fn main() {
    let mut config = Config::load_required("config.yaml", "/", None)
        .expect("Failed to load config");
    
    loop {
        // Check for config updates every 5 seconds
        if let Ok(_) = config.reload() {
            println!("✓ Configuration reloaded");
            
            // Apply updated settings
            let timeout = config.get_int("app/timeout").unwrap_or(30);
            let debug = config.get_bool("app/debug").unwrap_or(false);
            
            println!("Timeout: {} seconds, Debug: {}", timeout, debug);
        }
        
        // Main application logic here
        thread::sleep(Duration::from_secs(5));
    }
}
```

## Escape Sequences


Keys containing the path separator can be accessed using escape sequences.

### Syntax


- `\/` - Include literal separator in the key
- `\\` - Include literal backslash in the key
- Works with any separator: `/`, `::`, `->`, etc.

### Example


Given this YAML with special characters in keys:

```yaml
database:
  "host/port": localhost:5432      # Key contains /
  "user\name": admin\user          # Key contains \
```

Access using escape sequences:

```rust
let config = Config::load_yaml(yaml, "/").unwrap();

// Access key containing separator (/)
let value = config.str("database/host\\/port"); // -> "localhost:5432"

// Access key containing backslash (\)
let value = config.str("database/user\\\\name"); // -> "admin\user"
```

With custom separator:

```rust
let config = Config::load_yaml(yaml, "::").unwrap();

// Path: a::b\::c::d navigates to keys ["a", "b::c", "d"]
let value = config.str("a::b\\::c::d");
```

## Input Validation


Trail Config validates inputs automatically and returns `FormatError` for invalid configurations:

| Input | Constraint | Error |
|-------|-----------|-------|
| Path Separator | Cannot be empty | Returns `FormatError` |
| File Paths | Empty filename treated as no file | Returns `IoError` |
| Paths | Empty paths safely handled | Returns `None` or empty |
| Separators (leading/trailing) | Handled gracefully | No error |
| Filename Templates | Must be valid format strings | Returns `FormatError` |

Examples:

```rust
// Empty separator - error
let result = Config::new("config.yaml", "", None);
assert!(result.is_err()); // FormatError

// Missing file with load_required - error
let result = Config::load_required("missing.yaml", "/", None);
assert!(result.is_err()); // IoError

// Missing file with default - ok, empty config
let config = Config::default();
assert!(config.str("any/path") == ""); // Graceful fallback
```

## Real-World Examples


### Web Server Configuration


```rust
use trail_config::Config;

let config = Config::load_required("server.yaml", "/", None)?;

let host = config.str("server/host");
let port = config.get_int_strict("server/port")?;
let ssl = config.get_bool("server/ssl").unwrap_or(false);
let workers = config.get_int("server/workers").unwrap_or(4);

println!("Starting server on {}:{} (workers: {})", host, port, workers);
```

### Environment-Specific Configuration


```rust
use trail_config::Config;
use std::env;

let env = env::var("APP_ENV").unwrap_or_else(|_| "development".to_string());
let config = Config::load_required(
    "config.{env}.yaml",
    "/",
    Some(&env)
)?;

let db_url = config.str_strict("database/url")?;
let log_level = config.str("logging/level");

println!("Using {} environment", env);
```

### Database Connection Pooling


```rust
use trail_config::Config;

let config = Config::default();

let db_config = DatabaseConfig {
    host: config.str("db/host"),
    port: config.get_int("db/port").unwrap_or(5432) as u16,
    username: config.str("db/username"),
    password: config.str("db/password"),
    pool_size: config.get_int("db/pool_size").unwrap_or(10) as usize,
    timeout: config.get_float("db/timeout").unwrap_or(30.0),
};

let pool = create_pool(db_config)?;
```

Sample YAML:
```yaml
db:
  host: localhost
  port: 5432
  username: admin
  password: secret
  pool_size: 20
  timeout: 60.0
```

### Feature Flags and Feature Detection


```rust
use trail_config::Config;

let config = Config::default();

if config.get_bool("features/analytics").unwrap_or(false) {
    init_analytics();
}

if config.get_bool("features/profiling").unwrap_or(false) {
    enable_profiling();
}

let beta_features = config.list("features/beta");
for feature in beta_features {
    println!("Beta feature enabled: {}", feature);
}
```

## Sample Configuration File


```yaml
app:
  name: MyApp
  port: 8080
  timeout: 30.5
  debug: false

database:
  host: localhost
  port: 5432
  name: myapp_db
  username: admin
  password: secret
  pool_size: 10

server:
  bind: 127.0.0.1
  workers: 4
  log_level: info

features:
  analytics: true
  profiling: false
  beta:
    - new_ui
    - advanced_search
```

## License


This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details