|
| 1 | +package format_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/microsoft/typescript-go/internal/ast" |
| 8 | + "github.com/microsoft/typescript-go/internal/core" |
| 9 | + "github.com/microsoft/typescript-go/internal/format" |
| 10 | + "github.com/microsoft/typescript-go/internal/parser" |
| 11 | + "gotest.tools/v3/assert" |
| 12 | +) |
| 13 | + |
| 14 | +func TestFormatNoTrailingNewline(t *testing.T) { |
| 15 | + t.Parallel() |
| 16 | + // Issue: Formatter adds extra space at end of line |
| 17 | + // When formatting a file that has content "1;" with no trailing newline, |
| 18 | + // an extra space should NOT be added at the end of the line |
| 19 | + |
| 20 | + testCases := []struct { |
| 21 | + name string |
| 22 | + text string |
| 23 | + }{ |
| 24 | + {"simple statement without trailing newline", "1;"}, |
| 25 | + {"function call without trailing newline", "console.log('hello');"}, |
| 26 | + {"variable declaration without trailing newline", "const x = 1;"}, |
| 27 | + {"multiple statements without trailing newline", "const x = 1;\nconst y = 2;"}, |
| 28 | + } |
| 29 | + |
| 30 | + for _, tc := range testCases { |
| 31 | + t.Run(tc.name, func(t *testing.T) { |
| 32 | + t.Parallel() |
| 33 | + ctx := format.WithFormatCodeSettings(t.Context(), &format.FormatCodeSettings{ |
| 34 | + EditorSettings: format.EditorSettings{ |
| 35 | + TabSize: 4, |
| 36 | + IndentSize: 4, |
| 37 | + BaseIndentSize: 4, |
| 38 | + NewLineCharacter: "\n", |
| 39 | + ConvertTabsToSpaces: true, |
| 40 | + IndentStyle: format.IndentStyleSmart, |
| 41 | + TrimTrailingWhitespace: true, |
| 42 | + }, |
| 43 | + }, "\n") |
| 44 | + sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{ |
| 45 | + FileName: "/test.ts", |
| 46 | + Path: "/test.ts", |
| 47 | + }, tc.text, core.ScriptKindTS) |
| 48 | + edits := format.FormatDocument(ctx, sourceFile) |
| 49 | + newText := applyBulkEdits(tc.text, edits) |
| 50 | + |
| 51 | + // The formatted text should not add extra space at the end |
| 52 | + // It may add proper spacing within the code, but not after the last character |
| 53 | + assert.Assert(t, !strings.HasSuffix(newText, " "), "Formatter should not add trailing space") |
| 54 | + // Also check that no space was added at EOF position if text didn't end with newline |
| 55 | + if !strings.HasSuffix(tc.text, "\n") { |
| 56 | + assert.Assert(t, !strings.HasSuffix(newText, " "), "Formatter should not add space before EOF") |
| 57 | + } |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
0 commit comments