Skip to main content

kdl_config/
lib.rs

1//! Strongly typed KDL configuration with derive-based decoding, canonical
2//! rendering, validation, fragments, layered loading, and round-trip updates.
3//!
4//! Most consumers derive [`derive@KdlNode`] and call [`parse_str`]:
5//!
6//! ```
7//! use kdl_config::{KdlNode, parse_str};
8//!
9//! #[derive(Debug, KdlNode)]
10//! #[kdl(node = "server")]
11//! struct Server {
12//!     #[kdl(attr)]
13//!     host: String,
14//!     #[kdl(attr)]
15//!     port: u16,
16//! }
17//!
18//! let server: Server = parse_str(r#"server host="localhost" port=8080"#)?;
19//! assert_eq!(server.port, 8080);
20//! # Ok::<(), kdl_config::KdlConfigError>(())
21//! ```
22#![allow(clippy::result_large_err)]
23extern crate self as kdl_config;
24
25pub mod config;
26pub mod context;
27pub mod convert;
28pub mod error;
29pub mod formatter;
30pub mod fragments;
31pub mod helpers;
32pub mod layer;
33pub mod loader;
34pub mod merge;
35pub mod newtypes;
36pub mod node_ext;
37pub mod node_path;
38pub mod parse;
39mod primitive_decode;
40pub mod render;
41mod residual;
42pub mod resolve;
43pub mod round_trip;
44pub mod schema;
45pub mod selector;
46mod sigil_fragments;
47pub mod types;
48pub mod validation;
49pub use kdl;
50
51pub use newtypes::{Duration, Identifier, LenientIdentifier, PositiveCount, Scalar, Weight};
52pub use validation::{
53    AsF64, KdlContains, KdlSubsetOf, KdlValidate, KdlValidateCount, run_count_validations,
54    run_cross_field_validation, run_exists_in_validation, run_field_validations,
55    run_func_validation, run_subset_of_validation, run_typed_cross_field_validation,
56};
57
58pub use config::{
59    BoolMode, ConflictPolicy, DefaultPlacement, EffectiveConfig, FieldOverrides, FlagStyle,
60    FragmentSyntax, ParseConfig, RootMode, StructOverrides, resolve_field, resolve_struct,
61};
62pub use context::{DecodeContext, Source, UpdateContext};
63pub use convert::{
64    ConvertContext, FromKdlValue, ValueConvertExt, convert_value, convert_value_checked,
65    convert_value_checked_ctx, convert_value_ctx,
66};
67pub use error::{ErrorKind, KdlConfigError, NodeLocation, Placement};
68pub use formatter::KdlFormatter;
69pub use fragments::FragmentExpansion;
70pub use kdl::{KdlDocument, KdlEntry, KdlNode, KdlValue};
71pub use node_ext::{
72    KdlNodeExt, arg_entry_index, attr_entry_indices, remove_attr_entries, remove_entry_indices,
73    remove_positional_entry, update_entry_from_value, update_entry_value, update_or_insert_attr,
74    update_or_insert_attr_value, update_or_insert_positional, update_or_insert_positional_value,
75};
76pub use node_path::NodePath;
77pub use parse::{parse_config, parse_config_with_config, parse_node, parse_node_with_config};
78pub use render::{
79    NodeRenderer, escape_string, insert_arg, insert_attr, is_valid_identifier, new_kdl_node,
80    new_kdl_node_with_config, render_child_node, render_flatten, render_key, render_key_with_repr,
81    render_node, render_node_name, render_node_name_with_config, render_node_name_with_repr,
82    render_node_name_with_repr_and_config, render_node_with_config, render_value,
83    render_value_node, render_value_node_scalar, render_value_with_repr, replace_node_name,
84    set_kdl_node_name, set_kdl_node_name_with_config, value_node, value_to_kdl, value_to_kdl_entry,
85    value_to_kdl_values, with_bare_identifiers, write_indent,
86};
87pub use residual::{
88    capture_rest_attrs, capture_rest_children, render_captured_node, update_captured_node,
89    update_rest_attrs, update_rest_children,
90};
91pub use resolve::{decode_at, decode_at_with_config, node_at};
92pub use round_trip::{
93    RoundTripAst, parse_file_roundtrip, parse_file_roundtrip_with_config, parse_str_roundtrip,
94    parse_str_roundtrip_with_config,
95};
96pub use selector::{CollectMode, CollectionSpec, InjectOpt, SelectOpts, SelectSpec, SelectorAst};
97pub use types::{
98    FieldOrder, MergeModifierPolicy, Modifier, Node, NodeLocation as NodeLocationLegacy, Value,
99};
100
101/// Trait for decoding a typed configuration from a KDL Node.
102pub trait KdlDecode: Sized {
103    /// Whether typed parse entry points should run fragment expansion before
104    /// decoding this type.
105    ///
106    /// Derives set this to `false` for `#[kdl(fragments = false)]`. Manual
107    /// implementations retain the default fragment-aware behavior.
108    const EXPAND_FRAGMENTS: bool = true;
109
110    /// Return whether this type can decode a node with `name`.
111    ///
112    /// Derived node and choice types provide an exact answer. Manual
113    /// implementations accept any name unless they override this method.
114    fn accepts_node_name(_name: &str) -> bool {
115        true
116    }
117
118    fn decode(node: &KdlNode, ctx: &DecodeContext) -> Result<Self, KdlConfigError>;
119}
120
121/// Trait for updating an existing KDL Node in-place (AST-preserving).
122pub trait KdlUpdate {
123    fn update(&self, node: &mut KdlNode, ctx: &UpdateContext) -> Result<(), KdlConfigError>;
124}
125
126/// Trait for rendering a value into KDL.
127pub trait KdlRender {
128    fn render<W: std::fmt::Write>(&self, w: &mut W, name: &str, indent: usize) -> std::fmt::Result;
129    fn render_node(&self, name: &str) -> Node {
130        let rendered = crate::to_kdl(self, name);
131        crate::parse_node(&rendered).expect("rendered node is invalid KDL")
132    }
133}
134
135/// Trait for encoding a value into a new KDL Node (canonical rendering).
136pub trait KdlEncode {
137    fn encode(&self, name: &str) -> KdlNode;
138}
139
140impl<T: KdlRender + ?Sized> KdlEncode for T {
141    fn encode(&self, name: &str) -> KdlNode {
142        let rendered = to_kdl(self, name);
143        let document = rendered
144            .parse::<KdlDocument>()
145            .expect("KdlRender produced invalid KDL");
146        document
147            .nodes()
148            .first()
149            .cloned()
150            .expect("KdlRender produced an empty document")
151    }
152}
153
154impl<T: KdlDecode> KdlDecode for Box<T> {
155    const EXPAND_FRAGMENTS: bool = T::EXPAND_FRAGMENTS;
156
157    fn accepts_node_name(name: &str) -> bool {
158        T::accepts_node_name(name)
159    }
160
161    fn decode(node: &KdlNode, ctx: &DecodeContext) -> Result<Self, KdlConfigError> {
162        T::decode(node, ctx).map(Box::new)
163    }
164}
165
166/// Render a KDL value into a string.
167pub fn to_kdl<T: KdlRender + ?Sized>(value: &T, name: &str) -> String {
168    let mut rendered = String::new();
169    value
170        .render(&mut rendered, name, 0)
171        .expect("render to string");
172    rendered
173}
174
175/// Render a KDL value using the selected fragment language.
176pub fn to_kdl_with_config<T: KdlRender>(value: &T, name: &str, config: &ParseConfig) -> String {
177    let node = value.render_node(name);
178    render_node_with_config(&node, config)
179}
180
181/// Render a KDL value into a flat document, i.e. as the children of the
182/// implicit wrapper node `name` rather than as a `name { ... }` block.
183///
184/// This is the render counterpart to [`RootMode::Document`]: it strips the
185/// outer wrapper that [`to_kdl`] would emit so the produced text round-trips
186/// through [`parse_str_with_config`] when `root_mode` is
187/// [`RootMode::Document`]. If the value renders to a non-empty node the
188/// returned string ends with a single trailing newline; an empty document
189/// returns an empty string.
190pub fn to_kdl_document<T: KdlRender + ?Sized>(value: &T, name: &str) -> String {
191    let wrapped = to_kdl(value, name);
192    strip_root_wrapper(&wrapped, name)
193}
194
195/// Render a flat KDL document using the selected fragment language.
196pub fn to_kdl_document_with_config<T: KdlRender>(
197    value: &T,
198    name: &str,
199    config: &ParseConfig,
200) -> String {
201    let wrapped = to_kdl_with_config(value, name, config);
202    strip_root_wrapper(&wrapped, name)
203}
204
205/// Strip the `name { ... }` wrapper around a rendered KDL document so that
206/// the children become flat top-level nodes. Returns the body with one-level
207/// dedent applied; never panics on unexpected shapes — if the wrapper is not
208/// found the input is returned trimmed with a trailing newline.
209fn strip_root_wrapper(wrapped: &str, name: &str) -> String {
210    if let Ok(document) = wrapped.parse::<KdlDocument>()
211        && let Some(root) = document.nodes().first()
212        && root.base_name() == name
213        && let Some(children) = root.children()
214    {
215        let rendered = children.to_string();
216        let mut out = String::with_capacity(rendered.len());
217        for line in rendered.lines() {
218            let dedented = line.strip_prefix("    ").unwrap_or(line);
219            if !dedented.is_empty() || !out.is_empty() {
220                out.push_str(dedented);
221                out.push('\n');
222            }
223        }
224        let result = out.trim().to_string();
225        return if result.is_empty() {
226            result
227        } else {
228            result + "\n"
229        };
230    }
231
232    let result = wrapped.trim().to_string();
233    if result.is_empty() {
234        result
235    } else {
236        result + "\n"
237    }
238}
239
240/// Parse a KDL string into a typed configuration using default config.
241pub fn parse_str<T: KdlDecode>(contents: &str) -> Result<T, KdlConfigError> {
242    parse_str_with_config(contents, &ParseConfig::default())
243}
244
245/// Parse a KDL string into a typed configuration using the provided config.
246pub fn parse_str_with_config<T: KdlDecode>(
247    contents: &str,
248    config: &ParseConfig,
249) -> Result<T, KdlConfigError> {
250    let mut effective_config = config.clone();
251    effective_config.expand_fragments &= T::EXPAND_FRAGMENTS;
252    parse_str_with_effective_config(contents, &effective_config)
253}
254
255fn parse_str_with_effective_config<T: KdlDecode>(
256    contents: &str,
257    config: &ParseConfig,
258) -> Result<T, KdlConfigError> {
259    let mut doc: KdlDocument = contents
260        .parse()
261        .map_err(|e: kdl::KdlError| KdlConfigError::from_kdl_parse_error("KDL Document", e))?;
262    let source = Source::new(contents.to_string());
263    preprocess_document(&mut doc, config, Some(&source), None)?;
264    decode_preprocessed_document::<T>(doc, config, &source)
265}
266
267fn decode_preprocessed_document<T: KdlDecode>(
268    mut doc: KdlDocument,
269    config: &ParseConfig,
270    source: &Source,
271) -> Result<T, KdlConfigError> {
272    if let RootMode::Document { name } = &config.root_mode {
273        doc = wrap_document(doc, name);
274    }
275    let ctx = DecodeContext::new(config, Some(source));
276    let nodes = doc.nodes();
277    let decoded = match nodes.len() {
278        0 => Err(KdlConfigError::custom(
279            "KDL Document",
280            "expected a single top-level node, found none",
281        )),
282        1 => T::decode(&nodes[0], &ctx.with_root_node(&nodes[0], 0)),
283        count => Err(KdlConfigError::custom(
284            "KDL Document",
285            format!("expected a single top-level node, found {count}"),
286        )),
287    };
288
289    match decoded {
290        Ok(value) => Ok(value),
291        Err(err) => {
292            let should_wrap = matches!(
293                &err.kind,
294                ErrorKind::Custom(message)
295                    if message.starts_with("expected a single top-level node")
296            ) || matches!(&err.kind, ErrorKind::NodeNameMismatch { .. });
297
298            if should_wrap && let RootMode::WrapExpectedNode { name } = &config.root_mode {
299                let wrapped = wrap_document(doc, name);
300                let mut strict = config.clone();
301                strict.root_mode = RootMode::Strict;
302                decode_preprocessed_document::<T>(wrapped, &strict, source)
303            } else {
304                Err(err)
305            }
306        }
307    }
308}
309
310fn wrap_document(doc: KdlDocument, name: &str) -> KdlDocument {
311    let mut wrapper = KdlNode::new(name);
312    wrapper.set_children(doc);
313    let mut wrapped = KdlDocument::new();
314    wrapped.nodes_mut().push(wrapper);
315    wrapped
316}
317
318pub(crate) fn preprocess_document(
319    doc: &mut KdlDocument,
320    config: &ParseConfig,
321    location: Option<&dyn crate::fragments::LocationProvider>,
322    origin: Option<&std::path::Path>,
323) -> Result<FragmentExpansion, KdlConfigError> {
324    if !config.expand_fragments {
325        return Ok(FragmentExpansion::default());
326    }
327    match config.fragment_syntax {
328        FragmentSyntax::Sigil => {
329            crate::sigil_fragments::expand_sigil_fragments(doc, location, origin)
330        }
331        FragmentSyntax::LegacyKeywords => crate::fragments::expand_fragments(doc, location),
332    }
333}
334
335/// Expand fragments in a parsed KDL document using the default sigil syntax.
336///
337/// Because this direct-AST entry point has no source path, an `@import`
338/// directive produces an import-needs-source error.
339pub fn expand_fragments(
340    doc: &mut KdlDocument,
341    location: Option<&dyn crate::fragments::LocationProvider>,
342) -> Result<FragmentExpansion, KdlConfigError> {
343    expand_fragments_with_config(doc, location, &ParseConfig::default())
344}
345
346/// Expand fragments in a parsed KDL document using `config`.
347pub fn expand_fragments_with_config(
348    doc: &mut KdlDocument,
349    location: Option<&dyn crate::fragments::LocationProvider>,
350    config: &ParseConfig,
351) -> Result<FragmentExpansion, KdlConfigError> {
352    preprocess_document(doc, config, location, None)
353}
354
355/// Parse a typed KDL file using [`ParseConfig::default`].
356pub fn parse_file<T: KdlDecode>(path: impl AsRef<std::path::Path>) -> Result<T, KdlConfigError> {
357    parse_file_with_config(path, &ParseConfig::default())
358}
359
360/// Parse a typed KDL file, resolving `@import` relative to that file.
361pub fn parse_file_with_config<T: KdlDecode>(
362    path: impl AsRef<std::path::Path>,
363    config: &ParseConfig,
364) -> Result<T, KdlConfigError> {
365    let path = path.as_ref();
366    let contents = std::fs::read_to_string(path).map_err(|err| {
367        KdlConfigError::custom(
368            "KDL file",
369            format!("failed to read {}: {err}", path.display()),
370        )
371    })?;
372    let mut effective_config = config.clone();
373    effective_config.expand_fragments &= T::EXPAND_FRAGMENTS;
374    let mut doc: KdlDocument = contents.parse().map_err(|e: kdl::KdlError| {
375        KdlConfigError::from_kdl_parse_error("KDL Document", e).with_source_path(path)
376    })?;
377    let source = Source::with_path(contents.clone(), path);
378    preprocess_document(&mut doc, &effective_config, Some(&source), Some(path))?;
379    decode_preprocessed_document::<T>(doc, &effective_config, &source)
380}
381
382// Re-export derive macros so users only need to depend on `kdl-config`
383pub use kdl_config_derive::{Kdl, KdlChoice, KdlMerge, KdlNode, KdlPartial, KdlSchema, KdlValue};