diff --git a/AGENTS.md b/AGENTS.md index 872f128b16..21c77c9009 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,21 +23,35 @@ Scripts require a debug build first (`dotnet build src/Fantomas/Fantomas.fsproj` ## Code Style -Annotate every parameter and the return type on a function, even where inference would manage -without it: +Annotate every `let` binding, even where inference would manage without it. On a function that +means every parameter and the return type; on a value it means the type: ```fsharp let writeRow (column: int) (left: string) (right: string) : unit = ... + +let extensions: Set = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] ``` -A written signature reads as documentation, and a wrong assumption fails at the definition -rather than at a call site somewhere else. Both matter more when the reader is skimming -unfamiliar code, which is most of the time. Modules with a signature file already state this at -the boundary; annotate the implementation as well. +A written type reads as documentation, and a wrong assumption fails at the definition rather than +at a call site somewhere else. Both matter more when the reader is skimming unfamiliar code, which +is most of the time, and a reader should not have to run the inference in their head to find out +what a name holds. Modules with a signature file already state this at the boundary; annotate the +implementation as well. + +This applies inside a function as much as at the top level: a local `let` in a long body is +exactly where a reader loses track of what something is. This is guidance for code you are writing or revisiting, not a reason to sweep the codebase. -When you touch a function for some other reason, add the annotations it is missing. Leave the -functions you had no reason to open alone. +When you touch a binding for some other reason, add the annotations it is missing. Leave the +bindings you had no reason to open alone. + +In a file that has a signature file, the signature file is the visibility boundary: anything it +does not list is already hidden. Do not write `let private` there. The keyword adds nothing and +suggests the `.fsi` says something it does not. + +Documentation comments belong in the signature file only, never in both. A `///` in the `.fs` +alongside one in the `.fsi` is a second copy to keep in step, and the one readers and tooling see +is the signature. ## Changelog @@ -45,7 +59,7 @@ When updating `CHANGELOG.md`, add new entries to the **end** of the relevant sec ## Post-task Steps -Run these after completing a task, not during iterative development — analyzers can be slow. +Run these after completing a task rather than during iterative development. ### Format @@ -59,4 +73,13 @@ dotnet fsi build.fsx -- -p FormatAll dotnet fsi build.fsx -- -p Analyze ``` -Output goes to `analysis.sarif` in the repo root. +Output goes to `analysis.sarif` in the repo root. This is safe to run whenever you need it; it no +longer saturates the machine. + +**Read `analysis.sarif` afterwards.** The pipeline writes its findings there and exits 0 whatever +it found, so a run finishing tells you nothing. GitHub raises the same findings as code scanning +alerts on the pull request, which is a slower way to learn about them. + +When you read it, read the results for every project you touched. Filtering the paths down to +`src/Fantomas/` looks right and silently drops `src/Fantomas.Tests/`, which does not contain that +substring. Match on `src/` and look at what comes back. diff --git a/CHANGELOG.md b/CHANGELOG.md index 298674913f..dc75063419 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ - Breaking: the `--help` page is written by Fantomas instead of by Argu. It carries the version, worked examples, what an input path may be, and links to the documentation, the F# Discord and the `llms.txt` files an LLM can read. Colours are used when the terminal supports them and dropped when standard out is redirected. `-h` is now accepted alongside `--help`. An argument error reports the complaint on standard error followed by a pointer to `--help`, where it used to print Argu's usage block. [#3402](https://github.com/fsprojects/fantomas/pull/3402) - Breaking: a run over a single file reports the path it was given instead of only the file name, so `fantomas src/A.fs` prints `src/A.fs was formatted.` where it printed `A.fs was formatted.`. The same applies to the unchanged, ignored and failure messages. A run over several files already reported the path, so the two now agree. [#3404](https://github.com/fsprojects/fantomas/pull/3404) - Breaking: a file that cannot be parsed is reported with the position of every diagnostic the parser produced, one MSBuild style line each, followed by a snippet of the source with two lines of context either side and a caret under the offending range. This replaces `Could not parse the file.` for a format run, the `%A` record dump and stack trace for a `--check` run, and the same `%A` dump the daemon used to hand editors. Diagnostics are ordered by position and columns are one based, matching what the F# compiler prints for the same file. [#3405](https://github.com/fsprojects/fantomas/pull/3405) +- Breaking: the messages for an input path Fantomas cannot work with are now the same whether the run formats or checks. `--check` used to report `Input path 'x' is unsupported file type` and `Input path 'x' not found` without a full stop where a format run ended both with one, and a run with no input path at all said `No input path provided.` when checking and `Input path is missing.` when formatting. Both now report `Input path 'x' is an unsupported file type.`, `Input path 'x' not found.` and `No input path provided. Call with --help for usage information.` [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- Breaking: a single file that `.fantomasignore` matches is reported the same way as an ignored file found while walking a folder. `fantomas A.fs` on an ignored file printed nothing unless `--verbosity d` was given, where `fantomas ./folder` containing only that file printed `A.fs was ignored.` Both now print it. A `--check` run reports the files it ignored at detailed verbosity whether they were named directly or found in a folder, where before only a directly named file was reported. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- At detailed verbosity, a run writing to `--out` now notes a file it found already formatted, as a run formatting in place always did. Both paths decide what formatting came to in the same place, so they say the same things about it. [#3406](https://github.com/fsprojects/fantomas/pull/3406) ### Fixed @@ -22,6 +25,11 @@ - `--out ` failed with `Failed to format file` and exit code 1 when the folder of the given path did not exist. Fantomas now creates it, along with the subfolders that mirroring an input folder needs. [#3403](https://github.com/fsprojects/fantomas/pull/3403) - `--out` naming the input folder under a different spelling, such as `fantomas src --out ./src`, emptied every file it was given. The output file was opened, and therefore truncated, before the input was read. Nothing is written now until formatting has produced the text to write, which also leaves the previous output in place when formatting fails. [#3403](https://github.com/fsprojects/fantomas/pull/3403) - `--out` pointing inside the input folder, such as `fantomas src --out src/formatted`, formatted the previous run's output again and nested it one folder deeper on every run. The output folder is left out of the input scan. [#3403](https://github.com/fsprojects/fantomas/pull/3403) +- `fantomas src/ --out src` formatted nothing and reported an empty table, where `fantomas src --out src` formatted the folder in place. A trailing separator made the two paths compare as different places, so every file below the input folder was taken for a previous run's output and skipped. The same applied to `fantomas src --out src/`. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- A file whose extension is not lowercase, such as `A.FS`, was refused as an unsupported file type, and one found while walking a folder was skipped. The extension is now compared without case, which is what a volume that ignores case, as macOS and Windows usually do, means by the same file. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- Given several input paths, a folder whose name contains a dot, such as `fantomas my.stuff src`, was taken for a file and reported as `Failed to format file`. A file with no extension was taken for a folder. Which one a path is, is now asked of the file system rather than guessed from the name. A single input path was already classified this way. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- A `.fantomasignore` pattern that cannot be matched against a path reported the raw exception, with its stack trace, through `%A`. It now names the file and the ignore file that could not be told apart, and keeps the exception for detailed verbosity. [#3406](https://github.com/fsprojects/fantomas/pull/3406) +- `--profile` reported `Line count: 0` for a file whose line endings are not the ones the platform uses, because it counted occurrences of the platform's newline rather than line breaks. A file saved with line feeds counted nothing on Windows, and one saved with carriage returns counted nothing elsewhere. [#3406](https://github.com/fsprojects/fantomas/pull/3406) ## [8.0.0-alpha-014] - 2026-08-20 diff --git a/build.fsx b/build.fsx index 5a7a26b2a4..3f1ada5429 100755 --- a/build.fsx +++ b/build.fsx @@ -29,8 +29,25 @@ let packagesDir = artifactsDir "package" "release" let analysisReportsDir = __SOURCE_DIRECTORY__ "analysisreports" let coverageReportDir = __SOURCE_DIRECTORY__ "coveragereport" -let coverageXml = - __SOURCE_DIRECTORY__ "src" "Fantomas.Core.Tests" "coverage.xml" +/// Every test project, by name. Each writes its raw coverage beside its own project file. +let coverageProjects: string list = + [ "Fantomas.Core.Tests"; "Fantomas.Tests"; "Fantomas.Client.Tests" ] + +let coverageXmlFiles: string list = + coverageProjects + |> List.map (fun (name: string) -> __SOURCE_DIRECTORY__ "src" name "coverage.xml") + +/// Run one test project under AltCover, measuring the one assembly it is there to exercise. +/// +/// The filter is a negative lookahead: instrument that assembly and nothing else, which keeps the +/// generated Fantomas.FCS parser and the test assembly itself out of the report and makes the run +/// fast. It cannot name several assemblies at once, because AltCover reads `|` as the separator +/// between filters rather than as alternation, so each project is run with its own. +let coverageCommand (name: string) (assemblyPattern: string) : string = + let project: string = __SOURCE_DIRECTORY__ "src" name $"{name}.fsproj" + + $"dotnet test {project} -c Release /p:AltCover=true " + + $"\"/p:AltCoverAssemblyFilter=^(?!{assemblyPattern}$)\"" let benchmarkAssembly = binDir "Fantomas.Benchmarks" "release" "Fantomas.Benchmarks.dll" @@ -108,29 +125,54 @@ pipeline "Benchmark" { runIfOnlySpecified true } -// Line and branch coverage for Fantomas.Core, via AltCover's MSBuild integration. +// Line and branch coverage for the three projects Fantomas ships, via AltCover's MSBuild +// integration. Every test project is run under AltCover, each measuring the one assembly it is +// there to exercise, and ReportGenerator merges the three results into a single report. // -// The filter is a negative lookahead: instrument Fantomas.Core and nothing else, which keeps the -// generated Fantomas.FCS parser (and the test assembly itself) out of the report and makes the -// run fast. AltCover writes OpenCover XML, which is for tooling rather than reading, so -// ReportGenerator turns it into a browsable HTML report afterwards. +// So `Fantomas.Core`'s figure comes from `Fantomas.Core.Tests` alone, even though `Fantomas.Tests` +// exercises Core heavily through real formatting. Core is understated here rather than wrong. +// +// The filter is a negative lookahead naming the three assemblies to instrument. Everything else +// is left alone, which keeps the generated Fantomas.FCS parser and the test assemblies +// themselves out of the report. AltCover writes OpenCover XML, which is for tooling rather than +// reading, so ReportGenerator turns it into a browsable HTML report afterwards. +// +// A test that starts the fantomas process, as those in Fantomas.Tests/Integration do, adds +// nothing here, because the child process is not instrumented. That is the point rather than a +// flaw: what this measures is how much of the tool can be reached without starting one. // // Produces: -// src/Fantomas.Core.Tests/coverage.xml raw OpenCover XML -// coveragereport/index.html browsable report, per file and per line +// src//coverage.xml raw OpenCover XML, one per test project +// coveragereport/index.html browsable report, per file and per line pipeline "Coverage" { workingDir __SOURCE_DIRECTORY__ stage "RestoreTools" { run "dotnet tool restore" } - stage "Clean" { run (cleanFolders [| coverageReportDir |]) } + + stage "Clean" { + run (cleanFolders [| coverageReportDir |]) + // A stale coverage.xml from an earlier run would otherwise be merged into the report. + run (fun _ -> + async { + for file in coverageXmlFiles do + if File.Exists file then + File.Delete file + + return 0 + }) + } stage "Coverage" { - run - @"dotnet test src/Fantomas.Core.Tests/Fantomas.Core.Tests.fsproj -c Release /p:AltCover=true ""/p:AltCoverAssemblyFilter=^(?!Fantomas\.Core$)""" + run (coverageCommand "Fantomas.Core.Tests" @"Fantomas\.Core") + run (coverageCommand "Fantomas.Tests" "fantomas") + run (coverageCommand "Fantomas.Client.Tests" @"Fantomas\.Client") } stage "Report" { - run - $"dotnet reportgenerator -reports:{coverageXml} -targetdir:{coverageReportDir} -reporttypes:Html;TextSummary" + run ( + $"dotnet reportgenerator -reports:{String.Join(';', coverageXmlFiles)} " + + $"-targetdir:{coverageReportDir} -reporttypes:Html;TextSummary" + ) + run (fun _ -> async { let summary = coverageReportDir "Summary.txt" diff --git a/docs/docs/end-users/UpgradeGuide.md b/docs/docs/end-users/UpgradeGuide.md index 5add0f0598..c79a66a3ce 100644 --- a/docs/docs/end-users/UpgradeGuide.md +++ b/docs/docs/end-users/UpgradeGuide.md @@ -102,6 +102,11 @@ fsharp_experimental_stroustrup_style = true - A file that cannot be parsed is reported with the position of each diagnostic instead of `Could not parse the file.`, one line per diagnostic in the shape `src/A.fs(3,9): error FS0583: Unmatched '('`, followed by the source around the failure with a caret under it. `--check` reported the same failure as an exception dump with a stack trace and now uses this as well. A script that matched on `Could not parse the file.` needs to match on the new text. - The `--help` page is written by Fantomas instead of by Argu, and `-h` is accepted alongside `--help`. An argument error prints its complaint on standard error followed by a pointer to `--help`, where it used to print Argu's usage block. - `--out` now mirrors the structure of the input folder, and creates the folders it needs. +- The message for an input path Fantomas cannot work with is the same whether the run formats or checks. `--check` reported `Input path 'x' is unsupported file type` and `Input path 'x' not found` without a full stop, and a run with no input path at all said `Input path is missing.` when formatting and `No input path provided.` when checking. All of them now read `Input path 'x' is an unsupported file type.`, `Input path 'x' not found.` and `No input path provided. Call with --help for usage information.` A script matching on the old text needs updating. +- A file whose extension is not lowercase, such as `A.FS`, is now formatted. Up to `v7` it was refused as an unsupported file type when named directly, and passed over when found while walking a folder, so a folder run can now touch files it used to leave alone. +- `fantomas src/ --out src` now formats the folder in place. Up to `v7` a trailing separator made the two paths count as different places, so every file was taken for the previous run's output and skipped: the run printed an empty table and exited 0 without formatting anything. The same applied to `fantomas src --out src/`. A build step that used either spelling was doing nothing and will start doing the work. +- Several input paths are told apart by asking the file system rather than by whether they carry an extension. Up to `v7`, `fantomas my.stuff src` reported `Failed to format file: my.stuff` and exited 1, because a folder whose name contains a dot was taken for a file. It now formats the folder. The converse also held: a path with no extension was taken for a folder, so naming a file that way ended the whole run rather than that one file. +- A single file matched by `.fantomasignore` reports `A.fs was ignored.` on standard out. Up to `v7` it printed nothing unless `--verbosity d` was given, even though a folder run whose only file was that same one reported it at normal verbosity. The two now agree. #### `--out ` mirrors the input folder diff --git a/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj b/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj index b1ea8b9214..c3de2d9434 100644 --- a/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj +++ b/src/Fantomas.Client.Tests/Fantomas.Client.Tests.fsproj @@ -18,6 +18,7 @@ + diff --git a/src/Fantomas.Client.Tests/packages.lock.json b/src/Fantomas.Client.Tests/packages.lock.json index e65142e02b..4cb3d993c4 100644 --- a/src/Fantomas.Client.Tests/packages.lock.json +++ b/src/Fantomas.Client.Tests/packages.lock.json @@ -2,6 +2,12 @@ "version": 2, "dependencies": { "net10.0": { + "altcover": { + "type": "Direct", + "requested": "[9.0.102, )", + "resolved": "9.0.102", + "contentHash": "q3Rf5t0M9kXlcO5qhsaAe6NrFSNd5enrhKmF/Ezgmomqw34PbUTbRSYjSDNhS3YGDyUrPTkyPn14EfLDJWztcA==" + }, "CliWrap": { "type": "Direct", "requested": "[3.10.0, )", diff --git a/src/Fantomas.Tests/ArgumentsTests.fs b/src/Fantomas.Tests/ArgumentsTests.fs new file mode 100644 index 0000000000..0dbdd40d39 --- /dev/null +++ b/src/Fantomas.Tests/ArgumentsTests.fs @@ -0,0 +1,125 @@ +module Fantomas.Tests.ArgumentsTests + +open System.IO.Abstractions +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas.Arguments +open Fantomas.Logging +open Fantomas.Tests.TestHelpers + +[] +let ``no input path at all is unspecified`` () = + classifyInputPath (MockFileSystem()) None |> shouldEqual InputPath.Unspecified + +[] +let ``a path that is not there is reported as not found`` () = + let fs: IFileSystem = MockFileSystem() + let missing: string = fs.Path.Combine(mockRoot fs, "nope.fs") + + classifyInputPath fs (Some [ missing ]) + |> shouldEqual (InputPath.NotFound missing) + +[] +let ``an existing folder is a folder`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + [ fs.Path.Combine(src, "A.fs") ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ src ]) |> shouldEqual (InputPath.Folder src) + +[] +let ``an existing F# file is a file`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "src", "A.fs") + [ file ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ file ]) |> shouldEqual (InputPath.File file) + +[] +let ``an existing file Fantomas does not format is reported as such`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "src", "README.md") + [ file ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ file ]) + |> shouldEqual (InputPath.NoFSharpFile file) + +[] +let ``several paths are told apart into files and folders`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "A.fs") + let folder: string = fs.Path.Combine(root, "src") + [ file; fs.Path.Combine(folder, "B.fs") ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ file; folder ]) + |> shouldEqual (InputPath.Multiple([ file ], [ folder ])) + +[] +let ``a folder with a dot in its name is still a folder`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let folder: string = fs.Path.Combine(root, "my.stuff") + let file: string = fs.Path.Combine(root, "A.fs") + [ file; fs.Path.Combine(folder, "B.fs") ] |> makeFileHierarchy fs + + // Guessing from the extension called this a file, and formatting it then failed. + classifyInputPath fs (Some [ folder; file ]) + |> shouldEqual (InputPath.Multiple([ file ], [ folder ])) + +[] +let ``a file with no extension is still a file`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "Makefile") + let folder: string = fs.Path.Combine(root, "src") + [ file; fs.Path.Combine(folder, "B.fs") ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ file; folder ]) + |> shouldEqual (InputPath.Multiple([ file ], [ folder ])) + +[] +let ``one missing path among several is reported rather than the rest being used`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let present: string = fs.Path.Combine(root, "A.fs") + let missing: string = fs.Path.Combine(root, "B.fs") + [ present ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ present; missing ]) + |> shouldEqual (InputPath.NotFound missing) + +[] +let ``several paths keep the order they were given`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let a: string = fs.Path.Combine(root, "A.fs") + let b: string = fs.Path.Combine(root, "B.fs") + [ a; b ] |> makeFileHierarchy fs + + classifyInputPath fs (Some [ a; b ]) + |> shouldEqual (InputPath.Multiple([ a; b ], [])) + +[] +[] +[] +[] +[] +let ``normal verbosity is the default and its spellings`` (value: string) = + let given: string option = Option.ofObj value + parseVerbosity given |> shouldEqual (Some VerbosityLevel.Normal) + +[] +[] +[] +[] +let ``detailed verbosity and its spellings`` (value: string) = + parseVerbosity (Some value) |> shouldEqual (Some VerbosityLevel.Detailed) + +[] +[] +[] +[] +let ``a verbosity Fantomas does not know is refused`` (value: string) = + parseVerbosity (Some value) |> shouldEqual None diff --git a/src/Fantomas.Tests/CheckCommandTests.fs b/src/Fantomas.Tests/CheckCommandTests.fs new file mode 100644 index 0000000000..53f4bc1840 --- /dev/null +++ b/src/Fantomas.Tests/CheckCommandTests.fs @@ -0,0 +1,155 @@ +module Fantomas.Tests.CheckCommandTests + +open System.IO.Abstractions +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas +open Fantomas.Arguments +open Fantomas.CheckCommand +open Fantomas.CommandResult +open Fantomas.Tests.TestHelpers + +[] +let private NeedsFormatting = "let a = 1\n" + +[] +let private Formatted = "let a = 1\n" + +let private write (fs: IFileSystem) (path: string) (content: string) : unit = + fs.FileInfo.New(path).Directory.Create() + fs.File.WriteAllText(path, content) + +let private check (fs: IFileSystem) (ignoreFile: IgnoreFile option) (inputPath: InputPath) : CheckCommandResult = + let recorded: RecordedRun = recordingEnvironment fs ignoreFile + runCheckCommand recorded.Environment inputPath + +let private completed (result: CheckCommandResult) : string list * CheckResult = + match result with + | CheckCommandResult.Completed(ignored, checkResult) -> ignored, checkResult + | other -> failwith $"Expected the check to complete, got %A{other}" + +[] +let ``a path that is not there is refused before anything is read`` () = + check (MockFileSystem()) None (InputPath.NotFound "A.fs") + |> shouldEqual (CheckCommandResult.InvalidInput(InputProblem.NotFound "A.fs")) + +[] +let ``no input path is refused`` () = + check (MockFileSystem()) None InputPath.Unspecified + |> shouldEqual (CheckCommandResult.InvalidInput InputProblem.NoPathGiven) + +[] +let ``a file Fantomas does not format is refused`` () = + check (MockFileSystem()) None (InputPath.NoFSharpFile "A.md") + |> shouldEqual (CheckCommandResult.InvalidInput(InputProblem.UnsupportedFileType "A.md")) + +[] +let ``a file that is already formatted needs nothing`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file Formatted + + let ignored, result = check fs None (InputPath.File file) |> completed + + ignored |> shouldBeEmpty + result.IsValid |> shouldEqual true + +[] +let ``a file that needs formatting is named`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file NeedsFormatting + + let _, result = check fs None (InputPath.File file) |> completed + + result.Formatted |> shouldEqual [ file ] + result.HasErrors |> shouldEqual false + result.NeedsFormatting |> shouldEqual true + +[] +let ``a check writes nothing, whatever it finds`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file NeedsFormatting + + check fs None (InputPath.File file) |> completed |> ignore + + fs.File.ReadAllText file |> shouldEqual NeedsFormatting + +[] +let ``a file that cannot be parsed is an error rather than a file needing formatting`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file "let a = (" + + let _, result = check fs None (InputPath.File file) |> completed + + result.HasErrors |> shouldEqual true + result.Errors |> List.map fst |> shouldEqual [ file ] + +[] +let ``every file below a folder is checked`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let needs: string = fs.Path.Combine(src, "Needs.fs") + write fs needs NeedsFormatting + write fs (fs.Path.Combine(src, "nested", "Fine.fs")) Formatted + + let _, result = check fs None (InputPath.Folder src) |> completed + + result.Formatted |> shouldEqual [ needs ] + +[] +let ``files and folders named together are all checked`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let loose: string = fs.Path.Combine(root, "Loose.fs") + let src: string = fs.Path.Combine(root, "src") + let inFolder: string = fs.Path.Combine(src, "A.fs") + write fs loose NeedsFormatting + write fs inFolder Formatted + + let _, result = check fs None (InputPath.Multiple([ loose ], [ src ])) |> completed + + result.Formatted |> shouldEqual [ loose ] + +[] +let ``an ignored file is neither checked nor counted, and is reported as ignored`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "A.fs") + write fs file NeedsFormatting + fs.File.WriteAllText(fs.Path.Combine(root, IgnoreFile.IgnoreFileName), "A.fs") + + let ignoreFile: IgnoreFile option = + IgnoreFile.findInDirectory fs root (IgnoreFile.loadIgnoreList fs) + + let ignored, result = check fs ignoreFile (InputPath.File file) |> completed + + ignored |> shouldEqual [ file ] + result.IsValid |> shouldEqual true + +[] +let ``a difference in the number of newlines does make a file need formatting, 2461`` () = + // Comparing without line endings strips carriage returns, not blank lines, so a trailing one + // still counts. + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file "module A\n\n" + + let _, result = check fs None (InputPath.File file) |> completed + + result.NeedsFormatting |> shouldEqual true + +[] +let ``line endings alone do not make a file need formatting`` () = + // A check compares without line endings, so a file written with the other platform's + // newlines is not reported as needing to be rewritten. + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file "let a = 1\r\n" + + let _, result = check fs None (InputPath.File file) |> completed + + result.IsValid |> shouldEqual true diff --git a/src/Fantomas.Tests/CheckTests.fs b/src/Fantomas.Tests/CheckTests.fs deleted file mode 100644 index d98d2e3858..0000000000 --- a/src/Fantomas.Tests/CheckTests.fs +++ /dev/null @@ -1,53 +0,0 @@ -module Fantomas.Core.Tests.CheckTests - -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers -open Fantomas.Format - -[] -let NeedsFormatting = - """module A - -let a = 5 -let b= a + 123 -""" - -[] -let WithErrors = """let a""" - -[] -let CorrectlyFormatted = - """module A -""" - -[] -let ``formatted files should report no changes`` () = - use fileFixture = new TemporaryFileCodeSample(CorrectlyFormatted) - - let result = - fileFixture.Filename |> Seq.singleton |> checkCode |> Async.RunSynchronously - - result.NeedsFormatting |> should equal false - result.IsValid |> should equal true - -[] -let ``files with errors should report an internal error`` () = - use fileFixture = new TemporaryFileCodeSample(WithErrors) - - let result = - fileFixture.Filename |> Seq.singleton |> checkCode |> Async.RunSynchronously - - result.HasErrors |> should equal true - List.length result.Errors |> should equal 1 - -[] -let ``files that need formatting should report that they need to be formatted`` () = - use fileFixture = new TemporaryFileCodeSample(NeedsFormatting) - - let result = - fileFixture.Filename |> Seq.singleton |> checkCode |> Async.RunSynchronously - - result.HasErrors |> should equal false - result.NeedsFormatting |> should equal true - List.length result.Formatted |> should equal 1 diff --git a/src/Fantomas.Tests/DiagnosticsTests.fs b/src/Fantomas.Tests/DiagnosticsTests.fs index 2d75828dfc..b97ca177d7 100644 --- a/src/Fantomas.Tests/DiagnosticsTests.fs +++ b/src/Fantomas.Tests/DiagnosticsTests.fs @@ -217,5 +217,5 @@ let ``without source there is no snippet`` () = [] let ``an exception that is not a parse failure is not this module's to describe`` () = - Diagnostics.describeParseFailure "bad.fs" source (exn "boom") + Diagnostics.describeParseFailure "bad.fs" (fun () -> source) (exn "boom") |> should equal None diff --git a/src/Fantomas.Tests/Fantomas.Tests.fsproj b/src/Fantomas.Tests/Fantomas.Tests.fsproj index 6c5009575b..74177ac991 100644 --- a/src/Fantomas.Tests/Fantomas.Tests.fsproj +++ b/src/Fantomas.Tests/Fantomas.Tests.fsproj @@ -16,21 +16,20 @@ + + + + + + + - - - + - - - - - - @@ -42,5 +41,6 @@ + \ No newline at end of file diff --git a/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs new file mode 100644 index 0000000000..9e628addc2 --- /dev/null +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -0,0 +1,401 @@ +module Fantomas.Tests.FormatCommandTests + +open System.Text +open System.IO.Abstractions +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.CommandResult +open Fantomas.FormatCommand +open Fantomas.Tests.TestHelpers + +[] +let private NeedsFormatting = "let a = 1\n" + +[] +let private Formatted = "let a = 1\n" + +/// Run the format command over the given file system, keeping what it wrote. +let private formatWith + (settings: CliSettings) + (ignoreFile: IgnoreFile option) + (fs: IFileSystem) + (inputPath: InputPath) + (outputPath: OutputPath) + : FormatCommandResult = + let recorded: RecordedRun = recordingEnvironment fs ignoreFile + runFormatCommand recorded.Environment settings inputPath outputPath + +let private format (fs: IFileSystem) (inputPath: InputPath) (outputPath: OutputPath) : FormatCommandResult = + formatWith defaultSettings None fs inputPath outputPath + +/// Run the format command, keeping both the result and what it logged. +let private formatLogging + (settings: CliSettings) + (fs: IFileSystem) + (inputPath: InputPath) + (outputPath: OutputPath) + : FormatCommandResult * CollectedLog = + let recorded: RecordedRun = recordingEnvironment fs None + + let result: FormatCommandResult = + runFormatCommand recorded.Environment settings inputPath outputPath + + result, recorded.Log() + +let private write (fs: IFileSystem) (path: string) (content: string) : unit = + fs.FileInfo.New(path).Directory.Create() + fs.File.WriteAllText(path, content) + +let private read (fs: IFileSystem) (path: string) : string = + fs.File.ReadAllText path |> String.normalizeNewLine + +let private results (result: FormatCommandResult) : FormatResult array = + match result with + | FormatCommandResult.Completed results -> results + | other -> failwith $"Expected the run to complete, got %A{other}" + +[] +let ``a badly formatted file is rewritten where it lies`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file NeedsFormatting + + let result: FormatResult array = + format fs (InputPath.File file) OutputPath.NotKnown |> results + + result |> Array.length |> shouldEqual 1 + read fs file |> shouldEqual Formatted + +[] +let ``a file that is already formatted is reported as unchanged`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file Formatted + + match format fs (InputPath.File file) OutputPath.NotKnown |> results with + | [| FormatResult.Unchanged(f, _) |] -> f |> shouldEqual file + | other -> failwith $"Expected one unchanged file, got %A{other}" + + read fs file |> shouldEqual Formatted + +[] +let ``an output path is written to and the input is left alone`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + write fs input NeedsFormatting + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + read fs input |> shouldEqual NeedsFormatting + read fs output |> shouldEqual Formatted + +[] +let ``an output file whose folder does not exist yet is still written`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "not", "there", "yet", "A.fs") + write fs input NeedsFormatting + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + read fs output |> shouldEqual Formatted + +[] +let ``an output folder mirrors the input tree rather than flattening it`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + let out: string = fs.Path.Combine(root, "out") + // Same file name in two folders: flattening would let one overwrite the other. + write fs (fs.Path.Combine(src, "A.fs")) "let a = 1\n" + write fs (fs.Path.Combine(src, "nested", "A.fs")) "let b = 2\n" + + format fs (InputPath.Folder src) (OutputPath.IO out) |> results |> ignore + + read fs (fs.Path.Combine(out, "A.fs")) |> shouldEqual "let a = 1\n" + read fs (fs.Path.Combine(out, "nested", "A.fs")) |> shouldEqual "let b = 2\n" + +[] +let ``an output folder is created even when there is nothing to put in it`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + let out: string = fs.Path.Combine(root, "out") + fs.Directory.CreateDirectory src |> ignore + + format fs (InputPath.Folder src) (OutputPath.IO out) |> results |> ignore + + fs.Directory.Exists out |> shouldEqual true + +[] +let ``an ignored file is not written and is reported as ignored`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + write fs file NeedsFormatting + fs.File.WriteAllText(fs.Path.Combine(root, IgnoreFile.IgnoreFileName), "A.fs") + + let ignoreFile: IgnoreFile option = + IgnoreFile.findInDirectory fs root (IgnoreFile.loadIgnoreList fs) + + let result: FormatResult array = + formatWith defaultSettings ignoreFile fs (InputPath.File file) (OutputPath.IO output) + |> results + + result |> shouldEqual [| FormatResult.IgnoredFile file |] + read fs file |> shouldEqual NeedsFormatting + fs.File.Exists output |> shouldEqual false + +[] +let ``a file that cannot be parsed is reported as an error and left alone`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + let broken: string = "let a = (" + write fs file broken + + match format fs (InputPath.File file) OutputPath.NotKnown |> results with + | [| FormatResult.Error(f, _) |] -> f |> shouldEqual file + | other -> failwith $"Expected one error, got %A{other}" + + read fs file |> shouldEqual broken + +[] +let ``a byte order mark the input carried is put back on the output`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + fs.FileInfo.New(input).Directory.Create() + fs.File.WriteAllText(input, NeedsFormatting, UTF8Encoding true) + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + let preamble: byte array = Encoding.UTF8.GetPreamble() + + fs.File.ReadAllBytes output + |> Array.truncate preamble.Length + |> shouldEqual preamble + +[] +let ``content already at the output path is replaced when the input carries a mark`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + fs.FileInfo.New(input).Directory.Create() + fs.File.WriteAllText(input, NeedsFormatting, UTF8Encoding true) + // A mark used to mean the output was opened without being truncated, so the tail of whatever + // was there before survived a write of shorter content. + write fs output "// leftovers leftovers leftovers leftovers leftovers leftovers\n" + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + read fs output |> shouldEqual Formatted + + let preamble: byte array = Encoding.UTF8.GetPreamble() + + fs.File.ReadAllBytes output + |> Array.truncate preamble.Length + |> shouldEqual preamble + +[] +let ``a file without a byte order mark does not gain one`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + write fs input NeedsFormatting + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + let preamble: byte array = Encoding.UTF8.GetPreamble() + + fs.File.ReadAllBytes output + |> Array.truncate preamble.Length + |> shouldNotEqual preamble + +[] +let ``several files and folders are all formatted where they lie`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let loose: string = fs.Path.Combine(root, "Loose.fs") + let src: string = fs.Path.Combine(root, "src") + let inFolder: string = fs.Path.Combine(src, "A.fs") + write fs loose NeedsFormatting + write fs inFolder NeedsFormatting + + format fs (InputPath.Multiple([ loose ], [ src ])) OutputPath.NotKnown + |> results + |> Array.length + |> shouldEqual 2 + + read fs loose |> shouldEqual Formatted + read fs inFolder |> shouldEqual Formatted + +[] +let ``content already at the output path is replaced rather than written over`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + write fs input NeedsFormatting + // Opening the output without truncating it left the tail of whatever was there before. + write fs output "// leftovers leftovers leftovers leftovers leftovers leftovers\n" + + format fs (InputPath.File input) (OutputPath.IO output) |> results |> ignore + + read fs output |> shouldEqual Formatted + +[] +let ``with force, output that is not valid F# is written anyway`` () = + // The day this fails because Fantomas can format the file is the day it can be deleted. + let source: string = + System.IO.Path.Combine(__SOURCE_DIRECTORY__, "..", "..", "tests", "data", "CheckDeclarations.fs") + |> System.IO.Path.GetFullPath + |> System.IO.File.ReadAllText + + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "CheckDeclarations.fs") + let output: string = fs.Path.Combine(root, "out", "CheckDeclarations.fs") + write fs input source + + let settings: CliSettings = { defaultSettings with Force = true } + + match + formatWith settings None fs (InputPath.File input) (OutputPath.IO output) + |> results + with + | [| FormatResult.Formatted _ |] -> fs.File.Exists output |> shouldEqual true + | other -> failwith $"Expected the invalid output to be written anyway, got %A{other}" + +[] +let ``without force, output that is not valid F# is not written`` () = + let source: string = + System.IO.Path.Combine(__SOURCE_DIRECTORY__, "..", "..", "tests", "data", "CheckDeclarations.fs") + |> System.IO.Path.GetFullPath + |> System.IO.File.ReadAllText + + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "CheckDeclarations.fs") + let output: string = fs.Path.Combine(root, "out", "CheckDeclarations.fs") + write fs input source + + // Without force the invalid output is turned into an error rather than reported as invalid, + // so that the caller has one kind of failure to report rather than two. + match format fs (InputPath.File input) (OutputPath.IO output) |> results with + | [| FormatResult.Error(f, error) |] -> + f |> shouldEqual input + error.Message |> shouldContainText "leads to invalid F# code" + fs.File.Exists output |> shouldEqual false + | other -> failwith $"Expected the invalid output to be withheld, got %A{other}" + +[] +let ``a run says what it is doing at detailed verbosity`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "A.fs") + let output: string = fs.Path.Combine(root, "out", "A.fs") + write fs input NeedsFormatting + + let _, log = + formatLogging defaultSettings fs (InputPath.File input) (OutputPath.IO output) + + log.Debug |> shouldContain $"Processing %s{input}" + log.Debug |> shouldContain $"%s{output} has been written." + +[] +let ``an unchanged file says so at detailed verbosity`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file Formatted + + let _, log = + formatLogging defaultSettings fs (InputPath.File file) OutputPath.NotKnown + + log.Debug |> shouldContain $"'%s{file}' was unchanged" + +[] +let ``with force, the output being invalid is said out loud`` () = + let source: string = + System.IO.Path.Combine(__SOURCE_DIRECTORY__, "..", "..", "tests", "data", "CheckDeclarations.fs") + |> System.IO.Path.GetFullPath + |> System.IO.File.ReadAllText + + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let input: string = fs.Path.Combine(root, "CheckDeclarations.fs") + let output: string = fs.Path.Combine(root, "out", "CheckDeclarations.fs") + write fs input source + + let settings: CliSettings = { defaultSettings with Force = true } + let _, log = formatLogging settings fs (InputPath.File input) (OutputPath.IO output) + + log.Information |> shouldContain $"%s{input} was not valid after formatting." + +[] +let ``profiling collects a line count and a time for the file it formatted`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file "let a = 1\nlet b = 2\n" + + let settings: CliSettings = { defaultSettings with Profile = true } + + match formatWith settings None fs (InputPath.File file) OutputPath.NotKnown |> results with + | [| FormatResult.Formatted(_, _, Some profile) |] -> profile.LineCount |> shouldBeGreaterThan 0 + | other -> failwith $"Expected a profiled result, got %A{other}" + +[] +let ``the line count does not depend on which line endings the file uses`` () = + // It used to count occurrences of the platform's newline, so a file written with line feeds + // counted zero lines on Windows and a file written with carriage returns counted zero on + // anything else. + let lineCountOf (content: string) : int = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file content + + let settings: CliSettings = { defaultSettings with Profile = true } + + match formatWith settings None fs (InputPath.File file) OutputPath.NotKnown |> results with + | [| FormatResult.Formatted(_, _, Some profile) |] -> profile.LineCount + | other -> failwith $"Expected a profiled result, got %A{other}" + + lineCountOf "let a = 1\nlet b = 2\n" |> shouldEqual 2 + lineCountOf "let a = 1\r\nlet b = 2\r\n" |> shouldEqual 2 + +[] +let ``nothing is profiled unless profiling was asked for`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + write fs file NeedsFormatting + + match format fs (InputPath.File file) OutputPath.NotKnown |> results with + | [| FormatResult.Formatted(_, _, None) |] -> () + | other -> failwith $"Expected no profile, got %A{other}" + +[] +let ``no input path at all is refused`` () = + format (MockFileSystem()) InputPath.Unspecified OutputPath.NotKnown + |> shouldEqual (FormatCommandResult.InvalidInput InputProblem.NoPathGiven) + +[] +let ``a file Fantomas does not format is refused`` () = + format (MockFileSystem()) (InputPath.NoFSharpFile "A.md") OutputPath.NotKnown + |> shouldEqual (FormatCommandResult.InvalidInput(InputProblem.UnsupportedFileType "A.md")) + +[] +let ``an unusable input path never reaches the file system`` () = + let fs: IFileSystem = MockFileSystem() + + format fs (InputPath.NotFound "A.fs") OutputPath.NotKnown + |> shouldEqual (FormatCommandResult.InvalidInput(InputProblem.NotFound "A.fs")) diff --git a/src/Fantomas.Tests/HelpPageTests.fs b/src/Fantomas.Tests/HelpPageTests.fs new file mode 100644 index 0000000000..9f6599945e --- /dev/null +++ b/src/Fantomas.Tests/HelpPageTests.fs @@ -0,0 +1,106 @@ +module Fantomas.Tests.HelpPageTests + +open System.Text.RegularExpressions +open NUnit.Framework +open FsUnitTyped +open Fantomas.Core +open Fantomas.HelpPage + +let private plainPage: string = render Palette.NoColour |> String.concat "\n" + +/// Any select graphic rendition sequence, whatever colour it sets. +let private anyEscapeSequence: Regex = Regex(@"\[[0-9;]*m") + +[] +let ``the page lists every flag`` () = + for flag in + [ "--check" + "--out" + "--force" + "--profile" + "--daemon" + "--verbosity" + "--version" + "--help" ] do + plainPage |> shouldContainText flag + +[] +let ``the page lists the short forms of the flags that have one`` () = + plainPage |> shouldContainText "-v" + plainPage |> shouldContainText "-h" + +[] +let ``the page carries the version`` () = + let versionNumber: string = CodeFormatter.GetVersion().Split('+').[0] + plainPage |> shouldContainText versionNumber + +[] +let ``the commit hash is trimmed to the short form git itself shows`` () = + match CodeFormatter.GetVersion().Split('+') with + | [| _; commit |] when commit.Length > 9 -> + plainPage |> shouldContainText (commit.Substring(0, 9)) + plainPage |> shouldNotContainText commit + | _ -> Assert.Ignore "This build's version carries no commit hash to trim" + +[] +let ``the page links the documentation, the Discord and the llms files`` () = + for url in + [ "https://fsprojects.github.io/fantomas/docs" + "https://fsprojects.github.io/fantomas/docs/end-users/Configuration.html" + "https://discord.com/channels/196693847965696000/1493226271767924747" + "https://fsprojects.github.io/fantomas/llms.txt" + "https://fsprojects.github.io/fantomas/llms-full.txt" ] do + plainPage |> shouldContainText url + +[] +let ``the page says what an input path may be`` () = + for extension in [ ".fs"; ".fsi"; ".fsx"; ".ml"; ".mli" ] do + plainPage |> shouldContainText extension + + plainPage |> shouldContainText ".editorconfig" + plainPage |> shouldContainText ".fantomasignore" + +[] +let ``a page without colour carries no escape sequences`` () = + anyEscapeSequence.IsMatch plainPage |> shouldEqual false + +[] +let ``a page with eight bit colour uses the 256 colour codes`` () = + let page: string = render Palette.EightBit |> String.concat "\n" + + // 38;5;38 is the closest 256 colour to the blue the website uses. + page |> shouldContainText "[1;38;5;38m" + +[] +let ``a page with four bit colour falls back to the basic codes`` () = + let page: string = render Palette.FourBit |> String.concat "\n" + + page |> shouldContainText "[1;36m" + page |> shouldNotContainText "38;5;" + +[] +let ``colour changes what is written but not what it says`` () = + let coloured: string = render Palette.EightBit |> String.concat "\n" + + anyEscapeSequence.Replace(coloured, "") |> shouldEqual plainPage + +[] +let ``the two column layout lines up whether or not there is colour`` () = + // The page is laid out in fixed columns, and a decorated string still has to measure as the + // text it decorates or the right hand column moves. + let widths (palette: Palette) : int list = + render palette + |> List.map (fun (line: string) -> anyEscapeSequence.Replace(line, "").Length) + + widths Palette.EightBit |> shouldEqual (widths Palette.NoColour) + +[] +let ``an argument error is reduced to the line that carries the complaint`` () = + let arguMessage: string = + "ERROR: missing argument '--out'.\nUSAGE: fantomas [--help] [--check]\n\nOPTIONS:\n --check ..." + + complaint arguMessage |> shouldEqual "ERROR: missing argument '--out'." + +[] +let ``a message with no complaint line is kept whole`` () = + complaint "something else entirely" |> shouldEqual "something else entirely" diff --git a/src/Fantomas.Tests/IgnoreFileTests.fs b/src/Fantomas.Tests/IgnoreFileTests.fs index 45d5177ef6..1364c51bd2 100644 --- a/src/Fantomas.Tests/IgnoreFileTests.fs +++ b/src/Fantomas.Tests/IgnoreFileTests.fs @@ -132,7 +132,7 @@ let ``IgnoreFile.find can find the fantomasignore one layer up from the source f getLoads () |> shouldEqual (Set.ofList [ target ]) [] -let ``IgnoreFile.current' does not load more than once`` () = +let ``IgnoreFile.findInDirectory loads the ignore file above the directory, exactly once`` () = let fs = MockFileSystem() let root = fs.Path.GetTempPath() |> fs.Path.GetPathRoot @@ -144,17 +144,12 @@ let ``IgnoreFile.current' does not load more than once`` () = let loadIgnoreList, getLoads = oneShotLoader (fun _ -> failwith "never called") let ignoreFile = - IgnoreFile.current' fs (fs.Path.GetDirectoryName target) loadIgnoreList + IgnoreFile.findInDirectory fs (fs.Path.GetDirectoryName target) loadIgnoreList - getLoads () |> shouldBeEmpty - - for _ in 1..2 do - let forced = - match ignoreFile.Force() with - | Some f -> f - | None -> failwith $"calling %s{nameof ignoreFile.Force} failed" + match ignoreFile with + | Some found -> found.Location.FullName |> shouldEqual target + | None -> failwith "Expected to find the ignore file above the directory" - forced.Location.FullName |> shouldEqual target - // The second invocation would throw if we were somehow getting the - // singleton wrong and re-invoking the find-and-load. - getLoads () |> shouldEqual (Set.ofList [ target ]) + // oneShotLoader throws on a second load of the same file, so this says the walk up stopped at + // the first ignore file it met rather than carrying on and loading another. + getLoads () |> shouldEqual (Set.ofList [ target ]) diff --git a/src/Fantomas.Tests/Integration/ByteOrderMarkTests.fs b/src/Fantomas.Tests/Integration/ByteOrderMarkTests.fs deleted file mode 100644 index ecd97d159e..0000000000 --- a/src/Fantomas.Tests/Integration/ByteOrderMarkTests.fs +++ /dev/null @@ -1,79 +0,0 @@ -module Fantomas.Tests.Integration.ByteOrderMarkTests - -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers -open System.Text - -[] -let Source = "namespace Company.Product.Feature" - -let private getInitialBytes file = - use file = new FileStream(file, FileMode.Open, FileAccess.Read) - - let mutable bom = Array.zeroCreate 3 - file.Read(bom, 0, 3) |> ignore - bom - -[] -let ``byte-order mark should be preserved, 795`` () = - use fileFixture = new TemporaryFileCodeSample(Source, true) - - let { ExitCode = exitCode } = runFantomasTool [ fileFixture.Filename ] - exitCode |> should equal 0 - - let expectedPreamble = Encoding.UTF8.GetPreamble() - let actualPreamble = getInitialBytes fileFixture.Filename - expectedPreamble |> should equal actualPreamble - -[] -let ``preserve byte-order from original file`` () = - use inputFixture = new TemporaryFileCodeSample(Source, true) - - use outputFixture = new OutputFile() - - let { ExitCode = exitCode } = - [ "--out"; outputFixture.Filename; inputFixture.Filename ] |> runFantomasTool - - exitCode |> should equal 0 - - let expectedPreamble = Encoding.UTF8.GetPreamble() - let actualPreamble = getInitialBytes outputFixture.Filename - expectedPreamble |> should equal actualPreamble - -[] -let ``file without byte-order mark does not gain one`` () = - use inputFixture = new TemporaryFileCodeSample(Source) - - use outputFixture = new OutputFile() - - let { ExitCode = exitCode } = - [ "--out"; outputFixture.Filename; inputFixture.Filename ] |> runFantomasTool - - exitCode |> should equal 0 - - let preamble = Encoding.UTF8.GetPreamble() - let actualPreamble = getInitialBytes outputFixture.Filename - actualPreamble |> should not' (equal preamble) - -[] -let ``content already at the output path is replaced, not written over`` () = - use inputFixture = new TemporaryFileCodeSample(Source, true) - - use outputFixture = new OutputFile() - - // A byte-order mark used to mean the output file was opened without being truncated, so the - // tail of whatever was there before survived a write of shorter content. - File.WriteAllText( - outputFixture.Filename, - "// leftovers leftovers leftovers leftovers leftovers leftovers\n", - Encoding.UTF8 - ) - - let { ExitCode = exitCode } = - [ "--out"; outputFixture.Filename; inputFixture.Filename ] |> runFantomasTool - - exitCode |> should equal 0 - - File.ReadAllText outputFixture.Filename |> should not' (contain "leftovers") diff --git a/src/Fantomas.Tests/Integration/CheckTests.fs b/src/Fantomas.Tests/Integration/CheckTests.fs deleted file mode 100644 index 330cf27c6c..0000000000 --- a/src/Fantomas.Tests/Integration/CheckTests.fs +++ /dev/null @@ -1,148 +0,0 @@ -module Fantomas.Tests.Integration.CheckTests - -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -[] -let NeedsFormatting = - """module A - -let a = 5 -let b= a + 123 -""" - -[] -let WithErrors = """let a =""" - -[] -let CorrectlyFormatted = - """module A -""" - -[] -let ``formatted files should report exit code 0`` () = - use fileFixture = new TemporaryFileCodeSample(CorrectlyFormatted) - - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 0 - -[] -let ``invalid files should report exit code 1`` () = - use fileFixture = new TemporaryFileCodeSample(WithErrors) - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 1 - -[] -let ``non-existing file should report exit code 1`` () = - let { ExitCode = exitCode } = checkCode [ "somenonexistingfile.fs" ] - exitCode |> should equal 1 - -[] -let ``unsupported file should report exit code 1`` () = - use fileFixture = new TemporaryFileCodeSample(CorrectlyFormatted, extension = "txt") - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 1 - -[] -let ``missing file should report exit code 1`` () = - let { ExitCode = exitCode } = checkCode [] - exitCode |> should equal 1 - -[] -let ``files that need formatting should report exit code 99`` () = - use fileFixture = new TemporaryFileCodeSample(NeedsFormatting) - - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 99 - -[] -let ``check with Program.fs file`` () = - let codeSnippet = - """[] -let main _ = 0 -""" - - use fileFixture = new TemporaryFileCodeSample(codeSnippet, fileName = "Program") - - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 0 - -[] -let ``check with different line endings`` () = - let codeSnippet = - """let a = - // some comment - 42 -""" - - let snippetWithOtherLineEndings = - if codeSnippet.Contains("\r\n") then - codeSnippet.Replace("\r\n", "\n") - else - codeSnippet.Replace("\n", "\r\n") - - use fileFixture = new TemporaryFileCodeSample(snippetWithOtherLineEndings) - - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 0 - -[] -let ``check with multiple files`` () = - use fileFixtureOne = new TemporaryFileCodeSample("let a = 0") - - use fileFixtureTwo = new TemporaryFileCodeSample("let b = 1") - - let { ExitCode = exitCode; Output = output } = - checkCode [ fileFixtureOne.Filename; fileFixtureTwo.Filename ] - - exitCode |> should equal 99 - - let needsFormatting = - sprintf "%s needs formatting" (Path.GetFileName(fileFixtureOne.Filename)) - - output |> should contain needsFormatting - -[] -let ``check with file and folder`` () = - use fileFixtureOne = new TemporaryFileCodeSample("let a = 0", subFolder = "sub") - - use fileFixtureTwo = new TemporaryFileCodeSample("let b = 1") - - let { ExitCode = exitCode; Output = output } = - checkCode [ fileFixtureOne.Filename; fileFixtureTwo.Filename ] - - exitCode |> should equal 99 - - let needsFormatting = - sprintf "sub%c%s needs formatting" Path.DirectorySeparatorChar (Path.GetFileName(fileFixtureOne.Filename)) - - output |> should contain needsFormatting - -[] -let ``honor ignore file when processing a folder`` () = - let fileName = "A" - let subFolder = System.Guid.NewGuid().ToString("N") - - use ignoreFixture = - new TemporaryFileCodeSample("let a = 0", fileName = fileName, subFolder = subFolder) - - use inputFixture = new FantomasIgnoreFile("*.fsx") - - let { Output = output } = - runFantomasTool [ "--check"; $".%c{Path.DirectorySeparatorChar}%s{subFolder}" ] - - output |> should not' (contain "ignored") - -[] -let ``check should fail if the number of newlines is different, 2461`` () = - let codeSnippet = - """module A - -""" - - use fileFixture = new TemporaryFileCodeSample(codeSnippet) - - let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] - exitCode |> should equal 99 diff --git a/src/Fantomas.Tests/Integration/DaemonTests.fs b/src/Fantomas.Tests/Integration/DaemonTests.fs index c30be4c1d6..eade9fe542 100644 --- a/src/Fantomas.Tests/Integration/DaemonTests.fs +++ b/src/Fantomas.Tests/Integration/DaemonTests.fs @@ -19,7 +19,7 @@ let private runWithDaemon (fn: JsonRpc -> Async) = async { let struct (serverStream, clientStream) = FullDuplexStream.CreatePair() - let daemon = new FantomasDaemon(serverStream, serverStream) + let daemon = new FantomasDaemon(serverStream, serverStream, realDaemonEnvironment) let client = new JsonRpc(clientStream, clientStream) client.StartListening() diff --git a/src/Fantomas.Tests/Integration/ExitCodeTests.fs b/src/Fantomas.Tests/Integration/ExitCodeTests.fs deleted file mode 100644 index 15c3196f8e..0000000000 --- a/src/Fantomas.Tests/Integration/ExitCodeTests.fs +++ /dev/null @@ -1,36 +0,0 @@ -module Fantomas.Tests.Integration.ExitCodeTests - -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -[] -let WithErrors = """let a =""" - -[] -let CorrectlyFormatted = - """module A - -""" - -[] -let ``invalid files should report exit code 1`` () = - use fileFixture = new TemporaryFileCodeSample(WithErrors) - let { ExitCode = exitCode } = formatCode [ fileFixture.Filename ] - exitCode |> should equal 1 - -[] -let ``non-existing file should report exit code 1`` () = - let { ExitCode = exitCode } = formatCode [ "somenonexistingfile.fs" ] - exitCode |> should equal 1 - -[] -let ``unsupported file should report exit code 1`` () = - use fileFixture = new TemporaryFileCodeSample(CorrectlyFormatted, extension = "txt") - let { ExitCode = exitCode } = formatCode [ fileFixture.Filename ] - exitCode |> should equal 1 - -[] -let ``missing file should report exit code 1`` () = - let { ExitCode = exitCode } = formatCode [] - exitCode |> should equal 1 diff --git a/src/Fantomas.Tests/Integration/ForceTests.fs b/src/Fantomas.Tests/Integration/ForceTests.fs deleted file mode 100644 index 89b597de3f..0000000000 --- a/src/Fantomas.Tests/Integration/ForceTests.fs +++ /dev/null @@ -1,31 +0,0 @@ -module Fantomas.Tests.Integration.ForceTests - -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -let Verbosity = [ "--verbosity"; "d" ] - -// The day this test fails because Fantomas can format the file, is the day you can remove this file. - -[] -let ``code that was invalid should be still be written`` () = - let pwd = Path.GetDirectoryName(typeof.Assembly.Location) - - let sourceFile = - Path.Combine(pwd, "..", "..", "..", "..", "tests", "data", "CheckDeclarations.fs") - |> Path.GetFullPath - - if not (File.Exists sourceFile) then - failwithf $"CheckDeclarations.fs was not found at \"%s{sourceFile}\"" - - use outputFixture = new OutputFile() - - let { ExitCode = exitCode; Output = output } = - runFantomasTool (Verbosity @ [ "--force"; "--out"; outputFixture.Filename; sourceFile ]) - - exitCode |> should equal 0 - output |> should contain "was not valid after formatting" - output |> should contain "has been written" - File.Exists outputFixture.Filename |> should equal true diff --git a/src/Fantomas.Tests/Integration/HelpPageTests.fs b/src/Fantomas.Tests/Integration/HelpPageTests.fs index 17b716ad23..9d9b39efc4 100644 --- a/src/Fantomas.Tests/Integration/HelpPageTests.fs +++ b/src/Fantomas.Tests/Integration/HelpPageTests.fs @@ -4,10 +4,14 @@ open NUnit.Framework open FsUnit open Fantomas.Tests.TestHelpers +// What the page says is settled in HelpPageTests, against `HelpPage.render`. What is left here is +// what only a real process shows: which stream the page goes to, and how much colour the terminal +// it is attached to actually gets. + [] [] [] -let ``help page is written to standard out`` (flag: string) = +let ``both spellings of the flag write the page to standard out`` (flag: string) = let { ExitCode = exitCode Output = output Error = error } = @@ -17,40 +21,6 @@ let ``help page is written to standard out`` (flag: string) = error |> should equal "" Assert.That(output, Does.Contain "Usage: fantomas [...flags] [...paths]") -[] -let ``help page lists every flag`` () = - let { Output = output } = runFantomasTool [ "--help" ] - - for flag in - [ "--check" - "--out" - "--force" - "--profile" - "--daemon" - "--verbosity" - "--version" - "--help" ] do - Assert.That(output, Does.Contain flag) - -[] -let ``help page carries the version`` () = - let { Output = output } = runFantomasTool [ "--help" ] - let version = Fantomas.Core.CodeFormatter.GetVersion() - let versionNumber = version.Split('+').[0] - - Assert.That(output, Does.Contain versionNumber) - -[] -let ``help page links the documentation, the Discord and the llms files`` () = - let { Output = output } = runFantomasTool [ "--help" ] - - for link in - [ "https://fsprojects.github.io/fantomas/docs" - "https://discord.com/channels/196693847965696000/1493226271767924747" - "https://fsprojects.github.io/fantomas/llms.txt" - "https://fsprojects.github.io/fantomas/llms-full.txt" ] do - Assert.That(output, Does.Contain link) - // Standard out is redirected here, so the page has to come back as plain text. [] let ``help page is not coloured when standard out is redirected`` () = diff --git a/src/Fantomas.Tests/Integration/IgnoreFilesTests.fs b/src/Fantomas.Tests/Integration/IgnoreFilesTests.fs deleted file mode 100644 index a0352cd520..0000000000 --- a/src/Fantomas.Tests/Integration/IgnoreFilesTests.fs +++ /dev/null @@ -1,136 +0,0 @@ -module Fantomas.Tests.Integration.IgnoreFilesTests - -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -[] -let Source = "let foo = 47" - -let Verbosity = [ "--verbosity"; "d" ] - -[] -let ``ignore all fs files`` () = - let fileName = "ToBeIgnored" - - use inputFixture = new TemporaryFileCodeSample(Source, fileName = fileName) - - use ignoreFixture = new FantomasIgnoreFile("*.fs") - use outputFixture = new OutputFile() - - let { ExitCode = exitCode } = - [ "--out"; outputFixture.Filename; inputFixture.Filename ] |> runFantomasTool - - exitCode |> should equal 0 - File.Exists outputFixture.Filename |> should equal false - -[] -let ``ignore specific file`` () = - let fileName = "A" - - use inputFixture = new TemporaryFileCodeSample(Source, fileName = fileName) - - use ignoreFixture = new FantomasIgnoreFile("A.fs") - let args = Verbosity @ [ inputFixture.Filename ] - let { ExitCode = exitCode; Output = output } = runFantomasTool args - exitCode |> should equal 0 - - output |> should contain "was ignored" - -[] -let ``ignore specific file in subfolder`` () = - let fileName = "A" - let sub1 = System.Guid.NewGuid().ToString("N") - let sub2 = System.Guid.NewGuid().ToString("N") - let subFolders = [| sub1; sub2 |] - - use inputFixture = - new TemporaryFileCodeSample(Source, fileName = fileName, subFolders = subFolders) - - use ignoreFixture = new FantomasIgnoreFile(sprintf "%s/%s/A.fs" sub1 sub2) - - let { ExitCode = exitCode } = - runFantomasTool [ "--check"; $".%c{Path.DirectorySeparatorChar}%s{sub1}" ] - - exitCode |> should equal 0 - -[] -let ``don't ignore other files`` () = - let fileName = "B" - - use inputFixture = new TemporaryFileCodeSample(Source, fileName = fileName) - - use ignoreFixture = new FantomasIgnoreFile("A.fs") - let args = Verbosity @ [ inputFixture.Filename ] - let { ExitCode = exitCode; Output = output } = runFantomasTool args - exitCode |> should equal 0 - - output |> should contain "Processing" - - output |> should contain "B.fs" - -[] -let ``ignore file in folder`` () = - let fileName = "A" - let subFolder = System.Guid.NewGuid().ToString("N") - - use inputFixture = - new TemporaryFileCodeSample(Source, fileName = fileName, subFolder = subFolder) - - use ignoreFixture = new FantomasIgnoreFile("A.fs") - - let { ExitCode = exitCode; Output = output } = - runFantomasTool (Verbosity @ [ $".%c{Path.DirectorySeparatorChar}%s{subFolder}" ]) - - exitCode |> should equal 0 - File.ReadAllText inputFixture.Filename |> should equal Source - - output |> should contain "A.fs was ignored" - -[] -let ``ignore file while checking`` () = - let fileName = "A" - - use inputFixture = new TemporaryFileCodeSample(Source, fileName = fileName) - - use ignoreFixture = new FantomasIgnoreFile("A.fs") - - let { ExitCode = exitCode; Output = output } = - [ "--check"; yield! Verbosity; inputFixture.Filename ] |> runFantomasTool - - exitCode |> should equal 0 - - output |> should contain "was ignored" - -[] -let ``ignore file in folder while checking`` () = - let fileName = "A" - let subFolder = System.Guid.NewGuid().ToString("N") - - use inputFixture = - new TemporaryFileCodeSample(Source, fileName = fileName, subFolder = subFolder) - - use ignoreFixture = new FantomasIgnoreFile("A.fs") - - let { ExitCode = exitCode } = - runFantomasTool [ $".%c{Path.DirectorySeparatorChar}%s{subFolder}"; "--check" ] - - exitCode |> should equal 0 - File.ReadAllText inputFixture.Filename |> should equal Source - -[] -let ``honor ignore file when processing a folder`` () = - let fileName = "A" - let subFolder = System.Guid.NewGuid().ToString("N") - - use ignoreFixture = - new TemporaryFileCodeSample(Source, fileName = fileName, subFolder = subFolder) - - use inputFixture = new FantomasIgnoreFile("*.fsx") - - let { Output = output } = - runFantomasTool (Verbosity @ [ $".%c{Path.DirectorySeparatorChar}%s{subFolder}" ]) - - output |> should not' (contain "ignored") - output |> should contain "A.fs was formatted" diff --git a/src/Fantomas.Tests/Integration/MultiplePathsTests.fs b/src/Fantomas.Tests/Integration/MultiplePathsTests.fs deleted file mode 100644 index d17cdb5f1f..0000000000 --- a/src/Fantomas.Tests/Integration/MultiplePathsTests.fs +++ /dev/null @@ -1,61 +0,0 @@ -module Fantomas.Tests.Integration.MultiplePathsTests - -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers -open System.IO - -[] -let UserCode = "let a = 9" - -[] -let FormattedCode = "let a = 9\n" - -let Verbosity = [ "--verbosity"; "d" ] - -let private fileContentMatches (expectedContent: string) (actualPath: string) : unit = - if File.Exists(actualPath) then - let actualContent = File.ReadAllText(actualPath) - actualContent |> should equal expectedContent - else - Assert.Fail(sprintf "File \"%s\" does not exist" actualPath) - -[] -let ``format multiple paths`` () = - use config = new ConfigurationFile("[*]\nend_of_line = lf") - - use fileFixtureOne = new TemporaryFileCodeSample(UserCode) - - use fileFixtureTwo = new TemporaryFileCodeSample(UserCode) - - let { ExitCode = exitCode } = - formatCode [ fileFixtureOne.Filename; fileFixtureTwo.Filename ] - - exitCode |> should equal 0 - - fileContentMatches FormattedCode fileFixtureOne.Filename - fileContentMatches FormattedCode fileFixtureTwo.Filename - -[] -let ``format multiple paths recursively`` () = - use config = new ConfigurationFile("[*]\nend_of_line = lf") - - use fileFixtureOne = new TemporaryFileCodeSample(UserCode) - - use fileFixtureTwo = new TemporaryFileCodeSample(UserCode) - - use fileFixtureThree = new TemporaryFileCodeSample(UserCode, subFolder = "sub") - - let arguments = - Verbosity @ [ fileFixtureOne.Filename; fileFixtureTwo.Filename; "sub" ] - - let { ExitCode = exitCode; Output = output } = runFantomasTool arguments - - exitCode |> should equal 0 - output |> should contain fileFixtureOne.Filename - output |> should contain fileFixtureTwo.Filename - - let subFolder = - sprintf "sub%c%s" Path.DirectorySeparatorChar (Path.GetFileName(fileFixtureThree.Filename)) - - output |> should contain subFolder diff --git a/src/Fantomas.Tests/Integration/ReportedPathTests.fs b/src/Fantomas.Tests/Integration/ReportedPathTests.fs deleted file mode 100644 index 571f5f4297..0000000000 --- a/src/Fantomas.Tests/Integration/ReportedPathTests.fs +++ /dev/null @@ -1,83 +0,0 @@ -module Fantomas.Tests.Integration.ReportedPathTests - -open System -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -[] -let UnformattedCode = "let a = 9" - -[] -let FormattedCode = "let a = 9\n" - -[] -let WithErrors = "let a =" - -// A single result used to be reported by file name only, while a run over several files -// reported the path the file was found at. Both now report the path. - -let private subFolderName () = Guid.NewGuid().ToString("N") - -let private relativePath (subFolder: string) (fileName: string) = - $"%s{subFolder}%c{Path.DirectorySeparatorChar}%s{fileName}.fs" - -[] -let ``a formatted single file is reported with the path it was given`` () = - use config = new ConfigurationFile("[*]\nend_of_line = lf") - let subFolder = subFolderName () - - use fileFixture = - new TemporaryFileCodeSample(UnformattedCode, fileName = "A", subFolder = subFolder) - - let path = relativePath subFolder "A" - let { ExitCode = exitCode; Output = output } = formatCode [ path ] - - exitCode |> should equal 0 - output |> should contain $"%s{path} was formatted." - -[] -let ``an unchanged single file is reported with the path it was given`` () = - use config = new ConfigurationFile("[*]\nend_of_line = lf") - let subFolder = subFolderName () - - use fileFixture = - new TemporaryFileCodeSample(FormattedCode, fileName = "A", subFolder = subFolder) - - let path = relativePath subFolder "A" - let { ExitCode = exitCode; Output = output } = formatCode [ path ] - - exitCode |> should equal 0 - output |> should contain $"%s{path} was unchanged." - -[] -let ``a single file that could not be parsed is reported with the path it was given`` () = - let subFolder = subFolderName () - - use fileFixture = - new TemporaryFileCodeSample(WithErrors, fileName = "A", subFolder = subFolder) - - let path = relativePath subFolder "A" - let { ExitCode = exitCode; Error = error } = formatCode [ path ] - - exitCode |> should equal 1 - error |> should contain $"Fantomas could not parse %s{path}:" - -[] -let ``a file that could not be parsed is reported the same way among several files`` () = - use config = new ConfigurationFile("[*]\nend_of_line = lf") - let subFolder = subFolderName () - - use erroneousFixture = - new TemporaryFileCodeSample(WithErrors, fileName = "A", subFolder = subFolder) - - use otherFixture = new TemporaryFileCodeSample(FormattedCode) - - let path = relativePath subFolder "A" - - let { ExitCode = exitCode; Error = error } = - formatCode [ path; otherFixture.Filename ] - - exitCode |> should equal 1 - error |> should contain $"Fantomas could not parse %s{path}:" diff --git a/src/Fantomas.Tests/Integration/SmokeTests.fs b/src/Fantomas.Tests/Integration/SmokeTests.fs new file mode 100644 index 0000000000..42b1108aa5 --- /dev/null +++ b/src/Fantomas.Tests/Integration/SmokeTests.fs @@ -0,0 +1,129 @@ +module Fantomas.Tests.Integration.SmokeTests + +open System.IO +open System.Text +open NUnit.Framework +open FsUnit +open Fantomas.Tests.TestHelpers + +// What is left of the tests that start a real fantomas process. +// +// Everything the tool decides is covered in memory, against a MockFileSystem, in the test files +// beside this folder. What that cannot reach is the wiring: that the arguments are parsed at all, +// that an exit code makes it out to the operating system, that a working directory and a real file +// on a real disk behave the way the mock says they do. That is what is left here, one case per +// thing, rather than a case per behaviour. +// +// Three files beside this one are kept for the same reason and are not repeated here: ConfigTests, +// because `.editorconfig` is deliberately never mocked and its parser reads the disk itself; +// StandardStreamTests, because which stream a message lands on is invisible from inside the +// process; and HelpPageTests, for how much colour a terminal is given. + +[] +let private NeedsFormatting = "let a = 1" + +[] +let ``the help page is written and the process ends well`` () = + let { ExitCode = exitCode; Output = output } = runFantomasTool [ "--help" ] + + exitCode |> should equal 0 + output |> should contain "Usage:" + +[] +let ``a file named on the command line is formatted where it lies`` () = + use fileFixture = new TemporaryFileCodeSample(NeedsFormatting) + + let { ExitCode = exitCode; Output = output } = formatCode [ fileFixture.Filename ] + + exitCode |> should equal 0 + output |> should contain "was formatted" + + File.ReadAllText fileFixture.Filename + |> String.normalizeNewLine + |> should equal "let a = 1\n" + +[] +let ``an out path is written to and the input is left alone`` () = + use inputFixture = new TemporaryFileCodeSample(NeedsFormatting) + use outputFixture = new OutputFile() + + let { ExitCode = exitCode } = + runFantomasTool [ "--out"; outputFixture.Filename; inputFixture.Filename ] + + exitCode |> should equal 0 + File.ReadAllText inputFixture.Filename |> should equal NeedsFormatting + + File.ReadAllText outputFixture.Filename + |> String.normalizeNewLine + |> should equal "let a = 1\n" + +// 0, 99 and 1 are what a build script branches on, so each has to reach the operating system. +[] +let ``a check that finds nothing to do exits 0`` () = + use fileFixture = new TemporaryFileCodeSample("let a = 1\n") + + let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] + exitCode |> should equal 0 + +[] +let ``a check that finds a file needing formatting exits 99`` () = + use fileFixture = new TemporaryFileCodeSample(NeedsFormatting) + + let { ExitCode = exitCode } = checkCode [ fileFixture.Filename ] + exitCode |> should equal 99 + +[] +let ``an input path that cannot be used exits 1`` () = + let { ExitCode = exitCode } = formatCode [ "somenonexistingfile.fs" ] + exitCode |> should equal 1 + +[] +let ``a file that cannot be parsed exits 1`` () = + use fileFixture = new TemporaryFileCodeSample("let a =") + + let { ExitCode = exitCode } = formatCode [ fileFixture.Filename ] + exitCode |> should equal 1 + +// The in-memory tests take a MockFileSystem at its word about encodings. This says a real disk +// agrees with it. +[] +let ``a byte order mark survives a round trip through a real file`` () = + use fileFixture = + new TemporaryFileCodeSample(NeedsFormatting, hasByteOrderMark = true) + + let { ExitCode = exitCode } = formatCode [ fileFixture.Filename ] + exitCode |> should equal 0 + + let preamble = Encoding.UTF8.GetPreamble() + + use stream = new FileStream(fileFixture.Filename, FileMode.Open, FileAccess.Read) + let actual = Array.zeroCreate preamble.Length + stream.ReadExactly(actual, 0, preamble.Length) + + actual |> should equal preamble + +// Reading the ignore file happens before either command runs, so a pattern the ignore library +// will not compile used to escape every handler and end the process with a stack trace. +[] +let ``a fantomasignore that cannot be read is reported rather than thrown`` () = + use fileFixture = new TemporaryFileCodeSample(NeedsFormatting) + use ignoreFixture = new FantomasIgnoreFile("a[") + + let { ExitCode = exitCode; Error = error } = formatCode [ fileFixture.Filename ] + + exitCode |> should equal 1 + Assert.That(error, Does.Not.Contain "Unhandled exception") + Assert.That(error, Does.Not.Contain " at ") + +// The ignore file is found relative to the directory the tool was started in, which is the one +// thing about it a mock cannot stand in for. +[] +let ``a fantomasignore in the working directory is honoured`` () = + use fileFixture = new TemporaryFileCodeSample(NeedsFormatting, fileName = "Ignored") + use ignoreFixture = new FantomasIgnoreFile("Ignored.fs") + + let { ExitCode = exitCode; Output = output } = formatCode [ fileFixture.Filename ] + + exitCode |> should equal 0 + output |> should contain "was ignored" + File.ReadAllText fileFixture.Filename |> should equal NeedsFormatting diff --git a/src/Fantomas.Tests/Integration/WriteTests.fs b/src/Fantomas.Tests/Integration/WriteTests.fs deleted file mode 100644 index 8289f1ea85..0000000000 --- a/src/Fantomas.Tests/Integration/WriteTests.fs +++ /dev/null @@ -1,218 +0,0 @@ -module Fantomas.Tests.Integration.WriteTests - -open System.IO -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers - -[] -let FormattedCode = "let a = 9\n" - -[] -let UnformattedCode = "let a = 9" - -[] -let OtherFormattedCode = "let b = 8\n" - -[] -let OtherUnformattedCode = "let b = 8" - -let Verbosity = [ "--verbosity"; "d" ] - -let readFormatted (file: string) : string = - File.ReadAllText file |> String.normalizeNewLine - -[] -let ``correctly formatted file should not be written, 1984`` () = - let fileName = "A" - - use configFixture = - new ConfigurationFile( - """ -[*] -end_of_line=lf -""" - ) - - use inputFixture = new TemporaryFileCodeSample(FormattedCode, fileName = fileName) - let args = Verbosity @ [ inputFixture.Filename ] - let { ExitCode = exitCode; Output = output } = runFantomasTool args - exitCode |> should equal 0 - - output |> should contain "was unchanged" - -[] -let ``incorrectly formatted file should be written`` () = - let fileName = "A" - - use inputFixture = new TemporaryFileCodeSample(UnformattedCode, fileName = fileName) - let args = Verbosity @ [ inputFixture.Filename ] - let { ExitCode = exitCode; Output = output } = runFantomasTool args - exitCode |> should equal 0 - - output |> should contain "has been written" - -[] -let ``file should be written to out folder when input folder has trailing slash`` () = - use fileFixtureOne = - new TemporaryFileCodeSample(FormattedCode, fileName = "A", subFolder = "subsrc") - - use outputFolder = new OutputFolder() - - let arguments = - Verbosity - @ [ $"subsrc%c{Path.DirectorySeparatorChar}"; "--out"; outputFolder.Foldername ] - - let { ExitCode = exitCode; Output = output } = runFantomasTool arguments - - exitCode |> should equal 0 - let outputFilePath = Path.Combine(outputFolder.Foldername, "A.fs") - output |> should contain outputFilePath - -[] -let ``file should be written to out folder when input folder has no trailing slash`` () = - use fileFixtureOne = - new TemporaryFileCodeSample(FormattedCode, fileName = "A", subFolder = "subsrc") - - use outputFolder = new OutputFolder() - - let arguments = Verbosity @ [ "subsrc"; "--out"; outputFolder.Foldername ] - - let { ExitCode = exitCode; Output = output } = runFantomasTool arguments - - exitCode |> should equal 0 - let outputFilePath = Path.Combine(outputFolder.Foldername, "A.fs") - output |> should contain outputFilePath - -[] -let ``out folder mirrors the structure of the input folder`` () = - let root = System.Guid.NewGuid().ToString("N") - - // Distinct contents, so that a file landing where another one belongs is caught. The bug - // this pins is two files with the same name overwriting each other. - use _nestedFixture = - new TemporaryFileCodeSample(OtherUnformattedCode, fileName = "A", subFolders = [| root; "nested" |]) - - File.WriteAllText(Path.Join(Path.GetTempPath(), root, "A.fs"), UnformattedCode) - - use outputFolder = new OutputFolder() - - let arguments = Verbosity @ [ root; "--out"; outputFolder.Foldername ] - - let { ExitCode = exitCode } = runFantomasTool arguments - - exitCode |> should equal 0 - - Path.Join(outputFolder.Foldername, "A.fs") - |> readFormatted - |> should equal FormattedCode - - Path.Join(outputFolder.Foldername, "nested", "A.fs") - |> readFormatted - |> should equal OtherFormattedCode - -[] -let ``out folder mirrors the input folder when it has a trailing separator`` () = - let root = System.Guid.NewGuid().ToString("N") - - use _nestedFixture = - new TemporaryFileCodeSample(UnformattedCode, fileName = "A", subFolders = [| root; "nested" |]) - - use outputFolder = new OutputFolder() - - let arguments = - Verbosity - @ [ $"%s{root}%c{Path.DirectorySeparatorChar}"; "--out"; outputFolder.Foldername ] - - let { ExitCode = exitCode } = runFantomasTool arguments - - exitCode |> should equal 0 - - Path.Join(outputFolder.Foldername, "nested", "A.fs") - |> readFormatted - |> should equal FormattedCode - -[] -let ``out folder naming the input folder differently does not empty the input`` () = - let root = System.Guid.NewGuid().ToString("N") - - use _nestedFixture = - new TemporaryFileCodeSample(OtherUnformattedCode, fileName = "A", subFolders = [| root; "nested" |]) - - File.WriteAllText(Path.Join(Path.GetTempPath(), root, "A.fs"), UnformattedCode) - - // The same folder under a spelling that differs from the input path. Writing the output - // before reading the input would empty every file here. - let arguments = - Verbosity @ [ root; "--out"; $".%c{Path.DirectorySeparatorChar}%s{root}" ] - - let { ExitCode = exitCode } = runFantomasTool arguments - - exitCode |> should equal 0 - - Path.Join(Path.GetTempPath(), root, "A.fs") - |> readFormatted - |> should equal FormattedCode - - Path.Join(Path.GetTempPath(), root, "nested", "A.fs") - |> readFormatted - |> should equal OtherFormattedCode - -[] -let ``out folder inside the input folder is not formatted into itself again`` () = - let root = System.Guid.NewGuid().ToString("N") - - use _inputFixture = - new TemporaryFileCodeSample(UnformattedCode, fileName = "A", subFolders = [| root |]) - - let outputFolder = Path.Join(root, "formatted") - let arguments = Verbosity @ [ root; "--out"; outputFolder ] - - let { ExitCode = firstExitCode } = runFantomasTool arguments - let { ExitCode = secondExitCode } = runFantomasTool arguments - - firstExitCode |> should equal 0 - secondExitCode |> should equal 0 - - Path.Join(Path.GetTempPath(), root, "formatted", "A.fs") - |> readFormatted - |> should equal FormattedCode - - // The second run must not pick its own output up as input and nest it one level deeper. - Path.Join(Path.GetTempPath(), root, "formatted", "formatted") - |> Directory.Exists - |> should equal false - -[] -let ``out file is written when its folder does not exist yet`` () = - use inputFixture = new TemporaryFileCodeSample(UnformattedCode, fileName = "A") - - use outputFolder = new OutputFolder() - let outputFile = Path.Join(outputFolder.Foldername, "nested", "A.fs") - - let arguments = Verbosity @ [ inputFixture.Filename; "--out"; outputFile ] - - let { ExitCode = exitCode } = runFantomasTool arguments - - exitCode |> should equal 0 - outputFile |> readFormatted |> should equal FormattedCode - -[] -let ``out file without a folder is written next to the working directory`` () = - use inputFixture = new TemporaryFileCodeSample(UnformattedCode, fileName = "A") - - // The tool runs with the temp folder as its working directory, so a bare file name has no - // folder part at all. Creating "the parent folder" of such a path must not be attempted. - let outputName = System.Guid.NewGuid().ToString("N") + ".fs" - - let arguments = Verbosity @ [ inputFixture.Filename; "--out"; outputName ] - - let outputFile = Path.Join(Path.GetTempPath(), outputName) - - try - let { ExitCode = exitCode } = runFantomasTool arguments - - exitCode |> should equal 0 - outputFile |> readFormatted |> should equal FormattedCode - finally - File.Delete outputFile diff --git a/src/Fantomas.Tests/PathsTests.fs b/src/Fantomas.Tests/PathsTests.fs new file mode 100644 index 0000000000..11125f34fb --- /dev/null +++ b/src/Fantomas.Tests/PathsTests.fs @@ -0,0 +1,167 @@ +module Fantomas.Tests.PathsTests + +open System.IO +open System.IO.Abstractions +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas.Paths +open Fantomas.Tests.TestHelpers + +let private separator: char = Path.DirectorySeparatorChar + +[] +[] +[] +[] +[] +[] +let ``the extensions Fantomas formats are F# files`` (path: string) = isFSharpFile path |> shouldEqual true + +[] +[] +[] +[] +let ``the extension is recognised whatever its case`` (path: string) = isFSharpFile path |> shouldEqual true + +[] +[] +[] +[] +[] +let ``anything else is not an F# file`` (path: string) = isFSharpFile path |> shouldEqual false + +[] +[] +[] +[] +[] +let ``a file below a folder someone else wrote is excluded`` (folder: string) = + isInExcludedDir $"src%c{separator}%s{folder}%c{separator}A.fs" + |> shouldEqual true + +[] +let ``a folder whose name merely starts with an excluded one is not excluded`` () = + // The separators either side are what stops `objects` from being read as `obj`. + isInExcludedDir $"src%c{separator}objects%c{separator}A.fs" |> shouldEqual false + +[] +let ``an excluded name at the very end of a path is not a folder`` () = + isInExcludedDir $"src%c{separator}obj" |> shouldEqual false + +[] +let ``every F# file below a folder is found, at any depth`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + + [ fs.Path.Combine(src, "A.fs") + fs.Path.Combine(src, "nested", "B.fsi") + fs.Path.Combine(src, "nested", "deeper", "C.fsx") ] + |> makeFileHierarchy fs + + findAllFilesRecursively fs src + |> Seq.map fs.Path.GetFileName + |> Seq.sort + |> List.ofSeq + |> shouldEqual [ "A.fs"; "B.fsi"; "C.fsx" ] + +[] +let ``files that are not F# are left out of the walk`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + + [ fs.Path.Combine(src, "A.fs") + fs.Path.Combine(src, "README.md") + fs.Path.Combine(src, "App.csproj") ] + |> makeFileHierarchy fs + + findAllFilesRecursively fs src + |> Seq.map fs.Path.GetFileName + |> List.ofSeq + |> shouldEqual [ "A.fs" ] + +[] +let ``build output is left out of the walk`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + + [ fs.Path.Combine(src, "A.fs") + fs.Path.Combine(src, "obj", "Generated.fs") + fs.Path.Combine(src, "node_modules", "thing", "B.fs") ] + |> makeFileHierarchy fs + + findAllFilesRecursively fs src + |> Seq.map fs.Path.GetFileName + |> List.ofSeq + |> shouldEqual [ "A.fs" ] + +[] +let ``the folders leading up to a file are created`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let target: string = fs.Path.Combine(root, "out", "nested", "A.fs") + + ensureParentFolderExists fs target + + fs.Directory.Exists(fs.Path.Combine(root, "out", "nested")) |> shouldEqual true + +[] +let ``a bare file name has no folder to create`` () = + let fs: IFileSystem = MockFileSystem() + + // Path.GetDirectoryName yields an empty string here, which must not be created. + ensureParentFolderExists fs "A.fs" + +[] +let ``two spellings of the same location are the same path`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let direct: string = fs.Path.Combine(root, "src", "A.fs") + let roundabout: string = fs.Path.Combine(root, "src", ".", "A.fs") + + isSamePath fs direct roundabout |> shouldEqual true + +[] +let ``a trailing separator names the same path`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + + isSamePath fs src (src + string separator) |> shouldEqual true + isSamePath fs (src + string separator) src |> shouldEqual true + +[] +let ``two different locations are not the same path`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + + isSamePath fs (fs.Path.Combine(root, "src", "A.fs")) (fs.Path.Combine(root, "src", "B.fs")) + |> shouldEqual false + +[] +let ``a file below a folder is in it, at any depth`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + + isInFolder fs src (fs.Path.Combine(src, "A.fs")) |> shouldEqual true + isInFolder fs src (fs.Path.Combine(src, "nested", "A.fs")) |> shouldEqual true + +[] +let ``a sibling folder whose name starts with the folder is not inside it`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + + // `src-generated` starts with `src`, so without the separator the comparison appends it + // would count as being inside. + isInFolder fs (fs.Path.Combine(root, "src")) (fs.Path.Combine(root, "src-generated", "A.fs")) + |> shouldEqual false + +[] +let ``a folder is not inside itself`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + + isInFolder fs src src |> shouldEqual false diff --git a/src/Fantomas.Tests/PlanTests.fs b/src/Fantomas.Tests/PlanTests.fs new file mode 100644 index 0000000000..bee8f3f308 --- /dev/null +++ b/src/Fantomas.Tests/PlanTests.fs @@ -0,0 +1,215 @@ +module Fantomas.Tests.PlanTests + +open System.IO.Abstractions +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult +open Fantomas.Plan +open Fantomas.Tests.TestHelpers + +/// Plan against the given file system, honouring no ignore file. +let private planOn + (fs: IFileSystem) + (inputPath: InputPath) + (outputPath: OutputPath) + : Result = + plan fs silentLogger None inputPath outputPath + +/// Plan against the given file system, honouring a `.fantomasignore` written at its root. +let private planIgnoring + (fs: IFileSystem) + (patterns: string) + (inputPath: InputPath) + (outputPath: OutputPath) + : Result = + let root: string = mockRoot fs + fs.File.WriteAllText(fs.Path.Combine(root, IgnoreFile.IgnoreFileName), patterns) + + let ignoreFile: IgnoreFile option = + IgnoreFile.findInDirectory fs root (IgnoreFile.loadIgnoreList fs) + + plan fs silentLogger ignoreFile inputPath outputPath + +let private shouldPlan (expected: WorkItem list) (actual: Result) : unit = + match actual with + | Ok items -> items |> List.sort |> shouldEqual (List.sort expected) + | Error problem -> failwith $"Expected a plan, got %A{problem}" + +let private shouldRefuse (expected: InputProblem) (actual: Result) : unit = + match actual with + | Error problem -> problem |> shouldEqual expected + | Ok items -> failwith $"Expected %A{expected}, got a plan of %d{items.Length} items" + +[] +let ``an unsupported file type is refused`` () = + planOn (MockFileSystem()) (InputPath.NoFSharpFile "A.md") OutputPath.NotKnown + |> shouldRefuse (InputProblem.UnsupportedFileType "A.md") + +[] +let ``a path that is not there is refused`` () = + planOn (MockFileSystem()) (InputPath.NotFound "A.fs") OutputPath.NotKnown + |> shouldRefuse (InputProblem.NotFound "A.fs") + +[] +let ``no input path is refused`` () = + planOn (MockFileSystem()) InputPath.Unspecified OutputPath.NotKnown + |> shouldRefuse InputProblem.NoPathGiven + +[] +let ``several input paths with an output path is refused`` () = + planOn (MockFileSystem()) (InputPath.Multiple([ "A.fs" ], [])) (OutputPath.IO "out") + |> shouldRefuse InputProblem.MultiplePathsWithOut + +[] +let ``a single file with no output path is formatted where it lies`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + [ file ] |> makeFileHierarchy fs + + planOn fs (InputPath.File file) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Format(file, file) ] + +[] +let ``a single file with an output path is written there instead`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "A.fs") + let out: string = fs.Path.Combine(root, "out", "A.fs") + [ file ] |> makeFileHierarchy fs + + planOn fs (InputPath.File file) (OutputPath.IO out) + |> shouldPlan [ WorkItem.Format(file, out) ] + +[] +let ``a folder with no output path formats every file where it lies`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let a: string = fs.Path.Combine(src, "A.fs") + let b: string = fs.Path.Combine(src, "nested", "B.fs") + [ a; b ] |> makeFileHierarchy fs + + planOn fs (InputPath.Folder src) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Format(a, a); WorkItem.Format(b, b) ] + +[] +let ``an output folder mirrors the input tree rather than flattening it`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let src: string = fs.Path.Combine(root, "src") + let out: string = fs.Path.Combine(root, "out") + // Two files with the same name would overwrite each other were the tree flattened. + let a: string = fs.Path.Combine(src, "A.fs") + let nestedA: string = fs.Path.Combine(src, "nested", "A.fs") + [ a; nestedA ] |> makeFileHierarchy fs + + planOn fs (InputPath.Folder src) (OutputPath.IO out) + |> shouldPlan + [ WorkItem.Format(a, fs.Path.Combine(out, "A.fs")) + WorkItem.Format(nestedA, fs.Path.Combine(out, "nested", "A.fs")) ] + +[] +let ``an output folder inside the input folder is not formatted into itself again`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let out: string = fs.Path.Combine(src, "out") + let a: string = fs.Path.Combine(src, "A.fs") + // What a previous run left behind. Formatting it again would nest it one level deeper. + let previous: string = fs.Path.Combine(out, "A.fs") + [ a; previous ] |> makeFileHierarchy fs + + planOn fs (InputPath.Folder src) (OutputPath.IO out) + |> shouldPlan [ WorkItem.Format(a, previous) ] + +[] +let ``an input folder that is also the output folder is formatted in place`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let a: string = fs.Path.Combine(src, "A.fs") + [ a ] |> makeFileHierarchy fs + + // Spelled differently, so only comparing the resolved paths says they are the same place. + let alsoSrc: string = fs.Path.Combine(src, ".") + + planOn fs (InputPath.Folder src) (OutputPath.IO alsoSrc) + |> shouldPlan [ WorkItem.Format(a, a) ] + +[] +let ``a folder spelled with a trailing separator is still formatted in place`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let a: string = fs.Path.Combine(src, "A.fs") + [ a ] |> makeFileHierarchy fs + + // `fantomas src/ --out src`. Taken as two different folders, every file below src counts as a + // previous run's output and the plan comes out empty. + planOn fs (InputPath.Folder(src + string fs.Path.DirectorySeparatorChar)) (OutputPath.IO src) + |> shouldPlan [ WorkItem.Format(a, a) ] + +[] +let ``several files and folders are all formatted where they lie`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let loose: string = fs.Path.Combine(root, "Loose.fs") + let src: string = fs.Path.Combine(root, "src") + let a: string = fs.Path.Combine(src, "A.fs") + [ loose; a ] |> makeFileHierarchy fs + + planOn fs (InputPath.Multiple([ loose ], [ src ])) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Format(loose, loose); WorkItem.Format(a, a) ] + +[] +let ``a file the ignore file matches is skipped rather than formatted`` () = + let fs: IFileSystem = MockFileSystem() + let file: string = fs.Path.Combine(mockRoot fs, "A.fs") + [ file ] |> makeFileHierarchy fs + + planIgnoring fs "A.fs" (InputPath.File file) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Ignored file ] + +[] +let ``an ignored file is skipped when found by walking a folder too`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let kept: string = fs.Path.Combine(src, "Kept.fs") + let skipped: string = fs.Path.Combine(src, "Skipped.fs") + [ kept; skipped ] |> makeFileHierarchy fs + + planIgnoring fs "Skipped.fs" (InputPath.Folder src) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Format(kept, kept); WorkItem.Ignored skipped ] + +[] +let ``an ignore pattern naming a nested path matches only that path`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let skipped: string = fs.Path.Combine(src, "generated", "A.fs") + let kept: string = fs.Path.Combine(src, "handwritten", "A.fs") + [ skipped; kept ] |> makeFileHierarchy fs + + // Patterns are read relative to the folder holding the ignore file, with forward slashes, + // whatever separator the platform uses for the paths themselves. + planIgnoring fs "src/generated/A.fs" (InputPath.Folder src) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Ignored skipped; WorkItem.Format(kept, kept) ] + +[] +let ``an ignore pattern naming a folder skips everything below it`` () = + let fs: IFileSystem = MockFileSystem() + let src: string = fs.Path.Combine(mockRoot fs, "src") + let skipped: string = fs.Path.Combine(src, "generated", "deep", "A.fs") + let kept: string = fs.Path.Combine(src, "B.fs") + [ skipped; kept ] |> makeFileHierarchy fs + + planIgnoring fs "src/generated/" (InputPath.Folder src) OutputPath.NotKnown + |> shouldPlan [ WorkItem.Ignored skipped; WorkItem.Format(kept, kept) ] + +[] +let ``an ignored file with an output path is skipped, so nothing is written there`` () = + let fs: IFileSystem = MockFileSystem() + let root: string = mockRoot fs + let file: string = fs.Path.Combine(root, "A.fs") + [ file ] |> makeFileHierarchy fs + + planIgnoring fs "*.fs" (InputPath.File file) (OutputPath.IO(fs.Path.Combine(root, "out", "A.fs"))) + |> shouldPlan [ WorkItem.Ignored file ] diff --git a/src/Fantomas.Tests/ReportTests.fs b/src/Fantomas.Tests/ReportTests.fs new file mode 100644 index 0000000000..31b07e2a6e --- /dev/null +++ b/src/Fantomas.Tests/ReportTests.fs @@ -0,0 +1,292 @@ +module Fantomas.Tests.ReportTests + +open System +open System.IO.Abstractions.TestingHelpers +open NUnit.Framework +open FsUnitTyped +open Fantomas.Core +open Fantomas.CommandResult +open Fantomas.Logging +open Fantomas.Report +open Fantomas.Tests.TestHelpers + +let private run () : RecordedRun = + recordingEnvironment (MockFileSystem()) None + +let private reportFormat + (settings: Fantomas.Cli.CliSettings) + (result: FormatCommandResult) + : int * CollectedLog * string = + let recorded: RecordedRun = run () + let code: int = reportFormatCommand recorded.Environment settings result + code, recorded.Log(), recorded.Drawn() + +let private reportCheck (result: CheckCommandResult) : int * CollectedLog = + let recorded: RecordedRun = run () + let code: int = reportCheckCommand recorded.Environment result + code, recorded.Log() + +[] +let ``every way the input paths can fail has its own wording`` () = + [ InputProblem.UnsupportedFileType "A.md" + InputProblem.NotFound "A.fs" + InputProblem.NoPathGiven + InputProblem.MultiplePathsWithOut ] + |> List.map describeInputProblem + |> shouldEqual + [ "Input path 'A.md' is an unsupported file type." + "Input path 'A.fs' not found." + "No input path provided. Call with --help for usage information." + "Multiple input files are not supported with the --out flag." ] + +[] +let ``an unusable input path is reported on error and exits 1`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.InvalidInput(InputProblem.NotFound "A.fs")) + + code |> shouldEqual 1 + log.Error |> shouldEqual [ "Input path 'A.fs' not found." ] + log.Information |> shouldBeEmpty + +[] +let ``a failure no single file can be blamed for is reported and exits 1`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.Failed(Exception "the disk went away")) + + code |> shouldEqual 1 + log.Error |> shouldEqual [ "the disk went away" ] + +[] +let ``a single formatted file is reported as a sentence naming it`` () = + let code, log, drawn = + reportFormat + defaultSettings + (FormatCommandResult.Completed [| FormatResult.Formatted("A.fs", "let a = 1", None) |]) + + code |> shouldEqual 0 + log.Information |> shouldEqual [ "A.fs was formatted." ] + // A table of one row would say less than the sentence does, so none is drawn. + drawn |> shouldEqual "" + +[] +let ``a file is reported by the path it was given, not by its name alone`` () = + // Reducing the path to its file name is the regression this guards: `sub/A.fs` has to come + // back as `sub/A.fs`, whatever spelling the caller used. + let path: string = "sub/A.fs" + + let formatted, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.Formatted(path, "", None) |]) + + let _, unchangedLog, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.Unchanged(path, None) |]) + + let _, ignoredLog, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.IgnoredFile path |]) + + formatted |> shouldEqual 0 + log.Information |> shouldEqual [ "sub/A.fs was formatted." ] + unchangedLog.Information |> shouldEqual [ "sub/A.fs was unchanged." ] + ignoredLog.Information |> shouldEqual [ "sub/A.fs was ignored." ] + +[] +let ``a file that failed is reported by the path it was given`` () = + let _, log, _ = + reportFormat + defaultSettings + (FormatCommandResult.Completed [| FormatResult.Error("sub/A.fs", Exception "boom") |]) + + log.Error |> shouldEqual [ "Failed to format file: sub/A.fs" ] + +[] +let ``a check names the files it found by the path it was given`` () = + let _, log = + reportCheck ( + CheckCommandResult.Completed( + [], + { Errors = [] + Formatted = [ "sub/A.fs" ] } + ) + ) + + log.Information |> shouldEqual [ "sub/A.fs needs formatting" ] + +[] +let ``the files a run ignored are named at detailed verbosity`` () = + // A single result is named outright; among several, only the counts table is drawn, so this + // debug line is the only place a folder run says which files it skipped. + let _, log, _ = + reportFormat + defaultSettings + (FormatCommandResult.Completed + [| FormatResult.Formatted("A.fs", "", None) + FormatResult.IgnoredFile "sub/B.fs" |]) + + log.Debug |> shouldEqual [ "'sub/B.fs' was ignored" ] + +[] +let ``a single unchanged file is reported as unchanged`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.Unchanged("A.fs", None) |]) + + code |> shouldEqual 0 + log.Information |> shouldEqual [ "A.fs was unchanged." ] + +[] +let ``a single ignored file is reported as ignored`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.IgnoredFile "A.fs" |]) + + code |> shouldEqual 0 + log.Information |> shouldEqual [ "A.fs was ignored." ] + +[] +let ``a single file that failed is reported on error and exits 1`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.Error("A.fs", Exception "boom") |]) + + code |> shouldEqual 1 + log.Error |> shouldEqual [ "Failed to format file: A.fs" ] + +[] +let ``code that came out invalid is reported as a failure and exits 1`` () = + let code, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.InvalidCode("A.fs", "let a =") |]) + + code |> shouldEqual 1 + + log.Error + |> shouldEqual [ "Failed to format file: A.fs : Formatting A.fs leads to invalid F# code" ] + +[] +let ``a detailed run reports the whole exception rather than a line`` () = + let settings: Fantomas.Cli.CliSettings = + { defaultSettings with + Verbosity = VerbosityLevel.Detailed } + + let code, log, _ = + reportFormat settings (FormatCommandResult.Completed [| FormatResult.Error("A.fs", Exception "boom") |]) + + code |> shouldEqual 1 + log.Error |> List.exactlyOne |> shouldContainText "System.Exception: boom" + +[] +let ``several files are reported as a table of counts`` () = + let code, log, drawn = + reportFormat + defaultSettings + (FormatCommandResult.Completed + [| FormatResult.Formatted("A.fs", "", None) + FormatResult.Unchanged("B.fs", None) + FormatResult.IgnoredFile "C.fs" |]) + + code |> shouldEqual 0 + // No sentence per file: the table is the report. + log.Information |> shouldBeEmpty + drawn |> shouldContainText "Formatted" + drawn |> shouldContainText "Ignored" + drawn |> shouldContainText "Unchanged" + drawn |> shouldContainText "Errored" + +[] +let ``one failure among several files still exits 1`` () = + let code, log, _ = + reportFormat + defaultSettings + (FormatCommandResult.Completed + [| FormatResult.Formatted("A.fs", "", None) + FormatResult.Error("B.fs", Exception "boom") |]) + + code |> shouldEqual 1 + log.Error |> shouldEqual [ "Failed to format file: B.fs" ] + +[] +let ``profiling reports the line count and the time taken for a single file`` () = + let settings: Fantomas.Cli.CliSettings = { defaultSettings with Profile = true } + + let profile: ProfileInfo option = + Some + { LineCount = 12 + TimeTaken = TimeSpan.FromSeconds 1.0 } + + let _, log, _ = + reportFormat settings (FormatCommandResult.Completed [| FormatResult.Formatted("A.fs", "", profile) |]) + + log.Information + |> List.filter (fun (line: string) -> line.Contains "Line count") + |> shouldEqual [ "A.fs Line count: 12 Time taken 00:00:01" ] + +[] +let ``nothing is profiled unless profiling was asked for`` () = + let profile: ProfileInfo option = + Some + { LineCount = 12 + TimeTaken = TimeSpan.FromSeconds 1.0 } + + let _, log, _ = + reportFormat defaultSettings (FormatCommandResult.Completed [| FormatResult.Formatted("A.fs", "", profile) |]) + + log.Information |> shouldEqual [ "A.fs was formatted." ] + +[] +let ``a check of an unusable input path exits 1`` () = + let code, log = + reportCheck (CheckCommandResult.InvalidInput InputProblem.NoPathGiven) + + code |> shouldEqual 1 + + log.Error + |> shouldEqual [ "No input path provided. Call with --help for usage information." ] + +[] +let ``a check that failed outright is reported and exits 1`` () = + let code, log = + reportCheck (CheckCommandResult.Failed(Exception "the ignore file makes no sense")) + + code |> shouldEqual 1 + log.Error |> shouldEqual [ "the ignore file makes no sense" ] + +[] +let ``a check with nothing to do exits 0`` () = + let code, log = + reportCheck (CheckCommandResult.Completed([], { Errors = []; Formatted = [] })) + + code |> shouldEqual 0 + log.Debug |> shouldEqual [ "No changes required." ] + +[] +let ``a check reports the files it ignored`` () = + let code, log = + reportCheck (CheckCommandResult.Completed([ "A.fs" ], { Errors = []; Formatted = [] })) + + code |> shouldEqual 0 + log.Debug |> shouldContain "'A.fs' was ignored" + +[] +let ``a check that found files needing formatting exits 99`` () = + let code, log = + reportCheck ( + CheckCommandResult.Completed( + [], + { Errors = [] + Formatted = [ "A.fs"; "B.fs" ] } + ) + ) + + code |> shouldEqual 99 + + log.Information + |> shouldEqual [ "A.fs needs formatting"; "B.fs needs formatting" ] + +[] +let ``a check that could not format a file exits 1 rather than 99`` () = + let code, log = + reportCheck ( + CheckCommandResult.Completed( + [], + { Errors = [ "A.fs", Exception "boom" ] + Formatted = [ "A.fs" ] } + ) + ) + + code |> shouldEqual 1 + log.Error |> List.exactlyOne |> shouldContainText "Failed to format A.fs" diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 5e40f6f4f5..918b53e813 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -3,8 +3,17 @@ module Fantomas.Tests.TestHelpers open System open System.Diagnostics open System.IO +open System.IO.Abstractions open System.Text +open Serilog +open Serilog.Core +open Serilog.Events +open Spectre.Console open Fantomas +open Fantomas.Cli +open Fantomas.Core +open Fantomas.Logging +open Fantomas.Daemon [] module String = @@ -108,23 +117,144 @@ type FantomasIgnoreFile internal (content: string) = if File.Exists(filename) then File.Delete(filename) +/// Create every file, and the folders leading to it, in the given file system. +let makeFileHierarchy (fs: IFileSystem) (filePaths: string list) : unit = + for path in filePaths do + let fileInfo: IFileInfo = fs.FileInfo.New path + fileInfo.Directory.Create() + fs.File.WriteAllText(fileInfo.FullName, "some text") + +/// The root a `MockFileSystem` hangs its paths from, so that a test never writes a path by hand +/// and never has to know which platform it is running on. +let mockRoot (fs: IFileSystem) : string = + fs.Path.GetTempPath() |> fs.Path.GetPathRoot + +/// A logger that writes nowhere, for a test that does not care what was logged. +let silentLogger: ILogger = LoggerConfiguration().CreateLogger() + +/// What a run wrote, gathered per level rather than per stream: which stream a level lands on is +/// `Logging.createLogger`'s business, and this is about the messages. +type CollectedLog = + { Information: string list + Warning: string list + Error: string list + Fatal: string list + Debug: string list } + +type private CollectingSink() = + let events: ResizeArray = ResizeArray() + + member _.Events: LogEvent list = lock events (fun () -> List.ofSeq events) + + interface ILogEventSink with + member _.Emit(logEvent: LogEvent) : unit = + lock events (fun () -> events.Add logEvent) + +/// A logger that keeps what was written, and a way to read it back. +let collectingLogger () : ILogger * (unit -> CollectedLog) = + let sink: CollectingSink = CollectingSink() + + let logger: ILogger = + LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger() + + let collected () : CollectedLog = + let atLevel (level: LogEventLevel) : string list = + sink.Events + |> List.choose (fun (e: LogEvent) -> if e.Level = level then Some(e.RenderMessage()) else None) + + { Information = atLevel LogEventLevel.Information + Warning = atLevel LogEventLevel.Warning + Error = atLevel LogEventLevel.Error + Fatal = atLevel LogEventLevel.Fatal + Debug = atLevel LogEventLevel.Debug } + + logger, collected + +/// A Spectre console that draws into a string rather than onto a terminal. Colour and width are +/// pinned so that what it draws does not depend on the terminal the tests happen to run in. +let recordingConsole () : IAnsiConsole * (unit -> string) = + let writer: StringWriter = new StringWriter() + + let console: IAnsiConsole = + AnsiConsole.Create( + AnsiConsoleSettings( + Ansi = AnsiSupport.No, + ColorSystem = ColorSystemSupport.NoColors, + Out = AnsiConsoleOutput(writer) + ) + ) + + console.Profile.Width <- 200 + console, (fun () -> writer.ToString()) + +/// A `CliEnvironment` that keeps whatever a run writes, with the two ways to read it back. +[] +type RecordedRun = + { + Environment: CliEnvironment + /// What was logged, per level. + Log: unit -> CollectedLog + /// What Spectre drew, as text. + Drawn: unit -> string + } + +/// An environment over the given file system that records rather than prints, honouring the given +/// ignore file and reading no `.editorconfig`. +let recordingEnvironment (fs: IFileSystem) (ignoreFile: IgnoreFile option) : RecordedRun = + let logger, collected = collectingLogger () + let console, drawn = recordingConsole () + + { Environment = + { FileSystem = fs + IgnoreFile = ignoreFile + ReadConfiguration = + fun _ -> + { FormatConfig.Default with + EndOfLine = EndOfLineStyle.LF } + Log = logger + Console = console } + Log = collected + Drawn = drawn } + +/// The settings a run gets when nothing was asked for on the command line. +let defaultSettings: CliSettings = + { Force = false + Profile = false + Verbosity = VerbosityLevel.Normal } + +/// A `DaemonEnvironment` over the real file system, as the tool itself builds one. +let realDaemonEnvironment: DaemonEnvironment = + { FileSystem = FileSystem() + ReadConfiguration = EditorConfig.readConfiguration + Log = Log.Logger } + +/// A `CliEnvironment` over the real file system, honouring no ignore file. Enough for a test that +/// wants the tool's own behaviour without standing up a mock. +let realEnvironment: CliEnvironment = + { FileSystem = FileSystem() + IgnoreFile = None + ReadConfiguration = EditorConfig.readConfiguration + Log = Log.Logger + Console = AnsiConsole.Console } + type FantomasToolResult = { ExitCode: int Output: string Error: string } -let getFantomasToolStartInfo arguments : ProcessStartInfo = - let pwd = Path.GetDirectoryName(typeof.Assembly.Location) - - let configuration = +let getFantomasToolStartInfo (arguments: string list) : ProcessStartInfo = + let configuration: string = #if DEBUG "debug" #else "release" #endif - let fantomasDll = - Path.Combine(pwd, "..", "..", "Fantomas", configuration, "fantomas.dll") + // Resolved from where this file sits rather than from where the test assembly is running, + // because those are not the same place under a coverage run: AltCover executes the tests from + // an instrumented copy of the output folder. + let fantomasDll: string = + Path.Combine(__SOURCE_DIRECTORY__, "..", "..", "artifacts", "bin", "Fantomas", configuration, "fantomas.dll") |> Path.GetFullPath if not (File.Exists fantomasDll) then diff --git a/src/Fantomas.Tests/packages.lock.json b/src/Fantomas.Tests/packages.lock.json index e468ff2769..2c0511ee4e 100644 --- a/src/Fantomas.Tests/packages.lock.json +++ b/src/Fantomas.Tests/packages.lock.json @@ -2,6 +2,12 @@ "version": 2, "dependencies": { "net10.0": { + "altcover": { + "type": "Direct", + "requested": "[9.0.102, )", + "resolved": "9.0.102", + "contentHash": "q3Rf5t0M9kXlcO5qhsaAe6NrFSNd5enrhKmF/Ezgmomqw34PbUTbRSYjSDNhS3YGDyUrPTkyPn14EfLDJWztcA==" + }, "FsCheck": { "type": "Direct", "requested": "[3.3.2, )", diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs new file mode 100644 index 0000000000..7c4049d8e7 --- /dev/null +++ b/src/Fantomas/Arguments.fs @@ -0,0 +1,86 @@ +module Fantomas.Arguments + +open System.IO.Abstractions +open Argu +open Fantomas.Logging +open Fantomas.Paths + +// The Argu attributes live in the signature file. Repeating them here compiles only the +// signature's copy and warns about the two whose arguments the compiler cannot match up. +type Arguments = + | Force + | Profile + | Out of string + | Check + | Daemon + | Version + | Verbosity of string + | Input of string list + + interface IArgParserTemplate with + member s.Usage = + match s with + | Force -> "Print the output even if it is not valid F# code. For debugging purposes only." + | Out _ -> + "Give a valid path for files/folders. Files should have .fs, .fsx, .fsi, .ml or .mli extension only. Multiple files/folders are not supported." + | Profile -> "Print performance profiling information." + | Check -> + "Report which files need formatting and write nothing. Exits with 0 when every file is already formatted, with 99 when some file needs formatting, and with 1 when an error occurred." + | Daemon -> "Daemon mode, launches an LSP-like server that can be used by editor tooling." + | Version -> "Displays the version of Fantomas" + | Input _ -> + sprintf + "Input paths: can be multiple folders or files with %s extension." + (Seq.map (fun s -> "*" + s) extensions |> String.concat ",") + | Verbosity _ -> "Set the verbosity level. Allowed values are n[ormal] and d[etailed]." + +[] +type InputPath = + | File of string + | Folder of string + | Multiple of files: string list * folder: string list + | NoFSharpFile of string + | NotFound of string + | Unspecified + +[] +type OutputPath = + | IO of string + | NotKnown + +let classifyInputPath (fs: IFileSystem) (maybeInput: string list option) : InputPath = + match maybeInput with + | Some [ input ] -> + if fs.Directory.Exists(input) then + InputPath.Folder input + elif fs.File.Exists input && isFSharpFile input then + InputPath.File input + elif fs.File.Exists input then + InputPath.NoFSharpFile input + else + InputPath.NotFound input + | Some inputs -> + let missing: string option = + inputs + |> List.tryFind (fun x -> not (fs.Directory.Exists(x) || fs.File.Exists(x))) + + match missing with + | Some x -> InputPath.NotFound x + | None -> + // Every path here is known to exist, so which of the two it is can be asked rather + // than guessed from whether it carries an extension. Guessing called a folder named + // `my.stuff` a file, and a file with no extension a folder. + let folders, files = + inputs |> List.partition (fun (path: string) -> fs.Directory.Exists path) + + InputPath.Multiple(files, folders) + | None -> InputPath.Unspecified + +let parseVerbosity (value: string option) : VerbosityLevel option = + match value |> Option.map (fun v -> v.ToLowerInvariant()) with + | None + | Some "n" + | Some "normal" -> Some VerbosityLevel.Normal + | Some "d" + | Some "detailed" -> Some VerbosityLevel.Detailed + | Some _ -> None diff --git a/src/Fantomas/Arguments.fsi b/src/Fantomas/Arguments.fsi new file mode 100644 index 0000000000..1f3e6f7d5c --- /dev/null +++ b/src/Fantomas/Arguments.fsi @@ -0,0 +1,42 @@ +module Fantomas.Arguments + +open System.IO.Abstractions +open Argu +open Fantomas.Logging + +[] +type Arguments = + | [] Force + | [] Profile + | [] Out of string + | [] Check + | [] Daemon + | [] Version + | [] Verbosity of string + | [] Input of string list + + interface IArgParserTemplate + +/// What the input paths on the command line were found to name. +[] +type InputPath = + | File of string + | Folder of string + | Multiple of files: string list * folder: string list + | NoFSharpFile of string + | NotFound of string + | Unspecified + +/// Where the result should be written, which is back over the input unless `--out` said otherwise. +[] +type OutputPath = + | IO of string + | NotKnown + +/// Decide what the paths on the command line name, by asking the file system. Several paths are +/// all required to exist before any of them is classified, so one path that is not there is +/// reported rather than the rest being worked on. +val classifyInputPath: fs: IFileSystem -> maybeInput: string list option -> InputPath + +/// Read the `--verbosity` value. `None` means the value was not one Fantomas knows. +val parseVerbosity: value: string option -> VerbosityLevel option diff --git a/src/Fantomas/CheckCommand.fs b/src/Fantomas/CheckCommand.fs new file mode 100644 index 0000000000..3e015ee3ee --- /dev/null +++ b/src/Fantomas/CheckCommand.fs @@ -0,0 +1,66 @@ +module Fantomas.CheckCommand + +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.CommandResult +open Fantomas.FormatCommand +open Fantomas.Plan + +let checkCode (env: CliEnvironment) (filenames: string seq) : Async = + async { + let! formatted = + filenames + |> Seq.map (fun filename -> + async { + let! (content: string) = env.FileSystem.File.ReadAllTextAsync filename |> Async.AwaitTask + + let formatParams: FormatParams = + FormatParams.Create(env.ReadConfiguration filename, true, false, filename) + + return! formatContentAsync formatParams content + }) + |> Async.Parallel + + let getChangedFile: FormatResult -> string option = + function + | FormatResult.Unchanged _ + | FormatResult.IgnoredFile _ -> None + | FormatResult.Formatted(f, _, _) + | FormatResult.Error(f, _) + | FormatResult.InvalidCode(f, _) -> Some f + + let changes: string list = formatted |> Seq.choose getChangedFile |> Seq.toList + + let getErrors: FormatResult -> (string * exn) option = + function + | FormatResult.Error(f, e) -> Some(f, e) + | _ -> None + + let errors: (string * exn) list = formatted |> Seq.choose getErrors |> Seq.toList + + return { Errors = errors; Formatted = changes } + } + +let runCheckCommand (env: CliEnvironment) (inputPath: InputPath) : CheckCommandResult = + try + // A check never writes, so the output path it plans against is the input itself. + match plan env.FileSystem env.Log env.IgnoreFile inputPath OutputPath.NotKnown with + | Error problem -> CheckCommandResult.InvalidInput problem + | Ok items -> + let ignored: string list = + items + |> List.choose (fun item -> + match item with + | WorkItem.Ignored file -> Some file + | WorkItem.Format _ -> None) + + let toCheck: string list = + items + |> List.choose (fun item -> + match item with + | WorkItem.Ignored _ -> None + | WorkItem.Format(inputFile, _) -> Some inputFile) + + CheckCommandResult.Completed(ignored, Async.RunSynchronously(checkCode env toCheck)) + with exn -> + CheckCommandResult.Failed exn diff --git a/src/Fantomas/CheckCommand.fsi b/src/Fantomas/CheckCommand.fsi new file mode 100644 index 0000000000..be428439e4 --- /dev/null +++ b/src/Fantomas/CheckCommand.fsi @@ -0,0 +1,13 @@ +module Fantomas.CheckCommand + +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.CommandResult + +/// Format every file in memory and report which ones came out different, without writing anything. +/// Every file given is checked: whether a file should be skipped is settled in `Plan`, not here. +val checkCode: env: CliEnvironment -> filenames: string seq -> Async + +/// Find out which files need formatting, writing nothing. What was found is returned rather than +/// printed, so that a caller can inspect it before any of it reaches a console. +val runCheckCommand: env: CliEnvironment -> inputPath: InputPath -> CheckCommandResult diff --git a/src/Fantomas/Cli.fs b/src/Fantomas/Cli.fs new file mode 100644 index 0000000000..ec7c9dc48a --- /dev/null +++ b/src/Fantomas/Cli.fs @@ -0,0 +1,21 @@ +module Fantomas.Cli + +open System.IO.Abstractions +open Serilog +open Spectre.Console +open Fantomas +open Fantomas.Core +open Fantomas.Logging + +[] +type CliEnvironment = + { FileSystem: IFileSystem + IgnoreFile: IgnoreFile option + ReadConfiguration: string -> FormatConfig + Log: ILogger + Console: IAnsiConsole } + +type CliSettings = + { Force: bool + Profile: bool + Verbosity: VerbosityLevel } diff --git a/src/Fantomas/Cli.fsi b/src/Fantomas/Cli.fsi new file mode 100644 index 0000000000..8a902a32e2 --- /dev/null +++ b/src/Fantomas/Cli.fsi @@ -0,0 +1,35 @@ +module Fantomas.Cli + +open System.IO.Abstractions +open Serilog +open Spectre.Console +open Fantomas +open Fantomas.Core +open Fantomas.Logging + +/// How the tool reaches the world outside itself. Built once, in `main`, and handed down. A test +/// builds one over a `MockFileSystem` and a configuration of its choosing, and so never needs the +/// real file system or the directory the test host happens to be running in. +[] +type CliEnvironment = + { + FileSystem: IFileSystem + /// The single `.fantomasignore` this run honours, already found. + IgnoreFile: IgnoreFile option + /// The `.editorconfig` settings for a file. A function rather than a file system read, + /// because the editorconfig parser reads the disk itself and cannot be given one. + ReadConfiguration: string -> FormatConfig + /// Where the tool writes. A test hands over a logger with a collecting sink instead of + /// reading a console. Which stream a level lands on is the logger's own configuration, + /// not this record's. + Log: ILogger + /// Spectre's console, for the one thing drawn rather than written: the summary table. + Console: IAnsiConsole + } + +/// What the user asked for. Kept apart from the environment because a test varies these on every +/// case and the environment on almost none. +type CliSettings = + { Force: bool + Profile: bool + Verbosity: VerbosityLevel } diff --git a/src/Fantomas/CommandResult.fs b/src/Fantomas/CommandResult.fs new file mode 100644 index 0000000000..960ef9ce0c --- /dev/null +++ b/src/Fantomas/CommandResult.fs @@ -0,0 +1,45 @@ +module Fantomas.CommandResult + +open System +open Fantomas.Core + +type ProfileInfo = { LineCount: int; TimeTaken: TimeSpan } + +[] +type FormatResult = + | Formatted of filename: string * formattedContent: string * profileInfo: ProfileInfo option + | Unchanged of filename: string * profileInfo: ProfileInfo option + | InvalidCode of filename: string * formattedContent: string + | Error of filename: string * formattingError: exn + | IgnoredFile of filename: string + +[] +type CheckResult = + { Errors: (string * exn) list + Formatted: string list } + + member this.HasErrors = List.isNotEmpty this.Errors + member this.NeedsFormatting = List.isNotEmpty this.Formatted + member this.IsValid = List.isEmpty this.Errors && List.isEmpty this.Formatted + +let invalidResultException (file: string) : FormatException = + FormatException($"Formatting %s{file} leads to invalid F# code") + +[] +type InputProblem = + | UnsupportedFileType of path: string + | NotFound of path: string + | NoPathGiven + | MultiplePathsWithOut + +[] +type FormatCommandResult = + | InvalidInput of problem: InputProblem + | Completed of results: FormatResult array + | Failed of error: exn + +[] +type CheckCommandResult = + | InvalidInput of problem: InputProblem + | Completed of ignored: string list * result: CheckResult + | Failed of error: exn diff --git a/src/Fantomas/CommandResult.fsi b/src/Fantomas/CommandResult.fsi new file mode 100644 index 0000000000..4f996600ee --- /dev/null +++ b/src/Fantomas/CommandResult.fsi @@ -0,0 +1,56 @@ +module Fantomas.CommandResult + +open System + +type ProfileInfo = { LineCount: int; TimeTaken: TimeSpan } + +/// What formatting one file came to. +[] +type FormatResult = + | Formatted of filename: string * formattedContent: string * profileInfo: ProfileInfo option + | Unchanged of filename: string * profileInfo: ProfileInfo option + | InvalidCode of filename: string * formattedContent: string + | Error of filename: string * formattingError: exn + | IgnoredFile of filename: string + +[] +type CheckResult = + { Errors: (string * exn) list + Formatted: string list } + + member HasErrors: bool + + member IsValid: bool + + member NeedsFormatting: bool + +/// The failure that a `FormatResult.InvalidCode` stands for. Formatting produced something that is +/// not F#, which is a bug in Fantomas rather than in the file it was given. +val invalidResultException: file: string -> Fantomas.Core.FormatException + +/// A reason the input paths cannot be worked with. Both commands can end this way and both are +/// described from here, which is what keeps their wording from drifting apart. +[] +type InputProblem = + | UnsupportedFileType of path: string + | NotFound of path: string + | NoPathGiven + | MultiplePathsWithOut + +/// What a format run did. Turning this into text and into an exit code is `Report`'s job, so that +/// a caller can ask what happened without reading the console. +[] +type FormatCommandResult = + | InvalidInput of problem: InputProblem + | Completed of results: FormatResult array + /// Something was raised that no single file could be blamed for. + | Failed of error: exn + +/// What a `--check` run did. The ignored files are carried alongside, since a run that ignored +/// everything is not the same as a run that found nothing to do. +[] +type CheckCommandResult = + | InvalidInput of problem: InputProblem + | Completed of ignored: string list * result: CheckResult + /// Something was raised that no single file could be blamed for. + | Failed of error: exn diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index c5af67aaa1..1c110db0ac 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -13,8 +13,15 @@ open Fantomas.Client.Contracts open Fantomas.Client.LSPFantomasServiceTypes open Fantomas.Core open Fantomas.EditorConfig +open Serilog -type FantomasDaemon(sender: Stream, reader: Stream) as this = +[] +type DaemonEnvironment = + { FileSystem: IFileSystem + ReadConfiguration: string -> FormatConfig + Log: ILogger } + +type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironment) as this = let rpc: JsonRpc = JsonRpc.Attach(sender, reader, this) let traceListener = new DefaultTraceListener() @@ -27,7 +34,7 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = let exit () = disconnectEvent.Set() |> ignore - let fs = FileSystem() + let fs: IFileSystem = environment.FileSystem do rpc.Disconnected.Add(fun _ -> exit ()) @@ -36,7 +43,6 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = traceListener.Dispose() disconnectEvent.Dispose() - /// returns a hot task that resolves when the stream has terminated member this.WaitForClose = rpc.Completion [] @@ -47,6 +53,7 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = task { if IgnoreFile.isIgnoredFile + environment.Log (IgnoreFile.find fs (IgnoreFile.loadIgnoreList fs) request.FilePath) request.FilePath then @@ -55,9 +62,9 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = let config = match request.Config with | Some configProperties -> - let config = readConfiguration request.FilePath + let config = environment.ReadConfiguration request.FilePath parseOptionsFromEditorConfig config configProperties - | None -> readConfiguration request.FilePath + | None -> environment.ReadConfiguration request.FilePath let cursor = request.Cursor @@ -87,7 +94,7 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = // A ParseException's own Message is an %A dump of the diagnostic records, and // it is the editor's user who would have been shown it. let message = - Diagnostics.describeParseFailure request.FilePath request.SourceCode ex + Diagnostics.describeParseFailure request.FilePath (fun () -> request.SourceCode) ex |> Option.defaultValue ex.Message return FormatDocumentResponse.Error(request.FilePath, message) @@ -99,9 +106,9 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = let config = match request.Config with | Some configProperties -> - let config = readConfiguration request.FilePath + let config = environment.ReadConfiguration request.FilePath parseOptionsFromEditorConfig config configProperties - | None -> readConfiguration request.FilePath + | None -> environment.ReadConfiguration request.FilePath let selection = let r = request.Range @@ -126,7 +133,7 @@ type FantomasDaemon(sender: Stream, reader: Stream) as this = return FormatSelectionResponse.Formatted(request.FilePath, formatted, actualSelection) with ex -> let message = - Diagnostics.describeParseFailure request.FilePath request.SourceCode ex + Diagnostics.describeParseFailure request.FilePath (fun () -> request.SourceCode) ex |> Option.defaultValue ex.Message return FormatSelectionResponse.Error(request.FilePath, message) diff --git a/src/Fantomas/Daemon.fsi b/src/Fantomas/Daemon.fsi index bcd00dbd35..eac262c9c5 100644 --- a/src/Fantomas/Daemon.fsi +++ b/src/Fantomas/Daemon.fsi @@ -4,12 +4,24 @@ open System open System.IO open System.Threading.Tasks open StreamJsonRpc +open System.IO.Abstractions +open Serilog +open Fantomas.Core open Fantomas.Client.Contracts +/// How the daemon reaches the world outside itself. Narrower than the command line tool's +/// environment: the daemon looks for an ignore file per request rather than resolving one for the +/// run, and it draws nothing, so it needs neither a resolved ignore file nor a console. +[] +type DaemonEnvironment = + { FileSystem: IFileSystem + ReadConfiguration: string -> FormatConfig + Log: ILogger } + type FantomasDaemon = interface IDisposable - new: sender: Stream * reader: Stream -> FantomasDaemon + new: sender: Stream * reader: Stream * environment: DaemonEnvironment -> FantomasDaemon [] member Configuration: unit -> string diff --git a/src/Fantomas/Diagnostics.fs b/src/Fantomas/Diagnostics.fs index 95935ec510..a22495570b 100644 --- a/src/Fantomas/Diagnostics.fs +++ b/src/Fantomas/Diagnostics.fs @@ -115,7 +115,7 @@ let renderParseFailure (file: string) (source: string) (diagnostics: FSharpParse yield "" ] |> String.concat "\n" -let describeParseFailure (file: string) (source: string) (error: exn) : string option = +let describeParseFailure (file: string) (source: unit -> string) (error: exn) : string option = match error with - | ParseException diagnostics -> Some(renderParseFailure file source diagnostics) + | ParseException diagnostics -> Some(renderParseFailure file (source ()) diagnostics) | _ -> None diff --git a/src/Fantomas/Diagnostics.fsi b/src/Fantomas/Diagnostics.fsi index b27c21dcaa..f02a39684f 100644 --- a/src/Fantomas/Diagnostics.fsi +++ b/src/Fantomas/Diagnostics.fsi @@ -21,5 +21,9 @@ val renderParseFailure: file: string -> source: string -> diagnostics: FSharpPar /// Render `error` as the text to report for `file`, when it is a parse failure and therefore has /// diagnostics worth positioning. Anything else is not this module's to describe and comes back -/// as `None`. `source` is the text those diagnostics were produced from. -val describeParseFailure: file: string -> source: string -> error: exn -> string option +/// as `None`. +/// +/// `source` yields the text those diagnostics were produced from, and is called only once `error` +/// turns out to be a parse failure. A caller that has to read a file to produce it therefore does +/// not read one for a failure that has nothing to do with parsing. +val describeParseFailure: file: string -> source: (unit -> string) -> error: exn -> string option diff --git a/src/Fantomas/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index 001184d340..7189b17892 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -29,13 +29,26 @@ - - - + + + + + + + + + + + + + + + + diff --git a/src/Fantomas/Format.fs b/src/Fantomas/Format.fs deleted file mode 100644 index b89764d6e0..0000000000 --- a/src/Fantomas/Format.fs +++ /dev/null @@ -1,178 +0,0 @@ -namespace Fantomas - -open System -open System.IO -open Fantomas.Core - -type ProfileInfo = { LineCount: int; TimeTaken: TimeSpan } - -[] -type FormatResult = - | Formatted of filename: string * formattedContent: string * profileInfo: ProfileInfo option - | Unchanged of filename: string * profileInfo: ProfileInfo option - | InvalidCode of filename: string * formattedContent: string - | Error of filename: string * formattingError: Exception - | IgnoredFile of filename: string - -type FormatParams = - { Config: FormatConfig - CompareWithoutLineEndings: bool - Profile: bool - File: string } - - static member Create(config: FormatConfig, compareWithoutLineEndings: bool, profile: bool, file: string) = - { Config = config - CompareWithoutLineEndings = compareWithoutLineEndings - Profile = profile - File = file } - - static member Create(compareWithoutLineEndings: bool, profile: bool, file: string) = - { Config = EditorConfig.readConfiguration file - CompareWithoutLineEndings = compareWithoutLineEndings - Profile = profile - File = file } - -[] -type CheckResult = - { Errors: (string * exn) list - Formatted: string list } - - member this.HasErrors = List.isNotEmpty this.Errors - member this.NeedsFormatting = List.isNotEmpty this.Formatted - member this.IsValid = List.isEmpty this.Errors && List.isEmpty this.Formatted - -module Format = - - let private formatR = System.Text.RegularExpressions.Regex(@"\r") - - let private formatContentInternalAsync - (formatParams: FormatParams) - (originalContent: string) - : Async = - if IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) formatParams.File then - async { return FormatResult.IgnoredFile formatParams.File } - else - async { - try - let isSignatureFile = Path.GetExtension(formatParams.File) = ".fsi" - - let! { Code = formattedContent }, profileInfo = - if formatParams.Profile then - async { - let sw = Diagnostics.Stopwatch.StartNew() - - let! res = - CodeFormatter.FormatDocumentAsync( - isSignatureFile, - originalContent, - formatParams.Config - ) - - sw.Stop() - - let count = - originalContent.Length - originalContent.Replace(Environment.NewLine, "").Length - - let profileInfo = - { LineCount = count - TimeTaken = sw.Elapsed } - - return res, Some profileInfo - } - else - async { - let! res = - CodeFormatter.FormatDocumentAsync( - isSignatureFile, - originalContent, - formatParams.Config - ) - - return res, None - } - - let contentChanged = - if formatParams.CompareWithoutLineEndings then - let stripNewlines (s: string) = formatR.Replace(s, String.Empty) - - (stripNewlines originalContent) <> (stripNewlines formattedContent) - else - originalContent <> formattedContent - - if contentChanged then - let! isValid = CodeFormatter.IsValidFSharpCodeAsync(isSignatureFile, formattedContent) - - if not isValid then - return - FormatResult.InvalidCode( - filename = formatParams.File, - formattedContent = formattedContent - ) - else - return - FormatResult.Formatted( - filename = formatParams.File, - formattedContent = formattedContent, - profileInfo = profileInfo - ) - else - return FormatResult.Unchanged(filename = formatParams.File, profileInfo = profileInfo) - with ex -> - return FormatResult.Error(formatParams.File, ex) - } - - let formatContentAsync = formatContentInternalAsync - - let private formatFileInternalAsync (parms: FormatParams) = - if IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) parms.File then - async { return FormatResult.IgnoredFile parms.File } - else - - async { - let! originalContent = File.ReadAllTextAsync parms.File |> Async.AwaitTask - - let! formatted = originalContent |> formatContentInternalAsync parms - - return formatted - } - - let formatFileAsync = formatFileInternalAsync - - /// Runs a check on the given files and reports the result to the given output: - /// - /// * It shows the paths of the files that need formatting - /// * It shows the path and the error message of files that failed the format check - /// - /// Returns: - /// - /// A record with the file names that were formatted and the files that encounter problems while formatting. - let checkCode (filenames: string seq) = - async { - let! formatted = - filenames - |> Seq.choose (fun filename -> - if IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) filename then - None - else - Some(formatFileInternalAsync (FormatParams.Create(true, false, filename)))) - |> Async.Parallel - - let getChangedFile = - function - | FormatResult.Unchanged _ - | FormatResult.IgnoredFile _ -> None - | FormatResult.Formatted(f, _, _) - | FormatResult.Error(f, _) - | FormatResult.InvalidCode(f, _) -> Some f - - let changes = formatted |> Seq.choose getChangedFile |> Seq.toList - - let getErrors = - function - | FormatResult.Error(f, e) -> Some(f, e) - | _ -> None - - let errors = formatted |> Seq.choose getErrors |> Seq.toList - - return { Errors = errors; Formatted = changes } - } diff --git a/src/Fantomas/Format.fsi b/src/Fantomas/Format.fsi deleted file mode 100644 index 89729dd8b9..0000000000 --- a/src/Fantomas/Format.fsi +++ /dev/null @@ -1,49 +0,0 @@ -namespace Fantomas - -open System -open Fantomas.Core - -type ProfileInfo = { LineCount: int; TimeTaken: TimeSpan } - -[] -type FormatResult = - | Formatted of filename: string * formattedContent: string * profileInfo: ProfileInfo option - | Unchanged of filename: string * profileInfo: ProfileInfo option - | InvalidCode of filename: string * formattedContent: string - | Error of filename: string * formattingError: Exception - | IgnoredFile of filename: string - -type FormatParams = - { Config: FormatConfig - CompareWithoutLineEndings: bool - Profile: bool - File: string } - - static member Create: bool * bool * string -> FormatParams - static member Create: FormatConfig * bool * bool * string -> FormatParams - -[] -type CheckResult = - { Errors: (string * exn) list - Formatted: string list } - - member HasErrors: bool - - member IsValid: bool - - member NeedsFormatting: bool - -module Format = - val formatContentAsync: (FormatParams -> string -> Async) - - val formatFileAsync: (FormatParams -> Async) - - /// Runs a check on the given files and reports the result to the given output: - /// - /// * It shows the paths of the files that need formatting - /// * It shows the path and the error message of files that failed the format check - /// - /// Returns: - /// - /// A record with the file names that were formatted and the files that encounter problems while formatting. - val checkCode: filenames: string seq -> Async diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs new file mode 100644 index 0000000000..6f5a9909d6 --- /dev/null +++ b/src/Fantomas/FormatCommand.fs @@ -0,0 +1,223 @@ +module Fantomas.FormatCommand + +open System +open System.IO +open System.IO.Abstractions +open System.Text +open Fantomas.Core +open Fantomas +open Fantomas.Logging +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.CommandResult +open Fantomas.Paths +open Fantomas.Plan + +type FormatParams = + { Config: FormatConfig + CompareWithoutLineEndings: bool + Profile: bool + File: string } + + static member Create + (config: FormatConfig, compareWithoutLineEndings: bool, profile: bool, file: string) + : FormatParams = + { Config = config + CompareWithoutLineEndings = compareWithoutLineEndings + Profile = profile + File = file } + +// Built once rather than inside `stripNewlines`, which runs twice for every file checked. +let carriageReturn: Text.RegularExpressions.Regex = + Text.RegularExpressions.Regex(@"\r") + +let formatContentAsync (formatParams: FormatParams) (originalContent: string) : Async = + async { + try + let isSignatureFile: bool = Path.GetExtension(formatParams.File) = ".fsi" + + let! { Code = formattedContent }, profileInfo = + if formatParams.Profile then + async { + let sw: Diagnostics.Stopwatch = Diagnostics.Stopwatch.StartNew() + + let! res = + CodeFormatter.FormatDocumentAsync(isSignatureFile, originalContent, formatParams.Config) + + sw.Stop() + + // Counting line feeds rather than the platform's newline: a file written + // with the other platform's line endings has just as many lines. + let count: int = originalContent.Length - originalContent.Replace("\n", "").Length + + let profileInfo: ProfileInfo = + { LineCount = count + TimeTaken = sw.Elapsed } + + return res, Some profileInfo + } + else + async { + let! res = + CodeFormatter.FormatDocumentAsync(isSignatureFile, originalContent, formatParams.Config) + + return res, None + } + + let contentChanged: bool = + if formatParams.CompareWithoutLineEndings then + let stripNewlines (s: string) : string = carriageReturn.Replace(s, String.Empty) + + (stripNewlines originalContent) <> (stripNewlines formattedContent) + else + originalContent <> formattedContent + + if contentChanged then + let! (isValid: bool) = CodeFormatter.IsValidFSharpCodeAsync(isSignatureFile, formattedContent) + + if not isValid then + return FormatResult.InvalidCode(filename = formatParams.File, formattedContent = formattedContent) + else + return + FormatResult.Formatted( + filename = formatParams.File, + formattedContent = formattedContent, + profileInfo = profileInfo + ) + else + return FormatResult.Unchanged(filename = formatParams.File, profileInfo = profileInfo) + with ex -> + return FormatResult.Error(formatParams.File, ex) + } + +/// A file as it was read: its text, and whether it began with a byte order mark. Both come out of +/// one read, because the mark is in the same bytes the text is decoded from. +type SourceFile = + { Content: string + HasByteOrderMark: bool } + +/// Fantomas assumes the input files are UTF-8 +/// As is stated in F# language spec: https://fsharp.org/specs/language-spec/4.1/FSharpSpec-4.1-latest.pdf#page=25 +let readSourceFile (fs: IFileSystem) (file: string) : Async = + async { + use stream = fs.File.OpenRead file + + use reader = + new StreamReader(stream, UTF8Encoding(false), detectEncodingFromByteOrderMarks = true) + + let! (content: string) = reader.ReadToEndAsync() |> Async.AwaitTask + + // Opening the file again to look at its first three bytes would be needless: the reader has + // already read them to settle on an encoding. A file that carried a mark comes back as + // UTF-8 with that mark as its preamble, and one that did not keeps the encoding passed in, + // whose preamble is empty. Checking the code page as well keeps this to the UTF-8 mark, as + // reading the three bytes by hand did. + let encoding: Encoding = reader.CurrentEncoding + + return + { Content = content + HasByteOrderMark = encoding.CodePage = Encoding.UTF8.CodePage && encoding.GetPreamble().Length > 0 } + } + +/// Format content that is already in hand, settling there what `--force` means and what output +/// that is not valid F# comes to, so that a caller is left with one kind of failure to report. +let formatSource + (env: CliEnvironment) + (settings: CliSettings) + (source: SourceFile) + (file: string) + (config: FormatConfig) + : Async = + async { + let formatParams: FormatParams = + FormatParams.Create(config, false, settings.Profile, file) + + let! (formatted: FormatResult) = formatContentAsync formatParams source.Content + + match formatted with + | FormatResult.InvalidCode(f, formattedContent) when settings.Force -> + env.Log.Information $"%s{f} was not valid after formatting." + return FormatResult.Formatted(file, formattedContent, None) + | FormatResult.InvalidCode(f, _) -> return FormatResult.Error(f, invalidResultException f) + | FormatResult.Unchanged(f, _) as r -> + env.Log.Debug $"'%s{f}' was unchanged" + return r + | r -> return r + } + +// The formatted text is held in memory and the output file is opened only once there is something +// to put in it. Opening it up front truncates it before the input is read, which empties the input +// when both paths turn out to name the same file, and leaves a zero byte file behind whenever +// formatting does not complete. +let processFile + (env: CliEnvironment) + (settings: CliSettings) + (inputFile: string) + (outputFile: string) + : Async = + let fs: IFileSystem = env.FileSystem + + async { + try + env.Log.Debug $"Processing %s{inputFile}" + let! (source: SourceFile) = readSourceFile fs inputFile + let inPlace: bool = isSamePath fs inputFile outputFile + let! (result: FormatResult) = formatSource env settings source inputFile (env.ReadConfiguration inputFile) + + let toWrite: string option = + match result with + | FormatResult.Formatted(_, formattedContent, _) -> Some formattedContent + // Writing somewhere else has to carry an unchanged file across to it. Writing back + // over the input has nothing to do. + | FormatResult.Unchanged _ when not inPlace -> Some source.Content + | _ -> None + + match toWrite with + | None -> () + | Some contents -> + if not inPlace then + ensureParentFolderExists fs outputFile + + if source.HasByteOrderMark then + do! + fs.File.WriteAllTextAsync(outputFile, contents, Encoding.UTF8) + |> Async.AwaitTask + else + do! fs.File.WriteAllTextAsync(outputFile, contents) |> Async.AwaitTask + + env.Log.Debug $"%s{outputFile} has been written." + + return result + with e -> + return FormatResult.Error(inputFile, e) + } + +let runFormatCommand + (env: CliEnvironment) + (settings: CliSettings) + (inputPath: InputPath) + (outputPath: OutputPath) + : FormatCommandResult = + let fs: IFileSystem = env.FileSystem + + try + // An output folder is created even when the run turns out to have nothing to put in it, + // which is what a folder that is empty, or entirely ignored, comes to. + match inputPath, outputPath with + | InputPath.Folder _, OutputPath.IO outputFolder when not (fs.Directory.Exists outputFolder) -> + fs.Directory.CreateDirectory outputFolder |> ignore + | _ -> () + + match plan fs env.Log env.IgnoreFile inputPath outputPath with + | Error problem -> FormatCommandResult.InvalidInput problem + | Ok items -> + items + |> List.map (fun item -> + match item with + | WorkItem.Ignored file -> async.Return(FormatResult.IgnoredFile file) + | WorkItem.Format(inputFile, outputFile) -> processFile env settings inputFile outputFile) + |> Async.Parallel + |> Async.RunSynchronously + |> FormatCommandResult.Completed + with exn -> + FormatCommandResult.Failed exn diff --git a/src/Fantomas/FormatCommand.fsi b/src/Fantomas/FormatCommand.fsi new file mode 100644 index 0000000000..5d345ee08b --- /dev/null +++ b/src/Fantomas/FormatCommand.fsi @@ -0,0 +1,28 @@ +module Fantomas.FormatCommand + +open Fantomas.Core +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.CommandResult + +type FormatParams = + { Config: FormatConfig + CompareWithoutLineEndings: bool + Profile: bool + File: string } + + static member Create: FormatConfig * bool * bool * string -> FormatParams + +/// Format content that is already in hand. Whether the file should have been formatted at all is +/// the caller's business, decided once in `Plan`. +val formatContentAsync: formatParams: FormatParams -> originalContent: string -> Async + +/// Format the files the input path names, writing each result where the output path says. What +/// happened is returned rather than printed, so that a caller can inspect it before any of it +/// reaches a console. +val runFormatCommand: + env: CliEnvironment -> + settings: CliSettings -> + inputPath: InputPath -> + outputPath: OutputPath -> + FormatCommandResult diff --git a/src/Fantomas/HelpPage.fs b/src/Fantomas/HelpPage.fs index 81aa917517..6c40a071eb 100644 --- a/src/Fantomas/HelpPage.fs +++ b/src/Fantomas/HelpPage.fs @@ -6,69 +6,81 @@ open Argu open Spectre.Console open Fantomas.Core -// Select graphic rendition sequences, so a decorated string can still be measured. -let escapeSequence = Regex(@"\u001b\[[0-9;]*m", RegexOptions.Compiled) - -// What the terminal can do is Spectre.Console's answer to give: it knows the TERM values, it -// honours NO_COLOR, and it reports which colour system is available. -let capabilities = lazy AnsiConsole.Profile.Capabilities - -// Redirection is decided here rather than left to Spectre. Spectre turns ANSI back on when it -// detects a CI environment, because a CI log viewer renders escape codes and a progress bar -// there is worth colouring. A help page is not: it gets piped into a file, a pager or a script -// that reads it, on a build agent as much as anywhere else. Standard out being a terminal is -// the question this page needs answered, so both have to agree. -let colorsEnabled = - lazy - (not Console.IsOutputRedirected - && capabilities.Value.Ansi - && capabilities.Value.ColorSystem <> ColorSystem.NoColors) +[] +type Palette = + | NoColour + | FourBit + | EightBit -let eightBitColors = lazy (capabilities.Value.ColorSystem >= ColorSystem.EightBit) +// Select graphic rendition sequences, so a decorated string can still be measured. +let escapeSequence: Regex = Regex(@"\u001b\[[0-9;]*m", RegexOptions.Compiled) + +let detectPalette () : Palette = + // What the terminal can do is Spectre.Console's answer to give: it knows the TERM values, it + // honours NO_COLOR, and it reports which colour system is available. + let capabilities: Capabilities = AnsiConsole.Profile.Capabilities + + // Redirection is decided here rather than left to Spectre. Spectre turns ANSI back on when it + // detects a CI environment, because a CI log viewer renders escape codes and a progress bar + // there is worth colouring. A help page is not: it gets piped into a file, a pager or a script + // that reads it, on a build agent as much as anywhere else. Standard out being a terminal is + // the question this page needs answered, so both have to agree. + let colorsEnabled: bool = + not Console.IsOutputRedirected + && capabilities.Ansi + && capabilities.ColorSystem <> ColorSystem.NoColors + + if not colorsEnabled then + Palette.NoColour + elif capabilities.ColorSystem >= ColorSystem.EightBit then + Palette.EightBit + else + Palette.FourBit // The palette is written out as escape codes rather than drawn by Spectre, because Spectre // wraps what it writes to the console width and this page is laid out in fixed columns. -let decorate (eightBit: string) (fallback: string) (text: string) = - if not colorsEnabled.Value then - text - else - let code = if eightBitColors.Value then eightBit else fallback - String.Concat("\u001b[", code, "m", text, "\u001b[0m") +let decorate (palette: Palette) (eightBit: string) (fallback: string) (text: string) : string = + match palette with + | Palette.NoColour -> text + | Palette.EightBit -> String.Concat("\u001b[", eightBit, "m", text, "\u001b[0m") + | Palette.FourBit -> String.Concat("\u001b[", fallback, "m", text, "\u001b[0m") // 38;5;38 is the closest 256 colour to the blue the website uses. -let title text = decorate "1;38;5;38" "1;36" text -let link text = decorate "38;5;38" "36" text -let heading text = decorate "1" "1" text -let flagName text = decorate "1;38;5;80" "1;36" text -let placeholder text = decorate "38;5;245" "2" text -let muted text = decorate "2" "2" text +let title (palette: Palette) (text: string) : string = + decorate palette "1;38;5;38" "1;36" text -// The column the right hand half of a two column row starts in. -let descriptionColumn = 29 -let exampleColumn = 33 -let linkColumn = 29 +let link (palette: Palette) (text: string) : string = decorate palette "38;5;38" "36" text +let heading (palette: Palette) (text: string) : string = decorate palette "1" "1" text + +let flagName (palette: Palette) (text: string) : string = + decorate palette "1;38;5;80" "1;36" text + +let placeholder (palette: Palette) (text: string) : string = decorate palette "38;5;245" "2" text +let muted (palette: Palette) (text: string) : string = decorate palette "2" "2" text -let write (line: string) = Console.Out.WriteLine(line) -let blank () = Console.Out.WriteLine() +// The column the right hand half of a two column row starts in. +let descriptionColumn: int = 29 +let exampleColumn: int = 33 +let linkColumn: int = 29 -let visibleLength (text: string) = escapeSequence.Replace(text, "").Length +let visibleLength (text: string) : int = escapeSequence.Replace(text, "").Length -let writeRow (column: int) (left: string) (right: string) = - let padding = String(' ', max 1 (column - visibleLength left)) +let writeRow (write: string -> unit) (column: int) (left: string) (right: string) : unit = + let padding: string = String(' ', max 1 (column - visibleLength left)) write (String.Concat(left, padding, right)) -let writeContinuation (column: int) (right: string) = +let writeContinuation (write: string -> unit) (column: int) (right: string) : unit = write (String.Concat(String(' ', column), right)) // Trim the commit hash the version carries down to the short form git itself shows. -let shortVersion () = - let version = CodeFormatter.GetVersion() +let shortVersion () : string = + let version: string = CodeFormatter.GetVersion() match version.Split('+') with | [| number; commit |] when commit.Length > 9 -> String.Concat(number, "+", commit.Substring(0, 9)) | _ -> version -let flags = +let flags: (string * string * string * string list) list = [ ("", "--check", "", @@ -95,13 +107,13 @@ let flags = ("", "--version", "", [ "Print the version and exit" ]) ("-h", "--help", "", [ "Display this menu and exit" ]) ] -let examples = +let examples: (string * string) list = [ ("fantomas .", "Format every F# file below the current folder") ("fantomas src/App.fs", "Format a single file in place") ("fantomas --check .", "Report what needs formatting, write nothing") ("fantomas --out build src", "Copy the formatted files to another folder") ] -let links = +let links: (string * string list) list = [ ("Learn more about Fantomas:", [ "https://fsprojects.github.io/fantomas/docs" ]) ("Configure Fantomas:", [ "https://fsprojects.github.io/fantomas/docs/end-users/Configuration.html" ]) ("Join the F# Discord:", [ "https://discord.com/channels/196693847965696000/1493226271767924747" ]) @@ -109,78 +121,101 @@ let links = [ "https://fsprojects.github.io/fantomas/llms.txt" "https://fsprojects.github.io/fantomas/llms-full.txt" ]) ] -let writeFlag (short: string, long: string, argument: string, description: string list) = - let shortPart = +let writeFlag + (write: string -> unit) + (palette: Palette) + (short: string, long: string, argument: string, description: string list) + : unit = + let shortPart: string = if String.IsNullOrEmpty short then " " else - String.Concat(flagName short, ", ") + String.Concat(flagName palette short, ", ") - let argumentPart = + let argumentPart: string = if String.IsNullOrEmpty argument then "" else - String.Concat(" ", placeholder argument) + String.Concat(" ", placeholder palette argument) - let left = String.Concat(" ", shortPart, flagName long, argumentPart) + let left: string = + String.Concat(" ", shortPart, flagName palette long, argumentPart) match description with | [] -> write left | first :: rest -> - writeRow descriptionColumn left first - List.iter (writeContinuation descriptionColumn) rest + writeRow write descriptionColumn left first + List.iter (writeContinuation write descriptionColumn) rest -let writeExample (command: string, description: string) = - let name, arguments = +let writeExample (write: string -> unit) (palette: Palette) (command: string, description: string) : unit = + let name, arguments: string * string = match command.IndexOf ' ' with | -1 -> command, "" | i -> command.Substring(0, i), command.Substring(i) - writeRow exampleColumn (String.Concat(" ", muted name, flagName arguments)) description + writeRow write exampleColumn (String.Concat(" ", muted palette name, flagName palette arguments)) description -let writeLink (label: string, urls: string list) = +let writeLink (write: string -> unit) (palette: Palette) (label: string, urls: string list) : unit = match urls with | [] -> () | first :: rest -> - writeRow linkColumn label (link first) - List.iter (fun url -> writeContinuation linkColumn (link url)) rest + writeRow write linkColumn label (link palette first) + List.iter (fun (url: string) -> writeContinuation write linkColumn (link palette url)) rest + +let render (palette: Palette) : string list = + let lines: ResizeArray = ResizeArray() + let write (line: string) : unit = lines.Add line + let blank () : unit = lines.Add "" -let print () = write ( String.Concat( - title "Fantomas", + title palette "Fantomas", " is an opinionated source code formatter for F#. ", - muted (String.Concat("(", shortVersion (), ")")) + muted palette (String.Concat("(", shortVersion (), ")")) ) ) blank () - write (String.Concat(heading "Usage:", " ", heading "fantomas", " ", flagName "[...flags] [...paths]")) + + write ( + String.Concat( + heading palette "Usage:", + " ", + heading palette "fantomas", + " ", + flagName palette "[...flags] [...paths]" + ) + ) + blank () - write (heading "Examples:") - List.iter writeExample examples + write (heading palette "Examples:") + List.iter (writeExample write palette) examples blank () - write (heading "Flags:") - List.iter writeFlag flags + write (heading palette "Flags:") + List.iter (writeFlag write palette) flags blank () - write (heading "Paths:") + write (heading palette "Paths:") write " A path is a folder, which is searched recursively, or a file ending in .fs, .fsi," write " .fsx, .ml or .mli. Formatting settings are read from .editorconfig, and files" write " matched by .fantomasignore in the current folder are skipped." blank () - List.iter writeLink links + List.iter (writeLink write palette) links blank () + List.ofSeq lines + +let print () : unit = + render (detectPalette ()) |> List.iter Console.Out.WriteLine // Argu builds a usage block of its own and hands it over as part of the message. Only the // first line carries the actual complaint, so the rest is dropped in favour of a pointer to // the page above. -let complaint (message: string) = +let complaint (message: string) : string = message.Split('\n') - |> Array.tryFind (fun line -> line.StartsWith("ERROR:", StringComparison.Ordinal)) + |> Array.tryFind (fun (line: string) -> line.StartsWith("ERROR:", StringComparison.Ordinal)) |> Option.defaultValue message - |> fun line -> line.Trim() + |> fun (line: string) -> line.Trim() -let exiter = +let exiter: IExiter = { new IExiter with member _.Name = "Fantomas help page" diff --git a/src/Fantomas/HelpPage.fsi b/src/Fantomas/HelpPage.fsi index 4700b318fb..315c2804b3 100644 --- a/src/Fantomas/HelpPage.fsi +++ b/src/Fantomas/HelpPage.fsi @@ -1,10 +1,27 @@ module Fantomas.HelpPage +/// How much colour the page may use. +[] +type Palette = + | NoColour + | FourBit + | EightBit + +/// What the terminal standard out is attached to will take. Colours are dropped when standard out +/// is redirected, so piping the page into a file or a pager yields plain text. +val detectPalette: unit -> Palette + +/// The `fantomas --help` page, as the lines it is made of. Nothing is written, so a caller can +/// look at the page without a console. +val render: palette: Palette -> string list + /// Write the `fantomas --help` page to standard out. -/// Colours are emitted only when standard out is a terminal that wants them, -/// so redirecting the output yields plain text. val print: unit -> unit +/// The line of Argu's message that carries the actual complaint. Argu builds a usage block of its +/// own and hands it over as part of the message; only the first line says what went wrong. +val complaint: message: string -> string + /// Error handler for Argu. `--help` renders the page above, and an argument error is /// reported on standard error, followed by a pointer to the page. /// Argu's own generated usage text is never shown. diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index 4a7bf2b002..e046f70abc 100644 --- a/src/Fantomas/IgnoreFile.fs +++ b/src/Fantomas/IgnoreFile.fs @@ -2,7 +2,7 @@ namespace Fantomas open System.IO.Abstractions open Ignore -open Fantomas.Logging +open Serilog type AbsoluteFilePath = private @@ -15,8 +15,6 @@ type AbsoluteFilePath = static member Create (fs: IFileSystem) (filePath: string) = fs.Path.GetFullPath filePath |> AbsoluteFilePath -/// The string argument is taken relative to the location -/// of the ignore-file. type IsPathIgnored = AbsoluteFilePath -> bool [] @@ -30,10 +28,6 @@ module IgnoreFile = [] let IgnoreFileName = ".fantomasignore" - /// Find the `.fantomasignore` file above the given filepath, if one exists. - /// Note that this is intended for use only in the daemon; the command-line tool - /// does not support `.fantomasignore` files anywhere other than the current - /// working directory. let find (fs: IFileSystem) (loadIgnoreList: string -> IsPathIgnored) (filePath: string) : IgnoreFile option = let rec walkUp (currentDirectory: IDirectoryInfo) : IgnoreFile option = if isNull currentDirectory then @@ -52,43 +46,51 @@ module IgnoreFile = walkUp (fs.FileInfo.New(filePath).Directory) let loadIgnoreList (fs: IFileSystem) (ignoreFilePath: string) : IsPathIgnored = - let lines = fs.File.ReadAllLines(ignoreFilePath) + let lines: string array = fs.File.ReadAllLines(ignoreFilePath) - let fantomasIgnore = + let fantomasIgnore: Ignore = (Ignore(), lines) ||> Array.fold (fun (ig: Ignore) (line: string) -> ig.Add(line)) + // The folder holding the ignore file does not change between calls, and looking it up + // again for every file walked meant a directory lookup per file. + let ignoreRoot: string = fs.Directory.GetParent(ignoreFilePath).FullName + fun (absoluteFilePath: AbsoluteFilePath) -> // See https://git-scm.com/docs/gitignore // We transform the incoming path relative to the .ignoreFilePath folder. // In a cli scenario that is the current directory, for the daemon it is the first found ignore file. // .gitignore uses forward slashes to path separators - let relativePath = - fs.Path - .GetRelativePath(fs.Directory.GetParent(ignoreFilePath).FullName, absoluteFilePath.Path) - .Replace("\\", "/") + let relativePath: string = + fs.Path.GetRelativePath(ignoreRoot, absoluteFilePath.Path).Replace("\\", "/") fantomasIgnore.IsIgnored(relativePath) - let internal current' (fs: IFileSystem) (currentDirectory: string) (loadIgnoreList: string -> IsPathIgnored) = - lazy find fs loadIgnoreList (fs.Path.Combine(currentDirectory, "_")) - - /// When executed from the command line, Fantomas will not dynamically locate - /// the most appropriate `.fantomasignore` for each input file; it only finds - /// a single `.fantomasignore` file. This is that file. - let current: Lazy = - let fs = FileSystem() - current' fs System.Environment.CurrentDirectory (loadIgnoreList fs) + let findInDirectory + (fs: IFileSystem) + (currentDirectory: string) + (loadIgnoreList: string -> IsPathIgnored) + : IgnoreFile option = + // `find` walks up from a file, so it is given a name that need not exist in the directory. + find fs loadIgnoreList (fs.Path.Combine(currentDirectory, "_")) - let isIgnoredFile (ignoreFile: IgnoreFile option) (file: string) : bool = + let isIgnoredFile (log: ILogger) (ignoreFile: IgnoreFile option) (file: string) : bool = match ignoreFile with | None -> false | Some ignoreFile -> - let fs = ignoreFile.Location.FileSystem - let fullPath = AbsoluteFilePath.Create fs file + let fs: IFileSystem = ignoreFile.Location.FileSystem + let fullPath: AbsoluteFilePath = AbsoluteFilePath.Create fs file try ignoreFile.IsIgnored fullPath with ex -> - elog $"%A{ex}" + // Matching a path against the ignore file is not something that should fail. If it + // does, say which file and which ignore file could not be told apart, and go on to + // format the file rather than abandon the run over it. + log.Error + $"Could not tell whether '%s{file}' is matched by %s{ignoreFile.Location.FullName}: %s{ex.Message}" + + // The line above is the one to act on; this keeps the type and the stack trace for + // whoever asks for detail. + log.Debug $"%A{ex}" false diff --git a/src/Fantomas/IgnoreFile.fsi b/src/Fantomas/IgnoreFile.fsi index e12134a589..079d30f25c 100644 --- a/src/Fantomas/IgnoreFile.fsi +++ b/src/Fantomas/IgnoreFile.fsi @@ -1,6 +1,7 @@ namespace Fantomas open System.IO.Abstractions +open Serilog type AbsoluteFilePath = private @@ -32,15 +33,12 @@ module IgnoreFile = val loadIgnoreList: fs: IFileSystem -> ignoreFilePath: string -> IsPathIgnored - val internal current': - fs: IFileSystem -> - currentDirectory: string -> - loadIgnoreList: (string -> IsPathIgnored) -> - Lazy + /// The `.fantomasignore` the command line tool honours: the single one at or above the + /// directory the tool was started from. The daemon instead finds the closest one to each + /// file it is asked about. + val findInDirectory: + fs: IFileSystem -> currentDirectory: string -> loadIgnoreList: (string -> IsPathIgnored) -> IgnoreFile option - /// When executed from the command line, Fantomas will not dynamically locate - /// the most appropriate `.fantomasignore` for each input file; it only finds - /// a single `.fantomasignore` file. This is that file. - val current: Lazy - - val isIgnoredFile: ignoreFile: IgnoreFile option -> file: string -> bool + /// Is the file matched by the ignore file? Deciding that is not something that should fail; + /// if it does, the failure is reported through the sink and the file counts as not ignored. + val isIgnoredFile: log: ILogger -> ignoreFile: IgnoreFile option -> file: string -> bool diff --git a/src/Fantomas/Logging.fs b/src/Fantomas/Logging.fs index 46e7ee5126..fc3680173b 100644 --- a/src/Fantomas/Logging.fs +++ b/src/Fantomas/Logging.fs @@ -33,10 +33,4 @@ let initLogger (level: VerbosityLevel) : VerbosityLevel = let initDaemonLogger (level: VerbosityLevel) : VerbosityLevel = createLogger level LogEventLevel.Verbose -let stdlog (s: string) = Log.Logger.Information(s) - -let elog (s: string) = Log.Logger.Error(s) - -let logGrEqDetailed s = Log.Logger.Debug(s) - -let closeAndFlushLog () = Log.CloseAndFlush() +let closeAndFlushLog () : unit = Log.CloseAndFlush() diff --git a/src/Fantomas/Logging.fsi b/src/Fantomas/Logging.fsi index 69f8539a20..257021a24a 100644 --- a/src/Fantomas/Logging.fsi +++ b/src/Fantomas/Logging.fsi @@ -15,13 +15,5 @@ val initLogger: level: VerbosityLevel -> VerbosityLevel /// corrupt the protocol stream and fault the client connection. val initDaemonLogger: level: VerbosityLevel -> VerbosityLevel -/// log a message -val stdlog: s: string -> unit - -/// log an error -val elog: s: string -> unit - -/// log a message if the verbosity level is >= Detailed -val logGrEqDetailed: s: string -> unit - +/// Flush anything the logger is still holding and shut it down. val closeAndFlushLog: unit -> unit diff --git a/src/Fantomas/Paths.fs b/src/Fantomas/Paths.fs new file mode 100644 index 0000000000..1954ef0472 --- /dev/null +++ b/src/Fantomas/Paths.fs @@ -0,0 +1,57 @@ +module Fantomas.Paths + +open System +open System.Collections.Generic +open System.IO +open System.IO.Abstractions + +let extensions: Set = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] + +// The extension is compared without case, so that a file named A.FS is the F# file it plainly is. +// On a volume that ignores case, which is the usual one on macOS and Windows, rejecting it would +// mean refusing to format a file the compiler happily builds. A set that ignores case does that +// without lowering a copy of every extension it is asked about; this runs once per file walked. +let extensionLookup: HashSet = + HashSet(extensions, StringComparer.OrdinalIgnoreCase) + +// The names to look for, with a separator either side so that `objects` is not read as `obj`. +// Worked out once: building them per file made walking a folder several times slower than it +// needs to be. +let excludedDirFragments: string array = + [| for dir in [| "obj"; ".fable"; "fable_modules"; "node_modules" |] -> + String.Concat(string Path.DirectorySeparatorChar, dir, string Path.DirectorySeparatorChar) |] + +let isInExcludedDir (fullPath: string) : bool = + excludedDirFragments + |> Array.exists (fun (fragment: string) -> fullPath.Contains(fragment, StringComparison.Ordinal)) + +let isFSharpFile (s: string) : bool = + extensionLookup.Contains(Path.GetExtension s) + +let findAllFilesRecursively (fs: IFileSystem) (path: string) : string seq = + fs.Directory.GetFiles(path, "*.*", SearchOption.AllDirectories) + |> Seq.filter (fun f -> isFSharpFile f && not (isInExcludedDir f)) + +let ensureParentFolderExists (fs: IFileSystem) (file: string) : unit = + let folder: string = fs.Path.GetDirectoryName(file) + + if not (String.IsNullOrEmpty folder) then + fs.Directory.CreateDirectory(folder) |> ignore + +let isSamePath (fs: IFileSystem) (left: string) (right: string) : bool = + // A trailing separator names the same place, so `src` and `src/` have to compare equal. They + // do not otherwise, and a folder formatted to itself under the longer spelling would be taken + // for a previous run's output and skipped entirely. + let resolve (path: string) : string = + fs.Path.GetFullPath(path).TrimEnd(fs.Path.DirectorySeparatorChar, fs.Path.AltDirectorySeparatorChar) + + String.Equals(resolve left, resolve right, StringComparison.Ordinal) + +let isInFolder (fs: IFileSystem) (folder: string) (file: string) : bool = + let folder: string = + String.Concat( + fs.Path.GetFullPath(folder).TrimEnd(fs.Path.DirectorySeparatorChar), + string fs.Path.DirectorySeparatorChar + ) + + fs.Path.GetFullPath(file).StartsWith(folder, StringComparison.Ordinal) diff --git a/src/Fantomas/Paths.fsi b/src/Fantomas/Paths.fsi new file mode 100644 index 0000000000..7ece3d3038 --- /dev/null +++ b/src/Fantomas/Paths.fsi @@ -0,0 +1,28 @@ +module Fantomas.Paths + +open System.IO.Abstractions + +/// The file extensions Fantomas formats. +val extensions: Set + +/// Is the path inside a folder whose contents a compiler or a package manager wrote? +val isInExcludedDir: fullPath: string -> bool + +val isFSharpFile: s: string -> bool + +/// Every F# file below the given path, at any depth. Build output and package folders are +/// skipped: formatting what a compiler or a package manager wrote is never what was asked for. +val findAllFilesRecursively: fs: IFileSystem -> path: string -> string seq + +/// Create the folders leading up to a file, so that writing to a path the user named but never +/// created succeeds. GetDirectoryName yields an empty string for a bare file name. +val ensureParentFolderExists: fs: IFileSystem -> file: string -> unit + +/// Do two paths name the same location? `src` and `./src` do, and comparing them as they were +/// typed does not say so. This is about spelling, not about the file system: a path reached +/// through a symbolic link, or through a spelling a case insensitive volume accepts, is not +/// recognised here. Nothing may depend on a negative answer to avoid destroying a file. +val isSamePath: fs: IFileSystem -> left: string -> right: string -> bool + +/// Is a file located inside a folder, at any depth? +val isInFolder: fs: IFileSystem -> folder: string -> file: string -> bool diff --git a/src/Fantomas/Plan.fs b/src/Fantomas/Plan.fs new file mode 100644 index 0000000000..05ef4911fe --- /dev/null +++ b/src/Fantomas/Plan.fs @@ -0,0 +1,64 @@ +module Fantomas.Plan + +open System.IO.Abstractions +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult +open Serilog +open Fantomas.Paths + +[] +type WorkItem = + | Ignored of file: string + | Format of inputFile: string * outputFile: string + +let plan + (fs: IFileSystem) + (log: ILogger) + (ignoreFile: IgnoreFile option) + (inputPath: InputPath) + (outputPath: OutputPath) + : Result = + let item (inputFile: string) (outputFile: string) : WorkItem = + if IgnoreFile.isIgnoredFile log ignoreFile inputFile then + WorkItem.Ignored inputFile + else + WorkItem.Format(inputFile, outputFile) + + let folder (inputFolder: string) (outputFolder: string) : WorkItem list = + let inPlace: bool = isSamePath fs inputFolder outputFolder + + // The output folder mirrors the input tree. Keeping only the file name would let two files + // with the same name in different subfolders overwrite each other. + let destinationOf (inputFile: string) : string = + if inPlace then + inputFile + else + fs.Path.Combine(outputFolder, fs.Path.GetRelativePath(inputFolder, inputFile)) + + // An output folder inside the input folder is walked over as well, so the previous run's + // results would be formatted again and nested one level deeper every time. + let isPreviousOutput (inputFile: string) : bool = + not inPlace && isInFolder fs outputFolder inputFile + + findAllFilesRecursively fs inputFolder + |> Seq.choose (fun i -> + if isPreviousOutput i then + None + else + Some(item i (destinationOf i))) + |> Seq.toList + + match inputPath, outputPath with + | InputPath.NoFSharpFile s, _ -> Error(InputProblem.UnsupportedFileType s) + | InputPath.NotFound s, _ -> Error(InputProblem.NotFound s) + | InputPath.Unspecified, _ -> Error InputProblem.NoPathGiven + | InputPath.Multiple _, OutputPath.IO _ -> Error InputProblem.MultiplePathsWithOut + | InputPath.File p, OutputPath.NotKnown -> Ok [ item p p ] + | InputPath.File p, OutputPath.IO o -> Ok [ item p o ] + | InputPath.Folder p, OutputPath.NotKnown -> Ok(folder p p) + | InputPath.Folder p, OutputPath.IO o -> Ok(folder p o) + | InputPath.Multiple(files, folders), OutputPath.NotKnown -> + Ok + [ yield! List.map (fun f -> item f f) files + yield! List.collect (fun f -> folder f f) folders ] diff --git a/src/Fantomas/Plan.fsi b/src/Fantomas/Plan.fsi new file mode 100644 index 0000000000..22d5429a21 --- /dev/null +++ b/src/Fantomas/Plan.fsi @@ -0,0 +1,25 @@ +module Fantomas.Plan + +open System.IO.Abstractions +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult +open Serilog + +/// One file's worth of work. Whether a file is ignored is settled here, once, rather than asked +/// again at every layer that touches the file. +[] +type WorkItem = + | Ignored of file: string + | Format of inputFile: string * outputFile: string + +/// Turn the input and output paths into the list of files to work on, with each output path +/// already worked out. This is where a folder becomes its files, where an output tree is mirrored +/// onto an input tree, and where the ignore file is consulted. +val plan: + fs: IFileSystem -> + log: ILogger -> + ignoreFile: IgnoreFile option -> + inputPath: InputPath -> + outputPath: OutputPath -> + Result diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 53a73bb88b..6c12838553 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -1,318 +1,58 @@ +module Program + open System -open System.IO +open System.IO.Abstractions open Fantomas.Core open Fantomas open Fantomas.Daemon open Fantomas.Logging +open Fantomas.Arguments +open Fantomas.Cli +open Fantomas.FormatCommand +open Fantomas.Report +open Fantomas.CheckCommand open Argu -open System.Text +open Serilog open Spectre.Console -let extensions = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] - -[] -type Arguments = - | [] Force - | [] Profile - | [] Out of string - | [] Check - | [] Daemon - | [] Version - | [] Verbosity of string - | [] Input of string list - - interface IArgParserTemplate with - member s.Usage = - match s with - | Force -> "Print the output even if it is not valid F# code. For debugging purposes only." - | Out _ -> - "Give a valid path for files/folders. Files should have .fs, .fsx, .fsi, .ml or .mli extension only. Multiple files/folders are not supported." - | Profile -> "Print performance profiling information." - | Check -> - "Report which files need formatting and write nothing. Exits with 0 when every file is already formatted, with 99 when some file needs formatting, and with 1 when an error occurred." - | Daemon -> "Daemon mode, launches an LSP-like server that can be used by editor tooling." - | Version -> "Displays the version of Fantomas" - | Input _ -> - sprintf - "Input paths: can be multiple folders or files with %s extension." - (Seq.map (fun s -> "*" + s) extensions |> String.concat ",") - | Verbosity _ -> "Set the verbosity level. Allowed values are n[ormal] and d[etailed]." - -[] -type InputPath = - | File of string - | Folder of string - | Multiple of files: string list * folder: string list - | NoFSharpFile of string - | NotFound of string - | Unspecified - -[] -type OutputPath = - | IO of string - | NotKnown - -type Table with - - member x.SetBorder(border: TableBorder) = - x.Border <- border - x - -let isInExcludedDir (fullPath: string) = - set [| "obj"; ".fable"; "fable_modules"; "node_modules" |] - |> Set.map (fun dir -> sprintf "%c%s%c" Path.DirectorySeparatorChar dir Path.DirectorySeparatorChar) - |> Set.exists fullPath.Contains - -let isFSharpFile (s: string) = - Set.contains (Path.GetExtension s) extensions - -/// Get all appropriate files, recursively. -let findAllFilesRecursively path = - let searchOption = SearchOption.AllDirectories - - Directory.GetFiles(path, "*.*", searchOption) - |> Seq.filter (fun f -> isFSharpFile f && not (isInExcludedDir f)) - -/// Create the folders leading up to a file, so that writing to a path the user named but never -/// created succeeds. Path.GetDirectoryName yields an empty string for a bare file name. -let ensureParentFolderExists (file: string) : unit = - let folder = Path.GetDirectoryName(file) - - if not (String.IsNullOrEmpty folder) then - Directory.CreateDirectory(folder) |> ignore - -/// Do two paths name the same location? `src` and `./src` do, and comparing them as they were -/// typed does not say so. This is about spelling, not about the file system: a path reached -/// through a symbolic link, or through a spelling a case insensitive volume accepts, is not -/// recognised here. Nothing may depend on a negative answer to avoid destroying a file. -let isSamePath (left: string) (right: string) : bool = - String.Equals(Path.GetFullPath left, Path.GetFullPath right, StringComparison.Ordinal) - -/// Is a file located inside a folder, at any depth? -let isInFolder (folder: string) (file: string) : bool = - let folder = - String.Concat( - Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar), - string Path.DirectorySeparatorChar - ) - - Path.GetFullPath(file).StartsWith(folder, StringComparison.Ordinal) - -/// Fantomas assumes the input files are UTF-8 -/// As is stated in F# language spec: https://fsharp.org/specs/language-spec/4.1/FSharpSpec-4.1-latest.pdf#page=25 -let private hasByteOrderMark file = - async { - if File.Exists(file) then - let preamble = Encoding.UTF8.GetPreamble() - - use file = new FileStream(file, FileMode.Open, FileAccess.Read) - - let mutable bom = Array.zeroCreate 3 - do! file.ReadAsync(bom, 0, 3) |> Async.AwaitTask |> Async.Ignore - return bom = preamble - else - return false - } - -let private invalidResultException (file: string) = - FormatException($"Formatting %s{file} leads to invalid F# code") - -/// Format a source string using given config and write to a text writer -let processSourceString (force: bool) (profile: bool) s (fileName: string) config = - let writeResult (formatted: string) = - async { - let! hasBom = hasByteOrderMark fileName - - if hasBom then - do! File.WriteAllTextAsync(fileName, formatted, Encoding.UTF8) |> Async.AwaitTask - else - do! File.WriteAllTextAsync(fileName, formatted) |> Async.AwaitTask - - logGrEqDetailed $"%s{fileName} has been written." - } - - async { - let formatParams = FormatParams.Create(config, false, profile, fileName) - let! formatted = s |> Format.formatContentAsync formatParams - - match formatted with - | FormatResult.Formatted(_, formattedContent, _) as r -> - do! formattedContent |> writeResult - return r - | FormatResult.InvalidCode(file, formattedContent) when force -> - stdlog $"%s{file} was not valid after formatting." - do! formattedContent |> writeResult - return FormatResult.Formatted(fileName, formattedContent, None) - | FormatResult.Unchanged(file, _) as r -> - logGrEqDetailed $"'%s{file}' was unchanged" - return r - | FormatResult.IgnoredFile file as r -> - logGrEqDetailed $"'%s{file}' was ignored" - return r - | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> - let ex = invalidResultException file - return FormatResult.Error(file, ex) - } - -/// Format inFile and write to text writer -let processSourceFile (force: bool) (profile: bool) inFile (tw: TextWriter) = - async { - let! formatted = FormatParams.Create(false, profile, inFile) |> Format.formatFileAsync - - match formatted with - | FormatResult.Formatted(_, formattedContent, _) as r -> - do! tw.WriteAsync(formattedContent) |> Async.AwaitTask - return r - | FormatResult.InvalidCode(file, formattedContent) when force -> - stdlog $"%s{file} was not valid after formatting." - do! tw.WriteAsync(formattedContent) |> Async.AwaitTask - return FormatResult.Formatted(inFile, formattedContent, None) - | FormatResult.Unchanged _ as r -> - let! input = inFile |> File.ReadAllTextAsync |> Async.AwaitTask - do! input |> tw.WriteAsync |> Async.AwaitTask - return r - | FormatResult.IgnoredFile file as r -> - logGrEqDetailed $"'%s{file}' was ignored" - return r - | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> - let ex = invalidResultException file - return FormatResult.Error(file, ex) - } - -// The context lines a parse failure's snippet is drawn from come from the file itself. This is -// the error path's last act before the tool gives up on the file, so reading it again is free. -let sourceOf (file: string) : string = - try - File.ReadAllText file - with _ -> - String.Empty - -let reportCheckResults (checkResult: CheckResult) = - for filename, exn in checkResult.Errors do - match Diagnostics.describeParseFailure filename (sourceOf filename) exn with - | Some parseFailure -> elog parseFailure - | None -> elog $"error: Failed to format %s{filename}: %s{exn.ToString()}" - - for filename in checkResult.Formatted do - stdlog $"%s{filename} needs formatting" - -let runCheckCommand (inputPath: InputPath) : int = - let check files = - Async.RunSynchronously(Format.checkCode files) - - let processCheckResult (checkResult: CheckResult) = - if checkResult.IsValid then - logGrEqDetailed "No changes required." - 0 - else - reportCheckResults checkResult - if checkResult.HasErrors then 1 else 99 - - match inputPath with - | InputPath.NoFSharpFile s -> - elog $"Input path '%s{s}' is unsupported file type" - 1 - | InputPath.NotFound s -> - elog $"Input path '%s{s}' not found" - 1 - | InputPath.Unspecified -> - elog "No input path provided. Call with --help for usage information." - 1 - | InputPath.File f when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> - logGrEqDetailed $"'%s{f}' was ignored" - 0 - | InputPath.File path -> path |> Seq.singleton |> check |> processCheckResult - | InputPath.Folder path -> path |> findAllFilesRecursively |> check |> processCheckResult - | InputPath.Multiple(files, folders) -> - let allFilesToCheck = - seq { - yield! files - yield! (Seq.collect findAllFilesRecursively folders) - } - - allFilesToCheck |> check |> processCheckResult - +/// Parse the command line and run whichever command it names: printing the version, serving the +/// daemon, checking whether files need formatting, or formatting them. Returns the exit code the +/// process should end with. [] let main argv = // Argu never gets to render a usage text of its own: HelpPage.exiter answers --help with // the Fantomas help page and reduces an argument error to its first line. - let parser = + let parser: ArgumentParser = ArgumentParser.Create(programName = "fantomas", errorHandler = HelpPage.exiter) - let results = parser.ParseCommandLine argv + let results: ParseResults = parser.ParseCommandLine argv - let outputPath = + let outputPath: OutputPath = match results.TryGetResult <@ Arguments.Out @> with | Some output -> OutputPath.IO output | None -> OutputPath.NotKnown - let inputPath = - let maybeInput = results.TryGetResult <@ Arguments.Input @> - - match maybeInput with - | Some [ input ] -> - if Directory.Exists(input) then - InputPath.Folder input - elif File.Exists input && isFSharpFile input then - InputPath.File input - elif File.Exists input then - InputPath.NoFSharpFile input - else - InputPath.NotFound input - | Some inputs -> - let missing = - inputs |> List.tryFind (fun x -> not (Directory.Exists(x) || File.Exists(x))) - - match missing with - | Some x -> InputPath.NotFound x - | None -> - let isFolder (path: string) = - String.IsNullOrWhiteSpace(Path.GetExtension(path)) - - let rec loop - (files: string list) - (finalContinuation: string list * string list -> string list * string list) - = - match files with - | [] -> finalContinuation ([], []) - | h :: rest -> - loop rest (fun (files, folders) -> - if isFolder h then - files, (h :: folders) - else - (h :: files), folders - |> finalContinuation) + let fileSystem: IFileSystem = FileSystem() - let filesAndFolders = loop inputs id - InputPath.Multiple filesAndFolders - | None -> InputPath.Unspecified + let inputPath: InputPath = + results.TryGetResult <@ Arguments.Input @> |> classifyInputPath fileSystem - let force = results.Contains <@ Arguments.Force @> - let profile = results.Contains <@ Arguments.Profile @> - let version = results.TryGetResult <@ Arguments.Version @> + let force: bool = results.Contains <@ Arguments.Force @> + let profile: bool = results.Contains <@ Arguments.Profile @> + let version: Arguments option = results.TryGetResult <@ Arguments.Version @> - let maybeVerbosity = - results.TryGetResult <@ Arguments.Verbosity @> - |> Option.map (fun v -> v.ToLowerInvariant()) - - let verbosityLevel = - match maybeVerbosity with - | None - | Some "n" - | Some "normal" -> VerbosityLevel.Normal - | Some "d" - | Some "detailed" -> VerbosityLevel.Detailed - | Some _ -> - // The logger is not up yet, so this cannot go through elog. + let verbosityLevel: VerbosityLevel = + match parseVerbosity (results.TryGetResult <@ Arguments.Verbosity @>) with + | Some level -> level + | None -> + // The logger is not configured yet, so this cannot go through it. eprintfn "Invalid verbosity level" exit 1 - let isDaemon = results.Contains <@ Arguments.Daemon @> + let isDaemon: bool = results.Contains <@ Arguments.Daemon @> // In daemon mode standard out carries the JSON-RPC protocol, so the logger must stay off it. - let verbosity = + let verbosity: VerbosityLevel = if isDaemon then initDaemonLogger verbosityLevel else @@ -320,247 +60,61 @@ let main argv = AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> closeAndFlushLog ()) - // The formatted text is collected in memory and the output file is opened only once there - // is something to put in it. Opening it up front truncates it before the input is read, - // which empties the input when both paths turn out to name the same file, and leaves a - // zero byte file behind whenever formatting does not complete. - let fileToFile (force: bool) (inFile: string) (outFile: string) : Async = - async { - logGrEqDetailed $"Processing %s{inFile}" - use buffer = new StringWriter() - let! processResult = processSourceFile force profile inFile buffer - - match processResult with - | FormatResult.Formatted _ - | FormatResult.Unchanged _ -> - let! hasByteOrderMark = hasByteOrderMark inFile - ensureParentFolderExists outFile - let contents = buffer.ToString() - - if hasByteOrderMark then - do! File.WriteAllTextAsync(outFile, contents, Encoding.UTF8) |> Async.AwaitTask - else - do! File.WriteAllTextAsync(outFile, contents) |> Async.AwaitTask - - logGrEqDetailed $"%s{outFile} has been written." - | FormatResult.IgnoredFile _ - | FormatResult.InvalidCode _ - | FormatResult.Error _ -> () - - return processResult - } - - let stringToFile (force: bool) (s: string) (outFile: string) config = - async { return! processSourceString force profile s outFile config } - - let processFile (force: bool) (inputFile: string) (outputFile: string) : Async = - async { - try - if not (isSamePath inputFile outputFile) then - return! fileToFile force inputFile outputFile - else - logGrEqDetailed $"Processing %s{inputFile}" - let! content = File.ReadAllTextAsync inputFile |> Async.AwaitTask - let config = EditorConfig.readConfiguration inputFile - return! stringToFile force content inputFile config - with e -> - return FormatResult.Error(inputFile, e) - } - - let processFolder (force: bool) (inputFolder: string) (outputFolder: string) : Async list = - if not <| Directory.Exists(outputFolder) then - Directory.CreateDirectory(outputFolder) |> ignore - - let inPlace = isSamePath inputFolder outputFolder - - findAllFilesRecursively inputFolder - // An output folder inside the input folder is walked over as well, so the previous run's - // results would be formatted again and nested one level deeper every time. - |> Seq.filter (fun i -> inPlace || not (isInFolder outputFolder i)) - |> Seq.toList - |> List.map (fun i -> - - let o = - if inPlace then - i - else - // The output folder mirrors the input tree. Keeping only the file name would - // let two files with the same name in different subfolders overwrite each other. - // fileToFile creates the folders leading up to the file. - Path.Combine(outputFolder, Path.GetRelativePath(inputFolder, i)) - - processFile force i o) - - let filesAndFolders force (files: string list) (folders: string list) = - let fileTasks = - files - |> List.map (fun file -> - if (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) file) then - logGrEqDetailed $"'%s{file}' was ignored" - async.Return(FormatResult.IgnoredFile(file)) - else - processFile force file file) - - let folderTasks = - folders |> List.collect (fun folder -> processFolder force folder folder) - - (fileTasks @ folderTasks) - - let check = results.Contains <@ Arguments.Check @> + // The logger the calls above configured, now handed down rather than reached for. + let log: ILogger = Log.Logger - let partitionResults (results: #(FormatResult seq)) = - (([], [], [], []), results) - ||> Seq.fold (fun (oks, ignores, unchanged, errors) next -> - match next with - | FormatResult.Formatted(file, _, p) -> ((file, p) :: oks, ignores, unchanged, errors) - | FormatResult.IgnoredFile i -> (oks, i :: ignores, unchanged, errors) - | FormatResult.Unchanged(file, p) -> (oks, ignores, (file, p) :: unchanged, errors) - | FormatResult.Error(file, e) -> (oks, ignores, unchanged, (file, e) :: errors) - | FormatResult.InvalidCode(file, _) -> - let ex = invalidResultException file - (oks, ignores, unchanged, (file, ex) :: errors)) + let check: bool = results.Contains <@ Arguments.Check @> - let reportFormatResults (results: #(FormatResult seq)) = - let reportError (file: string, exn: Exception) = - let describeOther () : string = - let message = - match verbosity with - | VerbosityLevel.Normal -> - match exn with - | :? DefineParseException as dpe -> - let combinations = - dpe.Combinations - |> List.map (fun c -> if c = "no defines" then "no defines" else $"[%s{c}]") - |> String.concat ", " - - $"When Fantomas encounters #if directives in a file, it tries to format all possible combinations of defines and will merge all different versions back into one.\nFor %s{combinations}, however, we were not able to parse the file.\nWhile you may not use this combination in your project, Fantomas requires it to produce valid code.\nConsider fixing the code or ignoring this file.\nFor more information see: https://fsprojects.github.io/fantomas/docs/end-users/ConditionalCompilationDirectives.html" - | :? FormatException as fe -> fe.Message - | _ -> "" - | VerbosityLevel.Detailed -> $"%A{exn}" - - if String.IsNullOrEmpty message then - $"Failed to format file: %s{file}" - else - $"Failed to format file: %s{file} : %s{message}" - - // A parse failure describes itself, positions and all, rather than being reduced to a - // single line saying only that it happened. - match Diagnostics.describeParseFailure file (sourceOf file) exn with - | Some parseFailure -> elog parseFailure - | None -> elog (describeOther ()) - - let reportProfileInfos (results: (string * ProfileInfo option) list) = - if profile && not (List.isEmpty results) then - let table = Table().AddColumns([| "File"; "Line count"; "Time taken" |]) - - results - |> List.choose (fun (f, p) -> p |> Option.map (fun p -> f, p)) - |> List.sortBy fst - |> List.fold - (fun (t: Table) (f, p) -> - t.AddRow([| f; string p.LineCount; p.TimeTaken.ToString("mm\:ss\.fff") |])) - table - |> AnsiConsole.Write - - match Seq.tryExactlyOne results with - | Some singleResult -> - let reportProfileInfo (f, p: ProfileInfo option) = - match profile, p with - | true, Some pI -> stdlog $"%s{f} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" - | _ -> () - - match singleResult with - | FormatResult.Formatted(f, _, p) -> - stdlog $"%s{f} was formatted." - reportProfileInfo (f, p) - | FormatResult.IgnoredFile f -> stdlog $"%s{f} was ignored." - | FormatResult.Unchanged(f, p) -> - stdlog $"%s{f} was unchanged." - reportProfileInfo (f, p) - | FormatResult.Error(f, e) -> - reportError (f, e) - exit 1 - | FormatResult.InvalidCode(f, _) -> - let ex = invalidResultException f - reportError (f, ex) - exit 1 - - | None -> - let oks, ignored, unchanged, errored = partitionResults results - let centeredColumn (v: string) = TableColumn(v).Centered() - - Table() - .AddColumns( - [| "[green]Formatted[/]" - string oks.Length - "Ignored" - string ignored.Length - "[blue]Unchanged[/]" - string unchanged.Length - "[red]Errored[/]" - string errored.Length |] - |> Array.map centeredColumn - ) - .SetBorder(TableBorder.MinimalDoubleHead) - |> AnsiConsole.Write - - for e in errored do - reportError e - - reportProfileInfos (oks @ unchanged) - - if errored.Length > 0 then - exit 1 - - let asyncRunner = Async.Parallel >> Async.RunSynchronously - - let versionLog = - let version = CodeFormatter.GetVersion() + let versionLog: string = + let version: string = CodeFormatter.GetVersion() $"Fantomas v%s{version}" if Option.isNone version then - logGrEqDetailed versionLog + log.Debug versionLog if Option.isSome version then - stdlog versionLog + log.Information versionLog + 0 elif isDaemon then - let daemon = - new FantomasDaemon(Console.OpenStandardOutput(), Console.OpenStandardInput()) + let daemon: FantomasDaemon = + new FantomasDaemon( + Console.OpenStandardOutput(), + Console.OpenStandardInput(), + { FileSystem = fileSystem + ReadConfiguration = EditorConfig.readConfiguration + Log = log } + ) AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> (daemon :> IDisposable).Dispose()) daemon.WaitForClose.GetAwaiter().GetResult() - exit 0 - elif check then - inputPath |> runCheckCommand |> exit + 0 else + // Reading `.fantomasignore` can fail on a pattern the ignore library will not compile, and + // building the environment is the first thing either command needs, so it happens under + // the same guard the commands run under rather than before it. try - match inputPath, outputPath with - | InputPath.NoFSharpFile s, _ -> - elog $"Input path '%s{s}' is unsupported file type." - exit 1 - | InputPath.NotFound s, _ -> - elog $"Input path '%s{s}' not found." - exit 1 - | InputPath.Unspecified, _ -> - elog "Input path is missing. Call with --help for usage information." - exit 1 - | InputPath.File f, _ when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> - logGrEqDetailed $"'%s{f}' was ignored" - | InputPath.Folder p1, OutputPath.NotKnown -> - processFolder force p1 p1 |> asyncRunner |> reportFormatResults - | InputPath.File p1, OutputPath.NotKnown -> - processFile force p1 p1 |> List.singleton |> asyncRunner |> reportFormatResults - | InputPath.File p1, OutputPath.IO p2 -> - processFile force p1 p2 |> List.singleton |> asyncRunner |> reportFormatResults - | InputPath.Folder p1, OutputPath.IO p2 -> processFolder force p1 p2 |> asyncRunner |> reportFormatResults - | InputPath.Multiple(files, folders), OutputPath.NotKnown -> - filesAndFolders force files folders |> asyncRunner |> reportFormatResults - | InputPath.Multiple _, OutputPath.IO _ -> - elog "Multiple input files are not supported with the --out flag." - exit 1 + let environment: CliEnvironment = + { FileSystem = fileSystem + IgnoreFile = + IgnoreFile.findInDirectory + fileSystem + Environment.CurrentDirectory + (IgnoreFile.loadIgnoreList fileSystem) + ReadConfiguration = EditorConfig.readConfiguration + Log = log + Console = AnsiConsole.Console } + + let settings: CliSettings = + { Force = force + Profile = profile + Verbosity = verbosity } + + if check then + runCheckCommand environment inputPath |> reportCheckCommand environment + else + runFormatCommand environment settings inputPath outputPath + |> reportFormatCommand environment settings with exn -> - elog $"%s{exn.Message}" - exit 1 - - 0 + log.Error $"%s{exn.Message}" + 1 diff --git a/src/Fantomas/Program.fsi b/src/Fantomas/Program.fsi deleted file mode 100644 index 7b0639493f..0000000000 --- a/src/Fantomas/Program.fsi +++ /dev/null @@ -1,3 +0,0 @@ -module Program - -val main: argv: string array -> int diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs new file mode 100644 index 0000000000..9e67c145ad --- /dev/null +++ b/src/Fantomas/Report.fs @@ -0,0 +1,179 @@ +module Fantomas.Report + +open System +open System.IO.Abstractions +open Serilog +open Spectre.Console +// Fantomas.Core has a FormatResult of its own. Opening Fantomas last is what makes the +// FormatResult named here the one this project defines. +open Fantomas.Core +open Fantomas +open Fantomas.Cli +open Fantomas.CommandResult +open Fantomas.Logging + +// The context lines a parse failure's snippet is drawn from come from the file itself. This is +// the error path's last act before the tool gives up on the file, so reading it again is free. +let sourceOf (fs: IFileSystem) (file: string) : string = + try + fs.File.ReadAllText file + with _ -> + String.Empty + +let partitionResults + (results: #(FormatResult seq)) + : (string * ProfileInfo option) list * string list * (string * ProfileInfo option) list * (string * exn) list = + (([], [], [], []), results) + ||> Seq.fold (fun (oks, ignores, unchanged, errors) next -> + match next with + | FormatResult.Formatted(file, _, p) -> ((file, p) :: oks, ignores, unchanged, errors) + | FormatResult.IgnoredFile i -> (oks, i :: ignores, unchanged, errors) + | FormatResult.Unchanged(file, p) -> (oks, ignores, (file, p) :: unchanged, errors) + | FormatResult.Error(file, e) -> (oks, ignores, unchanged, (file, e) :: errors) + | FormatResult.InvalidCode(file, _) -> + let ex: FormatException = invalidResultException file + (oks, ignores, unchanged, (file, ex :> exn) :: errors)) + +let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, error: exn) : unit = + let describeOther () : string = + let message: string = + match verbosity with + | VerbosityLevel.Normal -> + match error with + | :? DefineParseException as dpe -> + let combinations: string = + dpe.Combinations + |> List.map (fun c -> if c = "no defines" then "no defines" else $"[%s{c}]") + |> String.concat ", " + + $"When Fantomas encounters #if directives in a file, it tries to format all possible combinations of defines and will merge all different versions back into one.\nFor %s{combinations}, however, we were not able to parse the file.\nWhile you may not use this combination in your project, Fantomas requires it to produce valid code.\nConsider fixing the code or ignoring this file.\nFor more information see: https://fsprojects.github.io/fantomas/docs/end-users/ConditionalCompilationDirectives.html" + | :? FormatException as fe -> fe.Message + | _ -> "" + | VerbosityLevel.Detailed -> $"%A{error}" + + if String.IsNullOrEmpty message then + $"Failed to format file: %s{file}" + else + $"Failed to format file: %s{file} : %s{message}" + + // A parse failure describes itself, positions and all, rather than being reduced to a + // single line saying only that it happened. + match Diagnostics.describeParseFailure file (fun () -> sourceOf env.FileSystem file) error with + | Some parseFailure -> env.Log.Error parseFailure + | None -> env.Log.Error(describeOther ()) + +let reportProfileInfo (log: ILogger) (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = + match profile, profileInfo with + | true, Some pI -> log.Information $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" + | _ -> () + +let reportProfileInfos (console: IAnsiConsole) (profile: bool) (results: (string * ProfileInfo option) list) : unit = + if profile && not (List.isEmpty results) then + let table: Table = Table().AddColumns([| "File"; "Line count"; "Time taken" |]) + + results + |> List.choose (fun (f, p) -> p |> Option.map (fun p -> f, p)) + |> List.sortBy fst + |> List.fold + (fun (t: Table) (f, p) -> t.AddRow([| f; string p.LineCount; p.TimeTaken.ToString("mm\:ss\.fff") |])) + table + |> console.Write + +let reportFormatResults (env: CliEnvironment) (settings: CliSettings) (results: #(FormatResult seq)) : int = + match Seq.tryExactlyOne results with + | Some singleResult -> + match singleResult with + | FormatResult.Formatted(f, _, p) -> + env.Log.Information $"%s{f} was formatted." + reportProfileInfo env.Log settings.Profile (f, p) + 0 + | FormatResult.IgnoredFile f -> + env.Log.Information $"%s{f} was ignored." + 0 + | FormatResult.Unchanged(f, p) -> + env.Log.Information $"%s{f} was unchanged." + reportProfileInfo env.Log settings.Profile (f, p) + 0 + | FormatResult.Error(f, e) -> + reportError env settings.Verbosity (f, e) + 1 + | FormatResult.InvalidCode(f, _) -> + let ex: FormatException = invalidResultException f + reportError env settings.Verbosity (f, ex) + 1 + + | None -> + let oks, ignored, unchanged, errored = partitionResults results + let centeredColumn (v: string) : TableColumn = TableColumn(v).Centered() + + let summary: Table = + Table() + .AddColumns( + [| "[green]Formatted[/]" + string oks.Length + "Ignored" + string ignored.Length + "[blue]Unchanged[/]" + string unchanged.Length + "[red]Errored[/]" + string errored.Length |] + |> Array.map centeredColumn + ) + + summary.Border <- TableBorder.MinimalDoubleHead + env.Console.Write summary + + for file in ignored do + env.Log.Debug $"'%s{file}' was ignored" + + for e in errored do + reportError env settings.Verbosity e + + reportProfileInfos env.Console settings.Profile (oks @ unchanged) + + if errored.Length > 0 then 1 else 0 + +let reportCheckResults (env: CliEnvironment) (checkResult: CheckResult) : unit = + for filename, exn in checkResult.Errors do + match Diagnostics.describeParseFailure filename (fun () -> sourceOf env.FileSystem filename) exn with + | Some parseFailure -> env.Log.Error parseFailure + | None -> env.Log.Error $"error: Failed to format %s{filename}: %s{exn.ToString()}" + + for filename in checkResult.Formatted do + env.Log.Information $"%s{filename} needs formatting" + +let describeInputProblem (problem: InputProblem) : string = + match problem with + | InputProblem.UnsupportedFileType path -> $"Input path '%s{path}' is an unsupported file type." + | InputProblem.NotFound path -> $"Input path '%s{path}' not found." + | InputProblem.NoPathGiven -> "No input path provided. Call with --help for usage information." + | InputProblem.MultiplePathsWithOut -> "Multiple input files are not supported with the --out flag." + +let reportFormatCommand (env: CliEnvironment) (settings: CliSettings) (result: FormatCommandResult) : int = + match result with + | FormatCommandResult.InvalidInput problem -> + env.Log.Error(describeInputProblem problem) + 1 + | FormatCommandResult.Failed error -> + env.Log.Error $"%s{error.Message}" + 1 + | FormatCommandResult.Completed results -> reportFormatResults env settings results + +let reportCheckCommand (env: CliEnvironment) (result: CheckCommandResult) : int = + match result with + | CheckCommandResult.InvalidInput problem -> + env.Log.Error(describeInputProblem problem) + 1 + | CheckCommandResult.Failed error -> + env.Log.Error $"%s{error.Message}" + 1 + | CheckCommandResult.Completed(ignored, checkResult) -> + for file in ignored do + env.Log.Debug $"'%s{file}' was ignored" + + if checkResult.IsValid then + env.Log.Debug "No changes required." + 0 + else + reportCheckResults env checkResult + if checkResult.HasErrors then 1 else 99 diff --git a/src/Fantomas/Report.fsi b/src/Fantomas/Report.fsi new file mode 100644 index 0000000000..3d0cc05bf7 --- /dev/null +++ b/src/Fantomas/Report.fsi @@ -0,0 +1,16 @@ +module Fantomas.Report + +open Fantomas.Cli +open Fantomas.CommandResult + +/// The single wording for each way the input paths can fail to make sense. Both commands are +/// described from here, so neither can drift away from the other. +val describeInputProblem: problem: InputProblem -> string + +/// Report what a format run did, and return the exit code the process should end with: 1 when +/// anything failed, 0 otherwise. +val reportFormatCommand: env: CliEnvironment -> settings: CliSettings -> result: FormatCommandResult -> int + +/// Report what a `--check` run found, and return the exit code the process should end with: 0 when +/// every file is already formatted, 99 when at least one needs formatting, and 1 on failure. +val reportCheckCommand: env: CliEnvironment -> result: CheckCommandResult -> int