Skip to content

Commit

Permalink
Fix: File with only comment and one on the first line reorder comments (
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheeguerin authored and markcowl committed Mar 8, 2024
1 parent 4959979 commit ef13f8f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
8 changes: 8 additions & 0 deletions .chronus/changes/fix-comment-only-2024-1-26-16-20-24.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: fix
packages:
- "@typespec/compiler"
---

[Formatter] Formatting file with only comments would reorder the first line.
13 changes: 11 additions & 2 deletions packages/compiler/src/formatter/print/comment-handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Printer } from "prettier";
import { Node, SyntaxKind, TypeSpecScriptNode } from "../../core/types.js";
import { Node, SyntaxKind, TextRange, TypeSpecScriptNode } from "../../core/types.js";
import { util } from "./util.js";

interface CommentNode {
interface CommentNode extends TextRange {
readonly kind: SyntaxKind.LineComment | SyntaxKind.BlockComment;
precedingNode?: Node;
enclosingNode?: Node;
followingNode?: Node;
Expand All @@ -19,6 +20,14 @@ export const commentHandler: Printer<Node>["handleComments"] = {
addCommentBetweenAnnotationsAndNode,
handleOnlyComments,
].some((x) => x({ comment, text, options, ast: ast as TypeSpecScriptNode, isLastComment })),
remaining: (comment, text, options, ast, isLastComment) =>
[handleOnlyComments].some((x) =>
x({ comment, text, options, ast: ast as TypeSpecScriptNode, isLastComment })
),
endOfLine: (comment, text, options, ast, isLastComment) =>
[handleOnlyComments].some((x) =>
x({ comment, text, options, ast: ast as TypeSpecScriptNode, isLastComment })
),
};

interface CommentContext {
Expand Down
16 changes: 16 additions & 0 deletions packages/compiler/test/formatter/formatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,22 @@ alias foo = ""; /* one */ /* two */ /* three */
});
});

it("format empty file with comment inside starting first line", async () => {
await assertFormat({
code: `
// empty file
// commented out things
`,
expected: `
// empty file
// commented out things
`,
});
});

it("format empty model with comment inside", async () => {
await assertFormat({
code: `
Expand Down

0 comments on commit ef13f8f

Please sign in to comment.