diff --git a/internal/format/format_test.go b/internal/format/format_test.go new file mode 100644 index 0000000000..1bf7945076 --- /dev/null +++ b/internal/format/format_test.go @@ -0,0 +1,60 @@ +package format_test + +import ( + "strings" + "testing" + + "github.com/microsoft/typescript-go/internal/ast" + "github.com/microsoft/typescript-go/internal/core" + "github.com/microsoft/typescript-go/internal/format" + "github.com/microsoft/typescript-go/internal/parser" + "gotest.tools/v3/assert" +) + +func TestFormatNoTrailingNewline(t *testing.T) { + t.Parallel() + // Issue: Formatter adds extra space at end of line + // When formatting a file that has content "1;" with no trailing newline, + // an extra space should NOT be added at the end of the line + + testCases := []struct { + name string + text string + }{ + {"simple statement without trailing newline", "1;"}, + {"function call without trailing newline", "console.log('hello');"}, + {"variable declaration without trailing newline", "const x = 1;"}, + {"multiple statements without trailing newline", "const x = 1;\nconst y = 2;"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ctx := format.WithFormatCodeSettings(t.Context(), &format.FormatCodeSettings{ + EditorSettings: format.EditorSettings{ + TabSize: 4, + IndentSize: 4, + BaseIndentSize: 4, + NewLineCharacter: "\n", + ConvertTabsToSpaces: true, + IndentStyle: format.IndentStyleSmart, + TrimTrailingWhitespace: true, + }, + }, "\n") + sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{ + FileName: "/test.ts", + Path: "/test.ts", + }, tc.text, core.ScriptKindTS) + edits := format.FormatDocument(ctx, sourceFile) + newText := applyBulkEdits(tc.text, edits) + + // The formatted text should not add extra space at the end + // It may add proper spacing within the code, but not after the last character + assert.Assert(t, !strings.HasSuffix(newText, " "), "Formatter should not add trailing space") + // Also check that no space was added at EOF position if text didn't end with newline + if !strings.HasSuffix(tc.text, "\n") { + assert.Assert(t, !strings.HasSuffix(newText, " "), "Formatter should not add space before EOF") + } + }) + } +} diff --git a/internal/format/rules.go b/internal/format/rules.go index c8b31a247e..07af86ef99 100644 --- a/internal/format/rules.go +++ b/internal/format/rules.go @@ -9,7 +9,9 @@ import ( func getAllRules() []ruleSpec { allTokens := make([]ast.Kind, 0, ast.KindLastToken-ast.KindFirstToken+1) for token := ast.KindFirstToken; token <= ast.KindLastToken; token++ { - allTokens = append(allTokens, token) + if token != ast.KindEndOfFile { + allTokens = append(allTokens, token) + } } anyTokenExcept := func(tokens ...ast.Kind) tokenRange {