Skip to main content

config_lib/
lib.rs

1//! # config-lib - Multi-Format Configuration Library
2//!
3//! A high-performance configuration management library supporting multiple formats
4//! including CONF, NOML, TOML, and JSON with advanced features like format preservation,
5//! async operations, and schema validation.
6//!
7//! ## Quick Start
8//!
9//! ```rust
10//! use config_lib::Config;
11//!
12//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
13//! // Parse any supported format automatically
14//! let mut config = Config::from_string("port = 8080\nname = \"MyApp\"", None)?;
15//!
16//! // Access values with type safety
17//! let port: i64 = config
18//!     .get("port")
19//!     .ok_or_else(|| config_lib::Error::key_not_found("port"))?
20//!     .as_integer()?;
21//! let name: String = config
22//!     .get("name")
23//!     .ok_or_else(|| config_lib::Error::key_not_found("name"))?
24//!     .as_string()?
25//!     .to_owned();
26//!
27//! // Modify and save (preserves format and comments)
28//! config.set("port", 9000)?;
29//! # let _ = (port, name);
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! ## Supported Formats
35//!
36//! - **CONF** - Built-in parser for standard .conf files (default)
37//! - **NOML** - Advanced configuration with dynamic features (feature: `noml`)
38//! - **TOML** - Standard TOML format with format preservation (feature: `toml`)
39//! - **JSON** - JSON format with edit capabilities (feature: `jsonx`, strict
40//!   RFC 8259 on jsonx-lib with duplicate keys refused, Rust 1.85+; or `json`,
41//!   on serde_json)
42//!
43//! ## Features
44//!
45//! - **High Performance** - Zero-copy parsing where possible
46//! - **Format Preservation** - Maintains comments, whitespace, and formatting
47//! - **Async Native** - Full async/await support (feature: `async`)
48//! - **Schema Validation** - Type safety and validation (feature: `schema`)
49//! - **Cross Platform** - Linux, macOS, and Windows support
50//! - **Type Safety** - Rich type system with automatic conversions
51
52// REPS — Rust Efficiency & Performance Standards (project-wide lint discipline).
53// Shipping code MUST satisfy these denies; test code carries narrower
54// allows with `REPS-AUDIT:` justifications where ergonomics outweigh the strict rule.
55#![deny(missing_docs)]
56#![deny(unsafe_op_in_unsafe_fn)]
57#![deny(unused_must_use)]
58#![deny(clippy::unwrap_used)]
59#![deny(clippy::expect_used)]
60#![deny(clippy::todo)]
61#![deny(clippy::unimplemented)]
62#![deny(clippy::print_stdout)]
63#![deny(clippy::print_stderr)]
64#![deny(clippy::dbg_macro)]
65#![deny(clippy::undocumented_unsafe_blocks)]
66#![deny(clippy::missing_safety_doc)]
67#![warn(clippy::pedantic)]
68// Some lints allowed below are newer than the 1.75 toolchain; its clippy
69// would otherwise stop on their names under `-D warnings`
70#![allow(unknown_lints)]
71// REPS-AUDIT: `clippy::pedantic` is a curated lint group, not a hard rule.
72// The following lints are turned back to `allow` because they fire on
73// idioms this crate uses deliberately, or because they trade real
74// readability against pure stylistic preference. The denies above
75// (REPS safety / correctness rules) remain in force.
76//
77// Style / API-shape noise:
78#![allow(clippy::module_name_repetitions)]
79#![allow(clippy::must_use_candidate)]
80#![allow(clippy::return_self_not_must_use)]
81#![allow(clippy::similar_names)]
82#![allow(clippy::wildcard_imports)]
83#![allow(clippy::used_underscore_binding)]
84#![allow(clippy::no_effect_underscore_binding)]
85// Numeric casts at bounded parser/stats boundaries:
86#![allow(clippy::cast_precision_loss)]
87#![allow(clippy::cast_possible_wrap)]
88#![allow(clippy::cast_possible_truncation)]
89#![allow(clippy::cast_sign_loss)]
90// Documentation style preference:
91#![allow(clippy::doc_markdown)]
92#![allow(clippy::missing_errors_doc)]
93#![allow(clippy::missing_panics_doc)]
94// Refactor suggestions deferred to a dedicated cleanup phase
95// (see `.dev/ROADMAP.md` post-1.0 backlog):
96#![allow(clippy::unused_self)]
97#![allow(clippy::self_only_used_in_recursion)]
98#![allow(clippy::unnecessary_wraps)]
99#![allow(clippy::needless_pass_by_value)]
100#![allow(clippy::redundant_closure_for_method_calls)]
101#![allow(clippy::map_unwrap_or)]
102#![allow(clippy::manual_let_else)]
103#![allow(clippy::match_same_arms)]
104#![allow(clippy::single_match_else)]
105#![allow(clippy::inline_always)]
106#![allow(clippy::format_push_string)]
107#![allow(clippy::case_sensitive_file_extension_comparisons)]
108#![allow(clippy::single_char_pattern)]
109#![allow(clippy::unnecessary_literal_bound)]
110#![allow(clippy::if_not_else)]
111#![allow(clippy::struct_excessive_bools)]
112#![allow(clippy::too_many_lines)]
113#![allow(clippy::large_enum_variant)]
114#![allow(clippy::missing_const_for_fn)]
115#![allow(clippy::needless_for_each)]
116#![allow(clippy::implicit_hasher)]
117#![allow(clippy::ignored_unit_patterns)]
118// REPS-AUDIT: test modules use `.unwrap()` / `.expect()` / `panic!` for terse
119// failure assertions, may emit `println!` / `eprintln!` for debug context,
120// and use raw-string-with-hashes / direct float `==` / unseparated literals
121// where the test input is more readable left as written. Allowed under
122// `cfg(test)` only; never reachable in shipped binaries.
123#![cfg_attr(
124    test,
125    allow(
126        clippy::unwrap_used,
127        clippy::expect_used,
128        clippy::panic,
129        clippy::print_stdout,
130        clippy::print_stderr,
131        clippy::needless_raw_string_hashes,
132        clippy::float_cmp,
133        clippy::unreadable_literal,
134        clippy::manual_assert,
135        clippy::ignore_without_reason,
136    )
137)]
138
139// The README's examples compile and run as doctests. Some of them use the
140// `validation` and `env-override` features, so the check runs when those are
141// on; CI runs the doctests with both.
142#[cfg(all(
143    doctest,
144    feature = "conf",
145    feature = "validation",
146    feature = "env-override"
147))]
148#[doc = include_str!("../README.md")]
149struct ReadmeDoctests;
150
151pub mod config;
152mod convert; // TryFrom<Value> for plain types (makes `Config::get_or` work)
153/// Enterprise-grade configuration management with advanced caching, performance optimizations,
154/// and multi-instance support. Provides thread-safe caching with `Arc<RwLock>` for high-concurrency
155/// environments and sub-50ns access times for cached values.
156pub mod enterprise; // Enterprise API with caching and performance
157pub mod error;
158pub mod load;
159pub mod parsers;
160pub mod value;
161
162#[cfg(feature = "schema")]
163pub mod schema;
164
165#[cfg(feature = "validation")]
166pub mod validation;
167
168/// Hot reloading system for zero-downtime configuration updates
169pub mod hot_reload;
170
171/// Comprehensive audit logging system for configuration operations
172pub mod audit;
173
174/// Environment variable override system for smart configuration overrides
175#[cfg(feature = "env-override")]
176pub mod env_override;
177
178// Re-export main types for convenience
179pub use config::{CacheStats, Config, ConfigBuilder, ConfigOptions, ConfigValue};
180#[allow(deprecated)]
181// see `enterprise.rs` — the items themselves carry the deprecation notices
182pub use enterprise::{ConfigManager, EnterpriseConfig};
183pub use error::{Error, Result};
184pub use load::LoadOptions;
185pub use value::Value;
186
187#[cfg(feature = "schema")]
188pub use schema::{Schema, SchemaBuilder};
189
190#[cfg(feature = "validation")]
191pub use validation::{
192    ValidationError, ValidationResult, ValidationRule, ValidationRuleSet, ValidationSeverity,
193};
194
195use std::path::Path;
196
197/// Parse configuration from a string with optional format hint
198///
199/// This is the primary entry point for parsing configuration data from strings.
200/// Automatically detects format if not specified.
201///
202/// # Arguments
203///
204/// * `source` - The configuration data as a string
205/// * `format` - Optional format hint ("conf", "toml", "json", "noml")
206///
207/// # Returns
208///
209/// Returns a [`Value`] containing the parsed configuration data.
210///
211/// # Errors
212///
213/// Returns an error if:
214/// - The input format is unknown or unsupported
215/// - The input contains syntax errors
216/// - Required features are not enabled for the detected format
217///
218/// # Examples
219///
220/// ```rust
221/// use config_lib::parse;
222///
223/// let config = parse("port = 8080\nname = \"MyApp\"", Some("conf"))?;
224/// let port = config
225///     .get("port")
226///     .ok_or_else(|| config_lib::Error::key_not_found("port"))?
227///     .as_integer()?;
228/// # let _ = port;
229/// # Ok::<(), config_lib::Error>(())
230/// ```
231pub fn parse(source: &str, format: Option<&str>) -> Result<Value> {
232    parsers::parse_string(source, format)
233}
234
235/// Parse configuration from a string without reading anything outside it
236///
237/// The same as [`parse`] for every format except NOML (feature `noml`),
238/// where `include` and every function call (`env()` included) are refused
239/// with [`Error::Parse`] carrying the line and column of the first one.
240/// Use it when the caller has checked the configuration file itself
241/// (owner, mode, size, file type) and nothing else may be read: an include
242/// would read a second file without those checks, and `env()` would copy
243/// an environment variable into the configuration. TOML never resolves
244/// them, in either entry point.
245///
246/// Since v1.3.0.
247///
248/// # Examples
249///
250/// ```rust
251/// use config_lib::parse_strict;
252///
253/// let config = parse_strict("port = 8080", Some("conf"))?;
254/// # let _ = config;
255/// # Ok::<(), config_lib::Error>(())
256/// ```
257pub fn parse_strict(source: &str, format: Option<&str>) -> Result<Value> {
258    parsers::parse_string_strict(source, format)
259}
260
261/// Parse configuration from a file, auto-detecting format from extension
262///
263/// Reads a configuration file from disk and automatically detects the format
264/// based on the file extension (.conf, .toml, .json, .noml).
265///
266/// # Arguments
267///
268/// * `path` - Path to the configuration file
269///
270/// # Returns
271///
272/// Returns a [`Value`] containing the parsed configuration data.
273///
274/// # Errors
275///
276/// Returns an error if:
277/// - The file cannot be read (I/O error)
278/// - The file format cannot be detected
279/// - The file contains syntax errors
280/// - Required features are not enabled for the detected format
281///
282/// # Examples
283///
284/// ```rust,no_run
285/// use config_lib::parse_file;
286///
287/// let config = parse_file("app.conf")?;
288/// let port = config
289///     .get("server.port")
290///     .ok_or_else(|| config_lib::Error::key_not_found("server.port"))?
291///     .as_integer()?;
292/// # let _ = port;
293/// # Ok::<(), config_lib::Error>(())
294/// ```
295pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Value> {
296    parsers::parse_file(path)
297}
298
299/// Validate configuration against a schema
300///
301/// Performs comprehensive validation of configuration data against a provided
302/// schema definition.
303///
304/// # Arguments
305///
306/// * `config` - Configuration value to validate
307/// * `schema` - Schema definition for validation
308///
309/// # Returns
310///
311/// Returns `Ok(())` if validation passes, or an error describing the issue.
312///
313/// # Examples
314///
315/// ```rust
316/// # #[cfg(feature = "schema")]
317/// # {
318/// use config_lib::{parse, SchemaBuilder};
319///
320/// let config = parse(r#"
321///     name = "my-app"
322///     port = 8080
323/// "#, None)?;
324///
325/// let schema = SchemaBuilder::new()
326///     .require_string("name")
327///     .require_integer("port")
328///     .build();
329///
330/// config_lib::validate(&config, &schema)?;
331/// # }
332///
333/// # Ok::<(), config_lib::Error>(())
334/// ```
335#[cfg(feature = "schema")]
336pub fn validate(config: &Value, schema: &Schema) -> Result<()> {
337    schema.validate(config)
338}
339
340/// Async version of parse_file
341///
342/// Available when the `async` feature is enabled.
343#[cfg(feature = "async")]
344pub async fn parse_file_async<P: AsRef<Path>>(path: P) -> Result<Value> {
345    parsers::parse_file_async(path).await
346}