spicex 0.1.0

A complete configuration solution for Rust applications, inspired by Viper
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
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
528
529
530
531
532
533
534
535
536
537
# SpiceX


A complete configuration solution for Rust applications, inspired by [viper](https://github.com/spf13/viper).

SpiceX is designed to work within an application and can handle all types of configuration needs and formats. It provides a unified interface for reading configuration from multiple sources with a clear precedence hierarchy.

## Features


- **Multiple Configuration Sources** - Files, environment variables, command line flags, defaults
-**Multiple File Formats** - JSON, YAML, TOML, INI support
-**Precedence Hierarchy** - Clear ordering of configuration sources
-**Nested Configuration** - Dot notation access to nested values
-**Type Safety** - Strong typing with automatic type conversion
-**Struct Deserialization** - Deserialize configuration into Rust structs
-**File Watching** - Automatic reloading when configuration files change
-**Environment Variables** - Automatic mapping with prefix support
-**Command Line Flags** - Integration with clap for CLI arguments
-**Default Values** - Fallback values for missing configuration
-**Configuration Writing** - Save configuration back to files

## Quick Start


Add this to your `Cargo.toml`:

```toml
[dependencies]
spicex = "0.1.0"

# Optional: Enable CLI support

[dependencies.spicex]
version = "0.1.0"
features = ["cli"]
```

### Basic Usage


```rust
use spicex::{Spice, ConfigValue};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut spice = Spice::new();

    // Set default values
    spice.set_default("database.host", ConfigValue::from("localhost"))?;
    spice.set_default("database.port", ConfigValue::from(5432i64))?;
    spice.set_default("debug", ConfigValue::from(false))?;

    // Configure file discovery
    spice.set_config_name("config");
    spice.add_config_path(".");
    spice.add_config_path("./configs");
    spice.add_config_path("/etc/myapp");

    // Try to read configuration file
    if let Err(e) = spice.read_in_config() {
        println!("No config file found, using defaults: {}", e);
    }

    // Set up environment variable support
    spice.set_env_prefix("MYAPP");
    spice.set_automatic_env(true);

    // Access configuration values
    let host = spice.get_string("database.host")?.unwrap_or_default();
    let port = spice.get_i64("database.port")?.unwrap_or(5432);
    let debug = spice.get_bool("debug")?.unwrap_or(false);

    println!("Database: {}:{}", host, port);
    println!("Debug mode: {}", debug);

    Ok(())
}
```

### With Struct Deserialization


```rust
use spicex::{Spice, ConfigValue};
use serde::Deserialize;

#[derive(Deserialize, Debug)]

struct DatabaseConfig {
    host: String,
    port: u16,
    #[serde(default)]
    ssl: bool,
}

#[derive(Deserialize, Debug)]

struct AppConfig {
    database: DatabaseConfig,
    debug: bool,
    #[serde(default)]
    log_level: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut spice = Spice::new();

    // Set defaults
    spice.set_default("database.host", ConfigValue::from("localhost"))?;
    spice.set_default("database.port", ConfigValue::from(5432i64))?;
    spice.set_default("debug", ConfigValue::from(false))?;
    spice.set_default("log_level", ConfigValue::from("info"))?;

    // Load configuration
    spice.set_config_name("config");
    spice.add_config_path(".");
    let _ = spice.read_in_config(); // Ignore errors, use defaults

    // Deserialize into struct
    let config: AppConfig = spice.unmarshal()?;
    println!("Configuration: {:#?}", config);

    Ok(())
}
```

## Configuration Precedence


Spice uses the following precedence order (highest to lowest):

1. **Explicit calls** - Values set via `spice.set()`
2. **Command line flags** - CLI arguments (requires `cli` feature)
3. **Environment variables** - System environment variables
4. **Configuration files** - JSON, YAML, TOML, INI files
5. **Key/value stores** - Remote configuration (future feature)
6. **Default values** - Fallback values set via `spice.set_default()`

## Configuration File Formats


### JSON Example (`config.json`)


```json
{
  "database": {
    "host": "localhost",
    "port": 5432,
    "ssl": true,
    "credentials": {
      "username": "admin",
      "password": "secret"
    }
  },
  "server": {
    "port": 8080,
    "host": "0.0.0.0"
  },
  "features": ["auth", "logging", "metrics"],
  "debug": false
}
```

### YAML Example (`config.yaml`)


```yaml
database:
  host: localhost
  port: 5432
  ssl: true
  credentials:
    username: admin
    password: secret

server:
  port: 8080
  host: 0.0.0.0

features:
  - auth
  - logging
  - metrics

debug: false
```

### TOML Example (`config.toml`)


```toml
debug = false
features = ["auth", "logging", "metrics"]

[database]
host = "localhost"
port = 5432
ssl = true

[database.credentials]
username = "admin"
password = "secret"

[server]
port = 8080
host = "0.0.0.0"
```

### INI Example (`config.ini`)


```ini
debug = false

[database]
host = localhost
port = 5432
ssl = true

[server]
port = 8080
host = 0.0.0.0
```

## Environment Variables


Environment variables are automatically mapped to configuration keys:

```bash
# Set environment variables

export MYAPP_DATABASE_HOST=production-db
export MYAPP_DATABASE_PORT=5432
export MYAPP_DEBUG=true

# These become available as:

# database.host = "production-db"

# database.port = 5432

# debug = true

```

```rust
use spicex::Spice;

let mut spice = Spice::new();
spice.set_env_prefix("MYAPP");
spice.set_automatic_env(true);

// Access environment variables
let host = spice.get_string("database.host")?;
let debug = spice.get_bool("debug")?;
```

## Command Line Flags


With the `cli` feature enabled, you can integrate with clap:

```rust
use spicex::Spice;
use clap::{Arg, Command};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Command::new("myapp")
        .arg(Arg::new("host")
            .long("host")
            .value_name("HOST")
            .help("Database host"))
        .arg(Arg::new("port")
            .long("port")
            .value_name("PORT")
            .help("Database port"))
        .arg(Arg::new("debug")
            .long("debug")
            .action(clap::ArgAction::SetTrue)
            .help("Enable debug mode"));

    let matches = app.get_matches();

    let mut spice = Spice::new();
    spice.bind_flags(matches);

    // CLI flags now override other configuration sources
    let host = spice.get_string("host")?;
    let debug = spice.get_bool("debug")?;

    Ok(())
}
```

## File Watching


Enable automatic reloading when configuration files change:

```rust
use spicex::Spice;
use std::sync::{Arc, Mutex};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut spice = Spice::new();
    spice.set_config_name("config");
    spice.read_in_config()?;

    // Enable file watching
    spice.watch_config()?;

    // Register callback for configuration changes
    let reload_count = Arc::new(Mutex::new(0));
    let count_clone = Arc::clone(&reload_count);

    spice.on_config_change(move || {
        let mut count = count_clone.lock().unwrap();
        *count += 1;
        println!("Configuration reloaded {} times", *count);
    })?;

    // Your application continues running...
    // Configuration will automatically reload when files change

    Ok(())
}
```

## Writing Configuration


Save current configuration to files:

```rust
use spicex::{Spice, ConfigValue};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut spice = Spice::new();

    // Set some configuration
    spice.set("app.name", ConfigValue::from("My Application"))?;
    spice.set("app.version", ConfigValue::from("1.0.0"))?;
    spice.set("database.host", ConfigValue::from("localhost"))?;

    // Write to different formats
    spice.write_config("output.json")?;        // JSON format
    spice.write_config("output.yaml")?;        // YAML format
    spice.write_config_as("output.txt", "toml")?; // TOML in .txt file

    // Safe write (won't overwrite existing files)
    spice.safe_write_config("backup.json")?;

    Ok(())
}
```

## Advanced Usage


### Sub-configurations


Work with configuration subsections:

```rust
use spicex::{Spice, ConfigValue};
use std::collections::HashMap;

let mut spice = Spice::new();

// Set up nested configuration
let mut db_config = HashMap::new();
db_config.insert("host".to_string(), ConfigValue::from("localhost"));
db_config.insert("port".to_string(), ConfigValue::from(5432i64));
spice.set("database", ConfigValue::Object(db_config))?;

// Create sub-configuration for database settings
if let Some(db_viper) = spice.sub("database")? {
    // Access "host" directly instead of "database.host"
    let host = db_viper.get_string("host")?;
    let port = db_viper.get_i64("port")?;
}
```

### Configuration Validation


Validate configuration during deserialization:

```rust
use spicex::{Spice, ConfigValue, ConfigError};
use serde::Deserialize;

#[derive(Deserialize, Debug)]

struct ServerConfig {
    host: String,
    port: u16,
}

impl ServerConfig {
    fn validate(&self) -> Result<(), String> {
        if self.port < 1024 {
            return Err("Port must be >= 1024".to_string());
        }
        if self.host.is_empty() {
            return Err("Host cannot be empty".to_string());
        }
        Ok(())
    }
}

let mut spice = Spice::new();
spice.set("host", ConfigValue::from("localhost"))?;
spice.set("port", ConfigValue::from(8080i64))?;

let config: ServerConfig = spice.unmarshal_with_validation(|config: &ServerConfig| {
    config.validate().map_err(|e| ConfigError::invalid_value(e))
})?;
```

## Error Handling


Spice provides detailed error information:

```rust
use spicex::{Spice, ConfigError};

let spice = Spice::new();

match spice.get_string("nonexistent.key") {
    Ok(Some(value)) => println!("Value: {}", value),
    Ok(None) => println!("Key not found"),
    Err(ConfigError::KeyNotFound { key }) => {
        println!("Key '{}' not found", key);
    }
    Err(ConfigError::TypeConversion { from, to }) => {
        println!("Cannot convert {} to {}", from, to);
    }
    Err(ConfigError::Parse { source_name, message }) => {
        println!("Parse error in {}: {}", source_name, message);
    }
    Err(e) => println!("Other error: {}", e),
}
```

## Migration from Other Libraries


### From `config` crate


```rust
// Old way (config crate)
use config::{Config, ConfigError, File};

let settings = Config::builder()
    .add_source(File::with_name("config"))
    .build()?;
let host: String = settings.get("database.host")?;

// New way (spice)
use spicex::Spice;

let mut spice = Spice::new();
spice.set_config_name("config");
spice.read_in_config()?;
let host = spice.get_string("database.host")?.unwrap_or_default();
```

### From Environment Variables Only


```rust
// Old way (std::env)
use std::env;

let host = env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string());
let port: u16 = env::var("DATABASE_PORT")
    .unwrap_or_else(|_| "5432".to_string())
    .parse()
    .unwrap_or(5432);

// New way (spice)
use spicex::{Spice, ConfigValue};

let mut spice = Spice::new();
spice.set_default("database.host", ConfigValue::from("localhost"))?;
spice.set_default("database.port", ConfigValue::from(5432i64))?;
spice.set_env_prefix("DATABASE");
spice.set_automatic_env(true);

let host = spice.get_string("host")?.unwrap_or_default();
let port = spice.get_i64("port")?.unwrap_or(5432) as u16;
```

## Examples


The `examples/` directory contains comprehensive examples:

- [`basic_usage.rs`]examples/basic_usage.rs - Basic configuration loading and access
- [`struct_deserialization.rs`]examples/struct_deserialization.rs - Deserializing into structs
- [`env_layer_usage.rs`]examples/env_layer_usage.rs - Environment variable configuration
- [`file_watching.rs`]examples/file_watching.rs - Watching for configuration changes
- [`cli_flag_usage.rs`]examples/cli_flag_usage.rs - Command line flag integration
- [`nested_access_usage.rs`]examples/nested_access_usage.rs - Working with nested configuration
- [`default_values_usage.rs`]examples/default_values_usage.rs - Setting and using defaults
- [`file_discovery_usage.rs`]examples/file_discovery_usage.rs - Automatic file discovery
- [`web_server_config.rs`]examples/web_server_config.rs - Real-world web server configuration
- [`microservice_config.rs`]examples/microservice_config.rs - Microservice configuration patterns

## Performance


Spice-rust is designed for performance:

- **Lazy Loading** - Configuration sources are loaded on-demand
- **Caching** - Values are cached after first access
- **Zero-Copy** - Minimal allocations through strategic use of references
- **Efficient Parsing** - Uses optimized parsers for each format

Run benchmarks with:

```bash
cargo run --example performance_benchmarks --release
```

## Contributing


Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup


```bash
git clone https://github.com/myself659/spicex.git
cd spicex
cargo build
cargo test
```

### Running Examples


```bash
# Basic usage

cargo run --example basic_usage

# With CLI support

cargo run --example cli_flag_usage --features cli -- --host localhost --port 8080

# File watching (requires a config file)

echo '{"debug": true}' > config.json
cargo run --example file_watching
```

## License



- MIT license ([LICENSE-MIT]LICENSE-MIT)


at your option.

## Acknowledgments


- Inspired by [viper]https://github.com/spf13/viper for Go
- Built with the excellent Rust ecosystem including serde, clap, notify, and more