Assign document leading format to the first node instead (#138)

Fixes: https://github.com/kdl-org/kdl-rs/issues/136
This commit is contained in:
Dion Dokter 2025-09-04 19:46:52 +02:00 committed by GitHub
parent 439aa63bfc
commit 758bd63621
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 6 deletions

View File

@ -669,12 +669,13 @@ final;";
doc.iter_dash_args("foo").collect::<Vec<&KdlValue>>(), doc.iter_dash_args("foo").collect::<Vec<&KdlValue>>(),
vec![&1.into(), &2.into(), &"three".into()] vec![&1.into(), &2.into(), &"three".into()]
); );
assert_eq!( assert_eq!(doc.format().map(|f| &f.leading[..]), Some(""));
doc.format().map(|f| &f.leading[..]),
Some("\n// This is the first node\n")
);
let foo = doc.get("foo").expect("expected a foo node"); let foo = doc.get("foo").expect("expected a foo node");
assert_eq!(
foo.format().map(|f| &f.leading[..]),
Some("\n// This is the first node\n")
);
assert_eq!(foo.format().map(|f| &f.terminator[..]), Some("\n")); assert_eq!(foo.format().map(|f| &f.terminator[..]), Some("\n"));
assert_eq!(&foo[2], &"three".into()); assert_eq!(&foo[2], &"three".into());
assert_eq!(&foo["bar"], &"baz".into()); assert_eq!(&foo["bar"], &"baz".into());

View File

@ -282,12 +282,12 @@ pub(crate) fn document(input: &mut Input<'_>) -> PResult<KdlDocument> {
/// `nodes := (line-space* node)* line-space*` /// `nodes := (line-space* node)* line-space*`
fn nodes(input: &mut Input<'_>) -> PResult<KdlDocument> { fn nodes(input: &mut Input<'_>) -> PResult<KdlDocument> {
let leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void()))) let mut leading = repeat(0.., alt((line_space.void(), (slashdash, base_node).void())))
.map(|()| ()) .map(|()| ())
.take() .take()
.parse_next(input)?; .parse_next(input)?;
let _start = input.checkpoint(); let _start = input.checkpoint();
let ns: Vec<KdlNode> = separated( let mut ns: Vec<KdlNode> = separated(
0.., 0..,
node, node,
alt((node_terminator.void(), (eof.void(), any.void()).void())), alt((node_terminator.void(), (eof.void(), any.void()).void())),
@ -299,6 +299,16 @@ fn nodes(input: &mut Input<'_>) -> PResult<KdlDocument> {
.map(|()| ()) .map(|()| ())
.take() .take()
.parse_next(input)?; .parse_next(input)?;
// If there is a node, let it have the leading format
// This gives more consistent behavior
if let Some(first_node) = ns.get_mut(0) {
if let Some(first_node_format) = first_node.format_mut() {
first_node_format.leading = leading.into();
leading = "";
}
}
Ok(KdlDocument { Ok(KdlDocument {
nodes: ns, nodes: ns,
format: Some(KdlDocumentFormat { format: Some(KdlDocumentFormat {