diff --git a/.changeset/funny-spiders-clean.md b/.changeset/funny-spiders-clean.md new file mode 100644 index 0000000000..bbf1f53d41 --- /dev/null +++ b/.changeset/funny-spiders-clean.md @@ -0,0 +1,5 @@ +--- +"@quri/prettier-plugin-squiggle": patch +--- + +"Fixes Prettier bug where trailing comma after single-element dict key would be removed" diff --git a/packages/prettier-plugin/src/printer.ts b/packages/prettier-plugin/src/printer.ts index bc3e1c8e7f..21abf6d740 100644 --- a/packages/prettier-plugin/src/printer.ts +++ b/packages/prettier-plugin/src/printer.ts @@ -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 @@ -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": diff --git a/packages/prettier-plugin/test/dicts.test.ts b/packages/prettier-plugin/test/dicts.test.ts index 5dde446938..611d6b6c97 100644 --- a/packages/prettier-plugin/test/dicts.test.ts +++ b/packages/prettier-plugin/test/dicts.test.ts @@ -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 }"); });