Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: File with only comment and one on the first line reorder comments #2955

Merged
merged 4 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading