git.delta.rocks / jrsonnet / refs/commits / 46ef62a1f872

difftreelog

feat(fmt) single-line objects

unzqvprpYaroslav Bolyukin2026-02-08parent: #9b1cb43.patch.diff
in: master

6 files changed

modifiedcrates/jrsonnet-formatter/src/children.rsdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/children.rs
+++ b/crates/jrsonnet-formatter/src/children.rs
@@ -80,14 +80,19 @@
 	)
 }
 
-pub fn should_start_with_newline(prev_inline: Option<&ChildTrivia>, tt: &ChildTrivia) -> bool {
-	count_newlines_before(tt)
-		+ prev_inline
-			.map(count_newlines_after)
-			.unwrap_or_default()
+// Should start, triggers multi-line render
+pub fn should_start_with_newline(
+	prev_inline: Option<&ChildTrivia>,
+	tt: &ChildTrivia,
+) -> (bool, bool) {
+	let count =
+		count_newlines_before(tt) + prev_inline.map(count_newlines_after).unwrap_or_default();
 
+	(
 		// First for previous item end, second for current item
-		>= 2
+		count >= 2,
+		count >= 1,
+	)
 }
 
 fn count_newlines_before(tt: &ChildTrivia) -> usize {
@@ -147,13 +152,14 @@
 			} else {
 				mem::take(&mut next)
 			};
+			let (should_start_with_newline, triggers_multiline) = should_start_with_newline(
+				current_child.as_ref().map(|c| &c.inline_trivia),
+				&before_trivia,
+			);
 			let last_child = current_child.replace(Child {
 				// First item should not start with newline
-				should_start_with_newline: had_some
-					&& should_start_with_newline(
-						current_child.as_ref().map(|c| &c.inline_trivia),
-						&before_trivia,
-					),
+				should_start_with_newline: had_some && should_start_with_newline,
+				triggers_multiline,
 				before_trivia,
 				value,
 				inline_trivia: Vec::new(),
@@ -203,7 +209,8 @@
 		should_start_with_newline: should_start_with_newline(
 			current_child.as_ref().map(|c| &c.inline_trivia),
 			&next,
-		),
+		)
+		.0,
 		trivia: next,
 	};
 
@@ -234,6 +241,9 @@
 	/// item2,
 	/// ```
 	pub inline_trivia: ChildTrivia,
+	/// Is this child has whitespace that is considered significant, meaning
+	/// user has inserted it to split the value into multiple lines.
+	pub triggers_multiline: bool,
 }
 
 pub struct EndingComments {
modifiedcrates/jrsonnet-formatter/src/comments.rsdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/comments.rs
+++ b/crates/jrsonnet-formatter/src/comments.rs
@@ -72,7 +72,10 @@
 					if matches!(loc, CommentLocation::ItemInline) {
 						p!(out, str(" "));
 					}
-					p!(out, str("/* ") string(lines[0].trim().to_string()) str(" */") nl);
+					p!(out, str("/* ") string(lines[0].trim().to_string()) str(" */"));
+					if matches!(loc, CommentLocation::AboveItem | CommentLocation::EndOfItems) {
+						p!(out, nl);
+					}
 				} else if !lines.is_empty() {
 					fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {
 						let offset = a
modifiedcrates/jrsonnet-formatter/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/lib.rs
+++ b/crates/jrsonnet-formatter/src/lib.rs
@@ -3,8 +3,10 @@
 use children::{children_between, trivia_before};
 use dprint_core::formatting::{
 	condition_helpers::is_multiple_lines,
+	condition_resolvers::true_resolver,
 	ir_helpers::{new_line_group, with_indent},
-	ConditionResolver, ConditionResolverContext, LineNumber, PrintItems, PrintOptions,
+	ConditionResolver, ConditionResolverContext, LineNumber, PrintItemPath, PrintItems,
+	PrintOptions, Signal,
 };
 use hi_doc::{Formatting, SnippetBuilder};
 use jrsonnet_rowan_parser::{
@@ -12,13 +14,13 @@
 		Arg, ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,
 		DestructRest, Expr, ExprBase, FieldName, ForSpec, IfSpec, ImportKind, Literal, Member,
 		Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc, SourceFile, Stmt, Suffix, Text,
-		UnaryOperator, Visibility,
+		Trivia, TriviaKind, UnaryOperator, Visibility,
 	},
 	AstNode, AstToken as _, SyntaxToken,
 };
 
 use crate::{
-	children::{trivia_after, Child},
+	children::{trivia_after, Child, EndingComments},
 	comments::{format_comments, CommentLocation},
 };
 
@@ -27,6 +29,23 @@
 #[cfg(test)]
 mod tests;
 
+fn with_indent_eoi(cond: ConditionResolver, o: PrintItems, e: EndingComments) -> PrintItems {
+	let end_comments_items = {
+		let mut items = PrintItems::new();
+		if e.should_start_with_newline {
+			p!(&mut items, nl);
+		}
+		format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);
+		items.into_rc_path()
+	};
+	let items =
+		new_line_group(pi!(@i; items(o.into()) items(end_comments_items.into()))).into_rc_path();
+
+	let indented = with_indent(pi!(@i; nl items(items.into())));
+
+	pi!(@i; if_else("indented body", cond, items(indented))(str(" ") items(items.into())))
+}
+
 pub trait Printable {
 	fn print(&self, out: &mut PrintItems);
 }
@@ -147,6 +166,10 @@
 	($o:ident, $($t:tt)*) => {
 		pi!(@s; $o: $($t)*)
 	};
+	(&mut $o:ident, $($t:tt)*) => {
+		let om = &mut $o;
+		pi!(@s; om: $($t)*)
+	};
 }
 pub(crate) use p;
 pub(crate) use pi;
@@ -461,22 +484,53 @@
 					p!(out, str("{ }"));
 					return;
 				}
-				p!(out, str("{") >i nl);
-				for (i, mem) in children.into_iter().enumerate() {
-					if mem.should_start_with_newline && i != 0 {
-						p!(out, nl);
+
+				let source_is_multiline = children.iter().any(|c| c.triggers_multiline)
+					|| end_comments.should_start_with_newline;
+
+				let start = LineNumber::new("obj start line");
+				let end = LineNumber::new("obj end line");
+				let multi_line: ConditionResolver = if source_is_multiline {
+					true_resolver()
+				} else {
+					Rc::new(move |ctx: &mut ConditionResolverContext| {
+						is_multiple_lines(ctx, start, end)
+					})
+				};
+
+				fn gen_members(
+					children: Vec<Child<Member>>,
+					multi_line: ConditionResolver,
+				) -> PrintItems {
+					let mut _out = PrintItems::new();
+					let out = &mut _out;
+					let mut members = children.into_iter().peekable();
+					while let Some(mem) = members.next() {
+						if mem.should_start_with_newline {
+							p!(out, nl);
+						}
+						format_comments(&mem.before_trivia, CommentLocation::AboveItem, out);
+						p!(out, { mem.value });
+						let has_more = members.peek().is_some();
+						if has_more {
+							p!(out, str(","));
+						} else {
+							p!(out, if("trailing comma", multi_line, str(",")));
+						}
+						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, out);
+						p!(out, if_else("member separator", multi_line, nl)(sonl));
 					}
-					format_comments(&mem.before_trivia, CommentLocation::AboveItem, out);
-					p!(out, {mem.value} str(","));
-					format_comments(&mem.inline_trivia, CommentLocation::ItemInline, out);
-					p!(out, nl);
+					_out
 				}
 
-				if end_comments.should_start_with_newline {
-					p!(out, nl);
-				}
-				format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);
-				p!(out, <i str("}"));
+				let members_items =
+					new_line_group(gen_members(children, multi_line.clone())).into_rc_path();
+
+				let members = with_indent_eoi(multi_line, members_items.into(), end_comments);
+
+				p!(out, str("{") info(start));
+				p!(out, items(members));
+				p!(out, str("}") info(end));
 			}
 		}
 	}
modifiedcrates/jrsonnet-formatter/src/snapshots/jrsonnet_formatter__tests__complex_comments.snapdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/snapshots/jrsonnet_formatter__tests__complex_comments.snap
+++ b/crates/jrsonnet-formatter/src/snapshots/jrsonnet_formatter__tests__complex_comments.snap
@@ -1,6 +1,6 @@
 ---
 source: crates/jrsonnet-formatter/src/tests.rs
-expression: "reformat(indoc!(\"{\n\t\t  comments: {\n\t\t\t_: '',\n\t\t\t//     Plain comment\n\t\t\ta: '',\n\n\t\t\t#    Plain comment with empty line before\n\t\t\tb: '',\n\t\t\t/*Single-line multiline comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Single-line multiline doc comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Multiline doc\n\t\t\tComment\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/*\n\n\tMulti-line\n\n\tcomment\n\t\t\t*/\n\t\t\td: '',\n\n\t\t\te: '', // Inline comment\n\n\t\t\tk: '',\n\n\t\t\t// Text after everything\n\t\t  },\n\t\t  comments2: {\n\t\t\tk: '',\n\t\t\t// Text after everything, but no newline above\n\t\t  },\n          spacing: {\n            a: '',\n\n            b: '',\n          },\n          noSpacing: {\n            a: '',\n            b: '',\n          },\n        }\"))"
+expression: "reformat(indoc!(\"{\n\t\t  comments: {\n\t\t\t_: '',\n\t\t\t//     Plain comment\n\t\t\ta: '',\n\n\t\t\t#    Plain comment with empty line before\n\t\t\tb: '',\n\t\t\t/*Single-line multiline comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Single-line multiline doc comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Multiline doc\n\t\t\tComment\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/*\n\n\tMulti-line\n\n\tcomment\n\t\t\t*/\n\t\t\td: '',\n\n\t\t\te: '', // Inline comment\n\n\t\t\tk: '',\n\n\t\t\t// Text after everything\n\t\t  },\n\t\t  comments2: {\n\t\t\tk: '',\n\t\t\t// Text after everything, but no newline above\n\t\t  },\n          spacing: {\n            a: '',\n\n            b: '',\n          },\n          noSpacing: {\n            a: '',\n            b: '',\n          },\n\n\t\t\t smallObjectWithEnding: {/*Ending comment*/},\n\t\t\t smallObjectWithFieldAndEnding: {a: 11/*Ending comment*/},\n\t\t\t smallObjectWithFieldAndEnding2: {/*Start*/a: 11/*Ending comment*/},\n        }\"))"
 ---
 {
 	comments: {
@@ -50,4 +50,13 @@
 		a: '',
 		b: '',
 	},
+
+	smallObjectWithEnding: {
+		/* Ending comment */
+	},
+	smallObjectWithFieldAndEnding: { a: 11 /* Ending comment */ },
+	smallObjectWithFieldAndEnding2: {
+		/* Start */
+		a: 11, /* Ending comment */
+	},
 }
addedcrates/jrsonnet-formatter/src/snapshots/jrsonnet_formatter__tests__complex_nested.snapdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-formatter/src/snapshots/jrsonnet_formatter__tests__complex_nested.snap
@@ -0,0 +1,41 @@
+---
+source: crates/jrsonnet-formatter/src/tests.rs
+expression: "reformat(indoc!(\"\n\t\t\t{\n\t\t\t\tkubernetes: {\n\t\t\t\t deployment: {\n\t\t\t\t\tapiVersion: 'apps/v1',\n\t\t\t\t\tkind: 'Deployment',\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t  name: 'myapp',\n\t\t\t\t\t  labels: { app: 'myapp', version: 'v1' },\n\t\t\t\t\t},\n\t\t\t\t\tspec: {\n\t\t\t\t\t  replicas: 3,\n\t\t\t\t\t  selector: { matchLabels: { app: 'myapp' } },\n\t\t\t\t\t  template: {\n\t\t\t\t\t\t metadata: { labels: { app: 'myapp' } },\n\t\t\t\t\t\t spec: {\n\t\t\t\t\t\t\tcontainers: [\n\t\t\t\t\t\t\t  {\n\t\t\t\t\t\t\t\t name: 'myapp',\n\t\t\t\t\t\t\t\t image: 'myapp:latest',\n\t\t\t\t\t\t\t\t ports: [{ containerPort: 8080 }],\n\t\t\t\t\t\t\t\t env: [\n\t\t\t\t\t\t\t\t\t{ name: 'FOO', value: 'bar' },\n\t\t\t\t\t\t\t\t\t{ name: 'BAZ', valueFrom: { secretKeyRef: { name: 'mysecret', key: 'password' } } },\n\t\t\t\t\t\t\t\t ],\n\t\t\t\t\t\t\t  },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t },\n\t\t\t\t\t  },\n\t\t\t\t\t},\n\t\t\t\t },\n\t\t\t  },\n\t\t\t}\n\t\t\"))"
+---
+{
+	kubernetes: {
+		deployment: {
+			apiVersion: 'apps/v1',
+			kind: 'Deployment',
+			metadata: {
+				name: 'myapp',
+				labels: { app: 'myapp', version: 'v1' },
+			},
+			spec: {
+				replicas: 3,
+				selector: { matchLabels: { app: 'myapp' } },
+				template: {
+					metadata: { labels: { app: 'myapp' } },
+					spec: {
+						containers: [
+							{
+								name: 'myapp',
+								image: 'myapp:latest',
+								ports: [
+									{ containerPort: 8080 },
+								],
+								env: [
+									{ name: 'FOO', value: 'bar' },
+									{
+										name: 'BAZ',
+										valueFrom: { secretKeyRef: { name: 'mysecret', key: 'password' } },
+									},
+								],
+							},
+						],
+					},
+				},
+			},
+		},
+	},
+}
modifiedcrates/jrsonnet-formatter/src/tests.rsdiffbeforeafterboth
24#[test]24#[test]
25fn complex_comments() {25fn complex_comments() {
26 insta::assert_snapshot!(reformat(indoc!(26 insta::assert_snapshot!(reformat(indoc!(
27 "{27 "{
28 comments: {28 comments: {
29 _: '',29 _: '',
30 // Plain comment30 // Plain comment
31 a: '',31 a: '',
3232
33 # Plain comment with empty line before33 # Plain comment with empty line before
34 b: '',34 b: '',
35 /*Single-line multiline comment35 /*Single-line multiline comment
3636
37 */37 */
38 c: '',38 c: '',
3939
40 /**Single-line multiline doc comment40 /**Single-line multiline doc comment
4141
42 */42 */
43 c: '',43 c: '',
4444
45 /**Multiline doc45 /**Multiline doc
46 Comment46 Comment
47 */47 */
48 c: '',48 c: '',
4949
50 /*50 /*
5151
52 Multi-line52 Multi-line
5353
54 comment54 comment
55 */55 */
56 d: '',56 d: '',
5757
58 e: '', // Inline comment58 e: '', // Inline comment
5959
60 k: '',60 k: '',
6161
62 // Text after everything62 // Text after everything
63 },63 },
64 comments2: {64 comments2: {
65 k: '',65 k: '',
66 // Text after everything, but no newline above66 // Text after everything, but no newline above
67 },67 },
68 spacing: {68 spacing: {
69 a: '',69 a: '',
7070
71 b: '',71 b: '',
72 },72 },
73 noSpacing: {73 noSpacing: {
74 a: '',74 a: '',
75 b: '',75 b: '',
76 },76 },
77
78 smallObjectWithEnding: {/*Ending comment*/},
79 smallObjectWithFieldAndEnding: {a: 11/*Ending comment*/},
80 smallObjectWithFieldAndEnding2: {/*Start*/a: 11/*Ending comment*/},
77 }"81 }"
78 )));82 )));
79}83}
8084
105 )));109 )));
106}110}
111
112#[test]
113fn complex_nested() {
114 insta::assert_snapshot!(reformat(indoc!(
115 "
116 {
117 kubernetes: {
118 deployment: {
119 apiVersion: 'apps/v1',
120 kind: 'Deployment',
121 metadata: {
122 name: 'myapp',
123 labels: { app: 'myapp', version: 'v1' },
124 },
125 spec: {
126 replicas: 3,
127 selector: { matchLabels: { app: 'myapp' } },
128 template: {
129 metadata: { labels: { app: 'myapp' } },
130 spec: {
131 containers: [
132 {
133 name: 'myapp',
134 image: 'myapp:latest',
135 ports: [{ containerPort: 8080 }],
136 env: [
137 { name: 'FOO', value: 'bar' },
138 { name: 'BAZ', valueFrom: { secretKeyRef: { name: 'mysecret', key: 'password' } } },
139 ],
140 },
141 ],
142 },
143 },
144 },
145 },
146 },
147 }
148 "
149 )));
150}
107151