diff --git a/internal/formatter/jsonnetfmt.go b/internal/formatter/jsonnetfmt.go index bdc6f5f..21e741d 100644 --- a/internal/formatter/jsonnetfmt.go +++ b/internal/formatter/jsonnetfmt.go @@ -194,8 +194,10 @@ func Format(filename string, input string, options Options) (string, error) { u := &unparser{options: options} u.unparse(node, false) u.fillFinal(finalFodder, true, false) - // Final whitespace is stripped at lexing time. Add a single new line - // as files ought to end with a new line. - u.write("\n") + if len(finalFodder) == 0 || finalFodder[len(finalFodder)-1].Kind == ast.FodderInterstitial { + // Final whitespace is stripped at lexing time. If we didn't just output a new line in fillFinal, + // then add a single new line to ensure Jsonnet files end with a new line. + u.write("\n") + } return u.string(), nil } diff --git a/internal/formatter/unparser.go b/internal/formatter/unparser.go index ccddabd..532f87f 100644 --- a/internal/formatter/unparser.go +++ b/internal/formatter/unparser.go @@ -85,8 +85,9 @@ func (u *unparser) fodderFill(fodder ast.Fodder, crowded bool, separateToken boo u.write(" ") u.write(fod.Comment[0]) } + u.write("\n") if !skipTrailing { - for i := 0; i <= fod.Blanks; i++ { + for i := 0; i < fod.Blanks; i++ { u.write("\n") } for i := 0; i < fod.Indent; i++ {