Skip to content

Commit

Permalink
Merge pull request #2946 from quantified-uncertainty/prettier-trailin…
Browse files Browse the repository at this point in the history
…g-comma-keep

Fixes Prettier bug where single-item dict key trailing comma would be…
  • Loading branch information
berekuk committed Jan 9, 2024
2 parents 9085694 + b1c500d commit 3ad42db
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-spiders-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@quri/prettier-plugin-squiggle": patch
---

"Fixes Prettier bug where trailing comma after single-element dict key would be removed"
8 changes: 6 additions & 2 deletions packages/prettier-plugin/src/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,10 @@ export function createSquigglePrinter(
softline,
"}",
]);
case "Dict":
case "Dict": {
const isSingleKeyWithoutValue =
node.elements.length === 1 &&
node.elements[0].type === "Identifier";
return group([
"{",
node.elements.length
Expand All @@ -326,12 +329,13 @@ export function createSquigglePrinter(
line,
join([",", line], path.map(print, "elements")),
]),
ifBreak(",", ""),
isSingleKeyWithoutValue ? "," : ifBreak(",", ""),
line,
]
: [],
"}",
]);
}
case "String":
return [JSON.stringify(node.value).replaceAll("\\n", "\n")];
case "Ternary":
Expand Down
16 changes: 16 additions & 0 deletions packages/prettier-plugin/test/dicts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,22 @@ describe("dicts", () => {
expect(await format("{foo: 5}")).toBe("{ foo: 5 }");
});

test("one key with trailing comma", async () => {
expect(
await format(`foo=3
{foo,}`)
).toBe(`foo = 3
{ foo, }`);
});

test("two keys with trailing comma", async () => {
expect(
await format(`foo=3
{foo,foo,}`)
).toBe(`foo = 3
{ foo, foo }`);
});

test("shorthand", async () => {
expect(await format("{foo, bar: bar, baz}")).toBe("{ foo, bar: bar, baz }");
});
Expand Down

1 comment on commit 3ad42db

@vercel
Copy link

@vercel vercel bot commented on 3ad42db Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.