Skip to content

Commit

Permalink
Add EOF newline to source code, if not there; Fix #480
Browse files Browse the repository at this point in the history
  • Loading branch information
jindraivanek committed Sep 17, 2019
1 parent b1f28f9 commit 632dddc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
12 changes: 12 additions & 0 deletions src/Fantomas.Tests/CompilerDirectivesTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -766,3 +766,15 @@ let x = 1
let x = 1
#endif
"""

[<Test>]
let ``inactive code with no newline at EOF #480``() =
formatSourceString false """
#if NOT_DEFINED
let x = 1
#endif
""" config
|> should equal """#if NOT_DEFINED
let x = 1
#endif
"""
16 changes: 8 additions & 8 deletions src/Fantomas/CodeFormatterImpl.fs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,13 @@ let isValidFSharpCode formatContext =
return false
}

let addNewlineIfNeeded (formattedSourceCode:string) =
// When formatting the whole document, an EOL is required
if formattedSourceCode.EndsWith(Environment.NewLine) then
formattedSourceCode
else
formattedSourceCode + Environment.NewLine

let formatWith ast formatContext config =
let moduleName = Path.GetFileNameWithoutExtension formatContext.FileName
let input =
Expand All @@ -410,7 +417,7 @@ let formatWith ast formatContext config =
// Use '\n' as the new line delimiter consistently
// It would be easier for F# parser
let sourceCode = defaultArg input String.Empty
let normalizedSourceCode = String.normalizeNewLine sourceCode
let normalizedSourceCode = String.normalizeNewLine sourceCode |> addNewlineIfNeeded
let formattedSourceCode =
let context = Fantomas.Context.Context.create config formatContext.ProjectOptions.ConditionalCompilationDefines normalizedSourceCode (Some ast)
context |> genParsedInput { ASTContext.Default with TopLevelModuleName = moduleName } ast
Expand Down Expand Up @@ -447,13 +454,6 @@ let format config formatContext =
return merged
}

let addNewlineIfNeeded (formattedSourceCode:string) =
// When formatting the whole document, an EOL is required
if formattedSourceCode.EndsWith(Environment.NewLine) then
formattedSourceCode
else
formattedSourceCode + Environment.NewLine

/// Format a source string using given config
let formatDocument config formatContext =
async {
Expand Down

0 comments on commit 632dddc

Please sign in to comment.