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// 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 string without reading anything outside it
218///
219/// The same as [`parse`] for every format except NOML (feature `noml`),
220/// where `include` and every function call (`env()` included) are refused
221/// with [`Error::Parse`] carrying the line and column of the first one.
222/// Use it when the caller has checked the configuration file itself
223/// (owner, mode, size, file type) and nothing else may be read: an include
224/// would read a second file without those checks, and `env()` would copy
225/// an environment variable into the configuration. TOML never resolves
226/// them, in either entry point.
227///
228/// Since v1.3.0.
229///
230/// # Examples
231///
232/// ```rust
233/// use config_lib::parse_strict;
234///
235/// let config = parse_strict("port = 8080", Some("conf"))?;
236/// # let _ = config;
237/// # Ok::<(), config_lib::Error>(())
238/// ```
239pub fn parse_strict(source: &str, format: Option<&str>) -> Result<Value> {
240    parsers::parse_string_strict(source, format)
241}
242
243/// Parse configuration from a file, auto-detecting format from extension
244///
245/// Reads a configuration file from disk and automatically detects the format
246/// based on the file extension (.conf, .toml, .json, .noml).
247///
248/// # Arguments
249///
250/// * `path` - Path to the configuration file
251///
252/// # Returns
253///
254/// Returns a [`Value`] containing the parsed configuration data.
255///
256/// # Errors
257///
258/// Returns an error if:
259/// - The file cannot be read (I/O error)
260/// - The file format cannot be detected
261/// - The file contains syntax errors
262/// - Required features are not enabled for the detected format
263///
264/// # Examples
265///
266/// ```rust,no_run
267/// use config_lib::parse_file;
268///
269/// let config = parse_file("app.conf")?;
270/// let port = config
271///     .get("server.port")
272///     .ok_or_else(|| config_lib::Error::key_not_found("server.port"))?
273///     .as_integer()?;
274/// # let _ = port;
275/// # Ok::<(), config_lib::Error>(())
276/// ```
277pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Value> {
278    parsers::parse_file(path)
279}
280
281/// Validate configuration against a schema
282///
283/// Performs comprehensive validation of configuration data against a provided
284/// schema definition.
285///
286/// # Arguments
287///
288/// * `config` - Configuration value to validate
289/// * `schema` - Schema definition for validation
290///
291/// # Returns
292///
293/// Returns `Ok(())` if validation passes, or an error describing the issue.
294///
295/// # Examples
296///
297/// ```rust
298/// # #[cfg(feature = "schema")]
299/// # {
300/// use config_lib::{parse, SchemaBuilder};
301///
302/// let config = parse(r#"
303///     name = "my-app"
304///     port = 8080
305/// "#, None)?;
306///
307/// let schema = SchemaBuilder::new()
308///     .require_string("name")
309///     .require_integer("port")
310///     .build();
311///
312/// config_lib::validate(&config, &schema)?;
313/// # }
314///
315/// # Ok::<(), config_lib::Error>(())
316/// ```
317#[cfg(feature = "schema")]
318pub fn validate(config: &Value, schema: &Schema) -> Result<()> {
319    schema.validate(config)
320}
321
322/// Async version of parse_file
323///
324/// Available when the `async` feature is enabled.
325#[cfg(feature = "async")]
326pub async fn parse_file_async<P: AsRef<Path>>(path: P) -> Result<Value> {
327    parsers::parse_file_async(path).await
328}