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// REPS-AUDIT: `clippy::pedantic` is a curated lint group, not a hard rule.
69// The following lints are turned back to `allow` because they fire on
70// idioms this crate uses deliberately, or because they trade real
71// readability against pure stylistic preference. The denies above
72// (REPS safety / correctness rules) remain in force.
73//
74// Style / API-shape noise:
75#![allow(clippy::module_name_repetitions)]
76#![allow(clippy::must_use_candidate)]
77#![allow(clippy::return_self_not_must_use)]
78#![allow(clippy::similar_names)]
79#![allow(clippy::wildcard_imports)]
80#![allow(clippy::used_underscore_binding)]
81#![allow(clippy::no_effect_underscore_binding)]
82// Numeric casts at bounded parser/stats boundaries:
83#![allow(clippy::cast_precision_loss)]
84#![allow(clippy::cast_possible_wrap)]
85#![allow(clippy::cast_possible_truncation)]
86#![allow(clippy::cast_sign_loss)]
87// Documentation style preference:
88#![allow(clippy::doc_markdown)]
89#![allow(clippy::missing_errors_doc)]
90#![allow(clippy::missing_panics_doc)]
91// Refactor suggestions deferred to a dedicated cleanup phase
92// (see `.dev/ROADMAP.md` post-1.0 backlog):
93#![allow(clippy::unused_self)]
94#![allow(clippy::self_only_used_in_recursion)]
95#![allow(clippy::unnecessary_wraps)]
96#![allow(clippy::needless_pass_by_value)]
97#![allow(clippy::redundant_closure_for_method_calls)]
98#![allow(clippy::map_unwrap_or)]
99#![allow(clippy::manual_let_else)]
100#![allow(clippy::match_same_arms)]
101#![allow(clippy::single_match_else)]
102#![allow(clippy::inline_always)]
103#![allow(clippy::format_push_string)]
104#![allow(clippy::case_sensitive_file_extension_comparisons)]
105#![allow(clippy::single_char_pattern)]
106#![allow(clippy::unnecessary_literal_bound)]
107#![allow(clippy::if_not_else)]
108#![allow(clippy::struct_excessive_bools)]
109#![allow(clippy::too_many_lines)]
110#![allow(clippy::large_enum_variant)]
111#![allow(clippy::missing_const_for_fn)]
112#![allow(clippy::needless_for_each)]
113#![allow(clippy::implicit_hasher)]
114#![allow(clippy::ignored_unit_patterns)]
115// REPS-AUDIT: test modules use `.unwrap()` / `.expect()` / `panic!` for terse
116// failure assertions, may emit `println!` / `eprintln!` for debug context,
117// and use raw-string-with-hashes / direct float `==` / unseparated literals
118// where the test input is more readable left as written. Allowed under
119// `cfg(test)` only; never reachable in shipped binaries.
120#![cfg_attr(
121 test,
122 allow(
123 clippy::unwrap_used,
124 clippy::expect_used,
125 clippy::panic,
126 clippy::print_stdout,
127 clippy::print_stderr,
128 clippy::needless_raw_string_hashes,
129 clippy::float_cmp,
130 clippy::unreadable_literal,
131 clippy::manual_assert,
132 clippy::ignore_without_reason,
133 )
134)]
135
136pub mod config;
137/// Enterprise-grade configuration management with advanced caching, performance optimizations,
138/// and multi-instance support. Provides thread-safe caching with `Arc<RwLock>` for high-concurrency
139/// environments and sub-50ns access times for cached values.
140pub mod enterprise; // Enterprise API with caching and performance
141pub mod error;
142pub mod parsers;
143pub mod value;
144
145#[cfg(feature = "schema")]
146pub mod schema;
147
148#[cfg(feature = "validation")]
149pub mod validation;
150
151/// Hot reloading system for zero-downtime configuration updates
152pub mod hot_reload;
153
154/// Comprehensive audit logging system for configuration operations
155pub mod audit;
156
157/// Environment variable override system for smart configuration overrides
158#[cfg(feature = "env-override")]
159pub mod env_override;
160
161// Re-export main types for convenience
162pub use config::{CacheStats, Config, ConfigBuilder, ConfigOptions, ConfigValue};
163#[allow(deprecated)]
164// see `enterprise.rs` — the items themselves carry the deprecation notices
165pub use enterprise::{ConfigManager, EnterpriseConfig};
166pub use error::{Error, Result};
167pub use value::Value;
168
169#[cfg(feature = "schema")]
170pub use schema::{Schema, SchemaBuilder};
171
172#[cfg(feature = "validation")]
173pub use validation::{
174 ValidationError, ValidationResult, ValidationRule, ValidationRuleSet, ValidationSeverity,
175};
176
177use std::path::Path;
178
179/// Parse configuration from a string with optional format hint
180///
181/// This is the primary entry point for parsing configuration data from strings.
182/// Automatically detects format if not specified.
183///
184/// # Arguments
185///
186/// * `source` - The configuration data as a string
187/// * `format` - Optional format hint ("conf", "toml", "json", "noml")
188///
189/// # Returns
190///
191/// Returns a [`Value`] containing the parsed configuration data.
192///
193/// # Errors
194///
195/// Returns an error if:
196/// - The input format is unknown or unsupported
197/// - The input contains syntax errors
198/// - Required features are not enabled for the detected format
199///
200/// # Examples
201///
202/// ```rust
203/// use config_lib::parse;
204///
205/// let config = parse("port = 8080\nname = \"MyApp\"", Some("conf"))?;
206/// let port = config
207/// .get("port")
208/// .ok_or_else(|| config_lib::Error::key_not_found("port"))?
209/// .as_integer()?;
210/// # let _ = port;
211/// # Ok::<(), config_lib::Error>(())
212/// ```
213pub fn parse(source: &str, format: Option<&str>) -> Result<Value> {
214 parsers::parse_string(source, format)
215}
216
217/// Parse configuration from a file, auto-detecting format from extension
218///
219/// Reads a configuration file from disk and automatically detects the format
220/// based on the file extension (.conf, .toml, .json, .noml).
221///
222/// # Arguments
223///
224/// * `path` - Path to the configuration file
225///
226/// # Returns
227///
228/// Returns a [`Value`] containing the parsed configuration data.
229///
230/// # Errors
231///
232/// Returns an error if:
233/// - The file cannot be read (I/O error)
234/// - The file format cannot be detected
235/// - The file contains syntax errors
236/// - Required features are not enabled for the detected format
237///
238/// # Examples
239///
240/// ```rust,no_run
241/// use config_lib::parse_file;
242///
243/// let config = parse_file("app.conf")?;
244/// let port = config
245/// .get("server.port")
246/// .ok_or_else(|| config_lib::Error::key_not_found("server.port"))?
247/// .as_integer()?;
248/// # let _ = port;
249/// # Ok::<(), config_lib::Error>(())
250/// ```
251pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Value> {
252 parsers::parse_file(path)
253}
254
255/// Validate configuration against a schema
256///
257/// Performs comprehensive validation of configuration data against a provided
258/// schema definition.
259///
260/// # Arguments
261///
262/// * `config` - Configuration value to validate
263/// * `schema` - Schema definition for validation
264///
265/// # Returns
266///
267/// Returns `Ok(())` if validation passes, or an error describing the issue.
268///
269/// # Examples
270///
271/// ```rust
272/// # #[cfg(feature = "schema")]
273/// # {
274/// use config_lib::{parse, SchemaBuilder};
275///
276/// let config = parse(r#"
277/// name = "my-app"
278/// port = 8080
279/// "#, None)?;
280///
281/// let schema = SchemaBuilder::new()
282/// .require_string("name")
283/// .require_integer("port")
284/// .build();
285///
286/// config_lib::validate(&config, &schema)?;
287/// # }
288///
289/// # Ok::<(), config_lib::Error>(())
290/// ```
291#[cfg(feature = "schema")]
292pub fn validate(config: &Value, schema: &Schema) -> Result<()> {
293 schema.validate(config)
294}
295
296/// Async version of parse_file
297///
298/// Available when the `async` feature is enabled.
299#[cfg(feature = "async")]
300pub async fn parse_file_async<P: AsRef<Path>>(path: P) -> Result<Value> {
301 parsers::parse_file_async(path).await
302}