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
136// The README's examples compile and run as doctests. Some of them use the
137// `validation` and `env-override` features, so the check runs when those are
138// on; CI runs the doctests with both.
139#[cfg(all(
140    doctest,
141    feature = "conf",
142    feature = "validation",
143    feature = "env-override"
144))]
145#[doc = include_str!("../README.md")]
146struct ReadmeDoctests;
147
148pub mod config;
149mod convert; // TryFrom<Value> for plain types (makes `Config::get_or` work)
150/// Enterprise-grade configuration management with advanced caching, performance optimizations,
151/// and multi-instance support. Provides thread-safe caching with `Arc<RwLock>` for high-concurrency
152/// environments and sub-50ns access times for cached values.
153pub mod enterprise; // Enterprise API with caching and performance
154pub mod error;
155pub mod parsers;
156pub mod value;
157
158#[cfg(feature = "schema")]
159pub mod schema;
160
161#[cfg(feature = "validation")]
162pub mod validation;
163
164/// Hot reloading system for zero-downtime configuration updates
165pub mod hot_reload;
166
167/// Comprehensive audit logging system for configuration operations
168pub mod audit;
169
170/// Environment variable override system for smart configuration overrides
171#[cfg(feature = "env-override")]
172pub mod env_override;
173
174// Re-export main types for convenience
175pub use config::{CacheStats, Config, ConfigBuilder, ConfigOptions, ConfigValue};
176#[allow(deprecated)]
177// see `enterprise.rs` — the items themselves carry the deprecation notices
178pub use enterprise::{ConfigManager, EnterpriseConfig};
179pub use error::{Error, Result};
180pub use value::Value;
181
182#[cfg(feature = "schema")]
183pub use schema::{Schema, SchemaBuilder};
184
185#[cfg(feature = "validation")]
186pub use validation::{
187    ValidationError, ValidationResult, ValidationRule, ValidationRuleSet, ValidationSeverity,
188};
189
190use std::path::Path;
191
192/// Parse configuration from a string with optional format hint
193///
194/// This is the primary entry point for parsing configuration data from strings.
195/// Automatically detects format if not specified.
196///
197/// # Arguments
198///
199/// * `source` - The configuration data as a string
200/// * `format` - Optional format hint ("conf", "toml", "json", "noml")
201///
202/// # Returns
203///
204/// Returns a [`Value`] containing the parsed configuration data.
205///
206/// # Errors
207///
208/// Returns an error if:
209/// - The input format is unknown or unsupported
210/// - The input contains syntax errors
211/// - Required features are not enabled for the detected format
212///
213/// # Examples
214///
215/// ```rust
216/// use config_lib::parse;
217///
218/// let config = parse("port = 8080\nname = \"MyApp\"", Some("conf"))?;
219/// let port = config
220///     .get("port")
221///     .ok_or_else(|| config_lib::Error::key_not_found("port"))?
222///     .as_integer()?;
223/// # let _ = port;
224/// # Ok::<(), config_lib::Error>(())
225/// ```
226pub fn parse(source: &str, format: Option<&str>) -> Result<Value> {
227    parsers::parse_string(source, format)
228}
229
230/// Parse configuration from a string without reading anything outside it
231///
232/// The same as [`parse`] for every format except NOML (feature `noml`),
233/// where `include` and every function call (`env()` included) are refused
234/// with [`Error::Parse`] carrying the line and column of the first one.
235/// Use it when the caller has checked the configuration file itself
236/// (owner, mode, size, file type) and nothing else may be read: an include
237/// would read a second file without those checks, and `env()` would copy
238/// an environment variable into the configuration. TOML never resolves
239/// them, in either entry point.
240///
241/// Since v1.3.0.
242///
243/// # Examples
244///
245/// ```rust
246/// use config_lib::parse_strict;
247///
248/// let config = parse_strict("port = 8080", Some("conf"))?;
249/// # let _ = config;
250/// # Ok::<(), config_lib::Error>(())
251/// ```
252pub fn parse_strict(source: &str, format: Option<&str>) -> Result<Value> {
253    parsers::parse_string_strict(source, format)
254}
255
256/// Parse configuration from a file, auto-detecting format from extension
257///
258/// Reads a configuration file from disk and automatically detects the format
259/// based on the file extension (.conf, .toml, .json, .noml).
260///
261/// # Arguments
262///
263/// * `path` - Path to the configuration file
264///
265/// # Returns
266///
267/// Returns a [`Value`] containing the parsed configuration data.
268///
269/// # Errors
270///
271/// Returns an error if:
272/// - The file cannot be read (I/O error)
273/// - The file format cannot be detected
274/// - The file contains syntax errors
275/// - Required features are not enabled for the detected format
276///
277/// # Examples
278///
279/// ```rust,no_run
280/// use config_lib::parse_file;
281///
282/// let config = parse_file("app.conf")?;
283/// let port = config
284///     .get("server.port")
285///     .ok_or_else(|| config_lib::Error::key_not_found("server.port"))?
286///     .as_integer()?;
287/// # let _ = port;
288/// # Ok::<(), config_lib::Error>(())
289/// ```
290pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Value> {
291    parsers::parse_file(path)
292}
293
294/// Validate configuration against a schema
295///
296/// Performs comprehensive validation of configuration data against a provided
297/// schema definition.
298///
299/// # Arguments
300///
301/// * `config` - Configuration value to validate
302/// * `schema` - Schema definition for validation
303///
304/// # Returns
305///
306/// Returns `Ok(())` if validation passes, or an error describing the issue.
307///
308/// # Examples
309///
310/// ```rust
311/// # #[cfg(feature = "schema")]
312/// # {
313/// use config_lib::{parse, SchemaBuilder};
314///
315/// let config = parse(r#"
316///     name = "my-app"
317///     port = 8080
318/// "#, None)?;
319///
320/// let schema = SchemaBuilder::new()
321///     .require_string("name")
322///     .require_integer("port")
323///     .build();
324///
325/// config_lib::validate(&config, &schema)?;
326/// # }
327///
328/// # Ok::<(), config_lib::Error>(())
329/// ```
330#[cfg(feature = "schema")]
331pub fn validate(config: &Value, schema: &Schema) -> Result<()> {
332    schema.validate(config)
333}
334
335/// Async version of parse_file
336///
337/// Available when the `async` feature is enabled.
338#[cfg(feature = "async")]
339pub async fn parse_file_async<P: AsRef<Path>>(path: P) -> Result<Value> {
340    parsers::parse_file_async(path).await
341}