From 6d48ddb035ef156c78c5b86830e3b425cd51ac60 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 10:41:05 +0200 Subject: [PATCH 01/17] Lift the CLI's logic out of main into top-level functions Almost everything the command line tool does lived inside main, as local bindings closing over force, profile and verbosity. Program.fsi exposes only main, so none of it could be called from a test, and the integration suite had to start a real fantomas process to exercise any of it. Move fileToFile, processFile, processFolder, filesAndFolders, partitionResults, reportError, reportProfileInfo, reportProfileInfos and reportFormatResults to top level, taking force, profile and verbosity as parameters, and lift the classification of the input paths out as classifyInputPath. No behaviour changes; main is now value bindings and the dispatch alone. Drop stringToFile, which was an eta-expansion of processSourceString with no other caller, and drop private from hasByteOrderMark and invalidResultException, since the signature file is already the visibility boundary here. Document the larger functions. Two existing comments were wrong rather than thin: processSourceString claimed to write to a text writer when it writes back over the file it was given, and findAllFilesRecursively did not mention that build output and package folders are skipped. --- src/Fantomas/Program.fs | 541 ++++++++++++++++++++++----------------- src/Fantomas/Program.fsi | 3 + 2 files changed, 302 insertions(+), 242 deletions(-) diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 53a73bb88b..3825a415f5 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -66,7 +66,8 @@ let isInExcludedDir (fullPath: string) = let isFSharpFile (s: string) = Set.contains (Path.GetExtension s) extensions -/// Get all appropriate files, recursively. +/// 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. let findAllFilesRecursively path = let searchOption = SearchOption.AllDirectories @@ -100,7 +101,7 @@ let isInFolder (folder: string) (file: string) : 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 private hasByteOrderMark file = +let hasByteOrderMark (file: string) : Async = async { if File.Exists(file) then let preamble = Encoding.UTF8.GetPreamble() @@ -114,10 +115,13 @@ let private hasByteOrderMark file = return false } -let private invalidResultException (file: string) = +let invalidResultException (file: string) : FormatException = FormatException($"Formatting %s{file} leads to invalid F# code") -/// Format a source string using given config and write to a text writer +/// Format content that has already been read, and write the result back over `fileName`. The +/// byte order mark the file started with is put back, since formatting is not the place to +/// decide a file's encoding. With `force`, output that failed the validity check is written +/// anyway and reported as a success. let processSourceString (force: bool) (profile: bool) s (fileName: string) config = let writeResult (formatted: string) = async { @@ -155,7 +159,8 @@ let processSourceString (force: bool) (profile: bool) s (fileName: string) confi return FormatResult.Error(file, ex) } -/// Format inFile and write to text writer +/// Format a file and write the result to `tw`. A file that needed no change is copied across +/// verbatim rather than skipped, so the caller receives the full content whatever the outcome. let processSourceFile (force: bool) (profile: bool) inFile (tw: TextWriter) = async { let! formatted = FormatParams.Create(false, profile, inFile) |> Format.formatFileAsync @@ -189,6 +194,8 @@ let sourceOf (file: string) : string = with _ -> String.Empty +/// Write one line per file that needs formatting, and a described failure for every file that +/// could not be formatted at all. let reportCheckResults (checkResult: CheckResult) = for filename, exn in checkResult.Errors do match Diagnostics.describeParseFailure filename (sourceOf filename) exn with @@ -198,6 +205,9 @@ let reportCheckResults (checkResult: CheckResult) = for filename in checkResult.Formatted do stdlog $"%s{filename} needs formatting" +/// Report which files need formatting and write nothing. Returns the exit code the process +/// should end with: 0 when every file is already formatted, 99 when at least one needs +/// formatting, and 1 when an input path was unusable or a file could not be formatted. let runCheckCommand (inputPath: InputPath) : int = let check files = Async.RunSynchronously(Format.checkCode files) @@ -234,6 +244,271 @@ let runCheckCommand (inputPath: InputPath) : int = allFilesToCheck |> check |> processCheckResult +/// Decide what the paths on the command line name. A single path is classified by asking the +/// file system about it. Several paths are all required to exist first, and are then told apart +/// by whether they carry a file extension, so `src` is taken as a folder and `src.fs` as a file. +let classifyInputPath (maybeInput: string list option) : InputPath = + 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) + + InputPath.Multiple(loop inputs id) + | None -> InputPath.Unspecified + +/// Format `inFile` and write the result to `outFile`, creating the folders leading up to it if +/// they are not there yet. +// 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) (profile: 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 + } + +/// Format one file to one destination. Writing back over the input is a different operation +/// from writing somewhere else, and is kept apart here: in place, the content has to be read +/// before anything is written. A failure is returned as an `Error` result rather than raised, so +/// that one unformattable file does not abandon the rest of the run. +let processFile (force: bool) (profile: bool) (inputFile: string) (outputFile: string) : Async = + async { + try + if not (isSamePath inputFile outputFile) then + return! fileToFile force profile inputFile outputFile + else + logGrEqDetailed $"Processing %s{inputFile}" + let! content = File.ReadAllTextAsync inputFile |> Async.AwaitTask + let config = EditorConfig.readConfiguration inputFile + return! processSourceString force profile content inputFile config + with e -> + return FormatResult.Error(inputFile, e) + } + +/// Format every F# file below `inputFolder`, writing each one to the matching place under +/// `outputFolder` so that the output mirrors the input tree. When the two folders name the same +/// place the files are formatted where they lie. +let processFolder + (force: bool) + (profile: 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 profile i o) + +/// Format an explicit list of files along with every F# file below the given folders. All of it +/// is formatted in place, which is the only thing on offer once more than one input path is +/// named. +let filesAndFolders + (force: bool) + (profile: bool) + (files: string list) + (folders: string list) + : Async 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 profile file file) + + let folderTasks = + folders + |> List.collect (fun folder -> processFolder force profile folder folder) + + (fileTasks @ folderTasks) + +/// Sort the results into what was formatted, ignored, left unchanged, and failed. Code that came +/// out invalid is counted as a failure and carries an exception saying so, which leaves the +/// caller one kind of thing to report rather than two. +let partitionResults + (results: #(FormatResult seq)) + : (string * ProfileInfo option) list * string list * (string * ProfileInfo option) list * (string * Exception) 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 = invalidResultException file + (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) + +/// Describe one failure on standard error. A parse failure is reported in full, positions and +/// surrounding source included. Anything else is reduced to a single line, unless the verbosity +/// asks for the whole exception. +let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = + 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 reportProfileInfo (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = + match profile, profileInfo with + | true, Some pI -> stdlog $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" + | _ -> () + +/// Print the line count and the time taken per file, when profiling was asked for. +let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) list) : unit = + 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 + +/// Report the outcome of a run. A single file is reported as a sentence naming it, and several +/// files as a table of counts, because a table of one row tells the reader less than the sentence +/// does. Any failure ends the process with exit code 1. +let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : unit = + match Seq.tryExactlyOne results with + | Some singleResult -> + match singleResult with + | FormatResult.Formatted(f, _, p) -> + stdlog $"%s{f} was formatted." + reportProfileInfo profile (f, p) + | FormatResult.IgnoredFile f -> stdlog $"%s{f} was ignored." + | FormatResult.Unchanged(f, p) -> + stdlog $"%s{f} was unchanged." + reportProfileInfo profile (f, p) + | FormatResult.Error(f, e) -> + reportError verbosity (f, e) + exit 1 + | FormatResult.InvalidCode(f, _) -> + let ex = invalidResultException f + reportError verbosity (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 verbosity e + + reportProfileInfos profile (oks @ unchanged) + + if errored.Length > 0 then + exit 1 + +let asyncRunner (computations: Async list) : FormatResult array = + computations |> Async.Parallel |> Async.RunSynchronously + [] let main argv = // Argu never gets to render a usage text of its own: HelpPage.exiter answers --help with @@ -248,46 +523,7 @@ let main argv = | 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 filesAndFolders = loop inputs id - InputPath.Multiple filesAndFolders - | None -> InputPath.Unspecified + let inputPath = results.TryGetResult <@ Arguments.Input @> |> classifyInputPath let force = results.Contains <@ Arguments.Force @> let profile = results.Contains <@ Arguments.Profile @> @@ -320,200 +556,8 @@ 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 @> - 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 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() $"Fantomas v%s{version}" @@ -548,14 +592,27 @@ let main argv = | 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 + processFolder force profile p1 p1 + |> asyncRunner + |> reportFormatResults profile verbosity | InputPath.File p1, OutputPath.NotKnown -> - processFile force p1 p1 |> List.singleton |> asyncRunner |> reportFormatResults + processFile force profile p1 p1 + |> List.singleton + |> asyncRunner + |> reportFormatResults profile verbosity | 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 + processFile force profile p1 p2 + |> List.singleton + |> asyncRunner + |> reportFormatResults profile verbosity + | InputPath.Folder p1, OutputPath.IO p2 -> + processFolder force profile p1 p2 + |> asyncRunner + |> reportFormatResults profile verbosity | InputPath.Multiple(files, folders), OutputPath.NotKnown -> - filesAndFolders force files folders |> asyncRunner |> reportFormatResults + filesAndFolders force profile files folders + |> asyncRunner + |> reportFormatResults profile verbosity | InputPath.Multiple _, OutputPath.IO _ -> elog "Multiple input files are not supported with the --out flag." exit 1 diff --git a/src/Fantomas/Program.fsi b/src/Fantomas/Program.fsi index 7b0639493f..1e96a41cde 100644 --- a/src/Fantomas/Program.fsi +++ b/src/Fantomas/Program.fsi @@ -1,3 +1,6 @@ module Program +/// 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, +/// though most paths through the program end the process themselves rather than returning here. val main: argv: string array -> int From 9f4a0b42b8bf50b73bc79fa2a973e01fd27a4ad7 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 10:44:46 +0200 Subject: [PATCH 02/17] Return exit codes from the CLI instead of calling exit Every command path ended the process itself, from inside reporting functions several calls deep. That makes the code untestable outside a real process: a call to exit in a test host kills the runner rather than failing an assertion. reportFormatResults now returns the exit code it used to exit with, and main returns that code rather than ending the process, so the whole command dispatch is an int-valued expression. The only remaining exit is the invalid --verbosity value in main, which is reached before there is anything to return through. Pull the verbosity parsing out as parseVerbosity, returning None for a value Fantomas does not know, so the parsing can be exercised on its own. No behaviour change: the process still ends with 0, 1 or 99 as before, and the log is still flushed on shutdown, now through normal termination rather than through Environment.Exit. --- src/Fantomas/Program.fs | 59 ++++++++++++++++++++++------------------ src/Fantomas/Program.fsi | 4 +-- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 3825a415f5..16e294466b 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -459,25 +459,29 @@ let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) l /// Report the outcome of a run. A single file is reported as a sentence naming it, and several /// files as a table of counts, because a table of one row tells the reader less than the sentence -/// does. Any failure ends the process with exit code 1. -let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : unit = +/// does. Returns the exit code the process should end with: 1 when anything failed, 0 otherwise. +let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : int = match Seq.tryExactlyOne results with | Some singleResult -> match singleResult with | FormatResult.Formatted(f, _, p) -> stdlog $"%s{f} was formatted." reportProfileInfo profile (f, p) - | FormatResult.IgnoredFile f -> stdlog $"%s{f} was ignored." + 0 + | FormatResult.IgnoredFile f -> + stdlog $"%s{f} was ignored." + 0 | FormatResult.Unchanged(f, p) -> stdlog $"%s{f} was unchanged." reportProfileInfo profile (f, p) + 0 | FormatResult.Error(f, e) -> reportError verbosity (f, e) - exit 1 + 1 | FormatResult.InvalidCode(f, _) -> let ex = invalidResultException f reportError verbosity (f, ex) - exit 1 + 1 | None -> let oks, ignored, unchanged, errored = partitionResults results @@ -503,8 +507,17 @@ let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #( reportProfileInfos profile (oks @ unchanged) - if errored.Length > 0 then - exit 1 + if errored.Length > 0 then 1 else 0 + +/// Read the `--verbosity` value. `None` means the value was not one Fantomas knows. +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 let asyncRunner (computations: Async list) : FormatResult array = computations |> Async.Parallel |> Async.RunSynchronously @@ -529,18 +542,10 @@ let main argv = let profile = results.Contains <@ Arguments.Profile @> let version = 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 _ -> + match parseVerbosity (results.TryGetResult <@ Arguments.Verbosity @>) with + | Some level -> level + | None -> // The logger is not up yet, so this cannot go through elog. eprintfn "Invalid verbosity level" exit 1 @@ -567,6 +572,7 @@ let main argv = if Option.isSome version then stdlog versionLog + 0 elif isDaemon then let daemon = new FantomasDaemon(Console.OpenStandardOutput(), Console.OpenStandardInput()) @@ -574,23 +580,24 @@ let main argv = AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> (daemon :> IDisposable).Dispose()) daemon.WaitForClose.GetAwaiter().GetResult() - exit 0 + 0 elif check then - inputPath |> runCheckCommand |> exit + runCheckCommand inputPath else try match inputPath, outputPath with | InputPath.NoFSharpFile s, _ -> elog $"Input path '%s{s}' is unsupported file type." - exit 1 + 1 | InputPath.NotFound s, _ -> elog $"Input path '%s{s}' not found." - exit 1 + 1 | InputPath.Unspecified, _ -> elog "Input path is missing. Call with --help for usage information." - exit 1 + 1 | InputPath.File f, _ when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> logGrEqDetailed $"'%s{f}' was ignored" + 0 | InputPath.Folder p1, OutputPath.NotKnown -> processFolder force profile p1 p1 |> asyncRunner @@ -615,9 +622,7 @@ let main argv = |> reportFormatResults profile verbosity | InputPath.Multiple _, OutputPath.IO _ -> elog "Multiple input files are not supported with the --out flag." - exit 1 + 1 with exn -> elog $"%s{exn.Message}" - exit 1 - - 0 + 1 diff --git a/src/Fantomas/Program.fsi b/src/Fantomas/Program.fsi index 1e96a41cde..8b3157e287 100644 --- a/src/Fantomas/Program.fsi +++ b/src/Fantomas/Program.fsi @@ -1,6 +1,6 @@ module Program /// 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, -/// though most paths through the program end the process themselves rather than returning here. +/// daemon, checking whether files need formatting, or formatting them. Returns the exit code the +/// process should end with. val main: argv: string array -> int From c066dc3ed22cd78573209daf7946f398dab7fced Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 11:06:26 +0200 Subject: [PATCH 03/17] Split the CLI into modules and return command results as values Program.fs held the whole command line tool behind a single exported value, main, so nothing in it could be reached from a test. Split it into Paths, Arguments, CommandResult, FormatCommand, CheckCommand and Report, each with a signature file stating what it offers, and leave Program with argument parsing, logger setup and dispatch. Both commands now return a value describing what happened rather than writing to the console and returning an exit code. runFormatCommand yields a FormatCommandResult and runCheckCommand a CheckCommandResult, and Report is the only module that turns either into text and into an exit code. A caller, a test above all, can ask what a run did without reading a console. The dependency runs one way: the commands produce, reporting consumes. The two commands described an unusable input path in wording that had drifted apart, with and without a full stop and with two different sentences for a missing path. Both now share an InputProblem and one place that renders it, so they cannot drift again. This changes what the tool prints. Move invalidResultException next to the FormatResult it describes, so that both FormatCommand and Report can reach it. Drop the Table extension, which existed only for one fluent chain and does not state well in a signature file. Keep Argu's attributes in the signature file alone; declaring them in both compiled only the signature's copy and warned. Record two conventions in AGENTS.md that this split relied on: a file with a signature file needs no let private, and documentation comments belong in the signature only. Note that the analyzer pipeline is safe to run at any time. --- AGENTS.md | 13 +- src/Fantomas/Arguments.fs | 97 ++++++ src/Fantomas/Arguments.fsi | 41 +++ src/Fantomas/CheckCommand.fs | 25 ++ src/Fantomas/CheckCommand.fsi | 8 + src/Fantomas/CommandResult.fs | 23 ++ src/Fantomas/CommandResult.fsi | 29 ++ src/Fantomas/Fantomas.fsproj | 12 + src/Fantomas/Format.fs | 12 +- src/Fantomas/Format.fsi | 4 + src/Fantomas/FormatCommand.fs | 224 +++++++++++++ src/Fantomas/FormatCommand.fsi | 10 + src/Fantomas/Paths.fs | 38 +++ src/Fantomas/Paths.fsi | 26 ++ src/Fantomas/Program.fs | 571 +-------------------------------- src/Fantomas/Report.fs | 174 ++++++++++ src/Fantomas/Report.fsi | 16 + 17 files changed, 755 insertions(+), 568 deletions(-) create mode 100644 src/Fantomas/Arguments.fs create mode 100644 src/Fantomas/Arguments.fsi create mode 100644 src/Fantomas/CheckCommand.fs create mode 100644 src/Fantomas/CheckCommand.fsi create mode 100644 src/Fantomas/CommandResult.fs create mode 100644 src/Fantomas/CommandResult.fsi create mode 100644 src/Fantomas/FormatCommand.fs create mode 100644 src/Fantomas/FormatCommand.fsi create mode 100644 src/Fantomas/Paths.fs create mode 100644 src/Fantomas/Paths.fsi create mode 100644 src/Fantomas/Report.fs create mode 100644 src/Fantomas/Report.fsi diff --git a/AGENTS.md b/AGENTS.md index 872f128b16..1dc887abb7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,13 +39,21 @@ This is guidance for code you are writing or revisiting, not a reason to sweep t 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. +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 When updating `CHANGELOG.md`, add new entries to the **end** of the relevant section (e.g. `### Fixed`), not the top. One entry per issue. ## 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 +67,5 @@ 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. diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs new file mode 100644 index 0000000000..aca7d3f5e7 --- /dev/null +++ b/src/Fantomas/Arguments.fs @@ -0,0 +1,97 @@ +module Fantomas.Arguments + +open System +open System.IO +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 (maybeInput: string list option) : InputPath = + 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) + + InputPath.Multiple(loop inputs id) + | 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..cdbf9d3173 --- /dev/null +++ b/src/Fantomas/Arguments.fsi @@ -0,0 +1,41 @@ +module Fantomas.Arguments + +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. A single path is classified by asking the +/// file system about it. Several paths are all required to exist first, and are then told apart +/// by whether they carry a file extension, so `src` is taken as a folder and `src.fs` as a file. +val classifyInputPath: 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..8809eb9dc2 --- /dev/null +++ b/src/Fantomas/CheckCommand.fs @@ -0,0 +1,25 @@ +module Fantomas.CheckCommand + +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult +open Fantomas.Paths + +let runCheckCommand (inputPath: InputPath) : CheckCommandResult = + let check (files: string seq) : CheckCommandResult = + Async.RunSynchronously(Format.checkCode files) |> CheckCommandResult.Completed + + match inputPath with + | InputPath.NoFSharpFile s -> CheckCommandResult.InvalidInput(InputProblem.UnsupportedFileType s) + | InputPath.NotFound s -> CheckCommandResult.InvalidInput(InputProblem.NotFound s) + | InputPath.Unspecified -> CheckCommandResult.InvalidInput InputProblem.NoPathGiven + | InputPath.File f when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> + CheckCommandResult.IgnoredFile f + | InputPath.File path -> path |> Seq.singleton |> check + | InputPath.Folder path -> path |> findAllFilesRecursively |> check + | InputPath.Multiple(files, folders) -> + seq { + yield! files + yield! (Seq.collect findAllFilesRecursively folders) + } + |> check diff --git a/src/Fantomas/CheckCommand.fsi b/src/Fantomas/CheckCommand.fsi new file mode 100644 index 0000000000..23baf556e2 --- /dev/null +++ b/src/Fantomas/CheckCommand.fsi @@ -0,0 +1,8 @@ +module Fantomas.CheckCommand + +open Fantomas.Arguments +open Fantomas.CommandResult + +/// 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: inputPath: InputPath -> CheckCommandResult diff --git a/src/Fantomas/CommandResult.fs b/src/Fantomas/CommandResult.fs new file mode 100644 index 0000000000..4150539e6a --- /dev/null +++ b/src/Fantomas/CommandResult.fs @@ -0,0 +1,23 @@ +module Fantomas.CommandResult + +open Fantomas + +[] +type InputProblem = + | UnsupportedFileType of path: string + | NotFound of path: string + | NoPathGiven + | MultiplePathsWithOut + +[] +type FormatCommandResult = + | InvalidInput of problem: InputProblem + | IgnoredFile of file: string + | Completed of results: FormatResult array + | Failed of error: exn + +[] +type CheckCommandResult = + | InvalidInput of problem: InputProblem + | IgnoredFile of file: string + | Completed of result: CheckResult diff --git a/src/Fantomas/CommandResult.fsi b/src/Fantomas/CommandResult.fsi new file mode 100644 index 0000000000..5cda87149d --- /dev/null +++ b/src/Fantomas/CommandResult.fsi @@ -0,0 +1,29 @@ +module Fantomas.CommandResult + +open Fantomas + +/// 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 + | IgnoredFile of file: string + | 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. +[] +type CheckCommandResult = + | InvalidInput of problem: InputProblem + | IgnoredFile of file: string + | Completed of result: CheckResult diff --git a/src/Fantomas/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index 001184d340..ff21db5500 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -35,6 +35,18 @@ + + + + + + + + + + + + diff --git a/src/Fantomas/Format.fs b/src/Fantomas/Format.fs index b89764d6e0..124a5fc1ee 100644 --- a/src/Fantomas/Format.fs +++ b/src/Fantomas/Format.fs @@ -43,12 +43,12 @@ type CheckResult = module Format = - let private formatR = System.Text.RegularExpressions.Regex(@"\r") + let invalidResultException (file: string) : FormatException = + FormatException($"Formatting %s{file} leads to invalid F# code") - let private formatContentInternalAsync - (formatParams: FormatParams) - (originalContent: string) - : Async = + let formatR = System.Text.RegularExpressions.Regex(@"\r") + + let formatContentInternalAsync (formatParams: FormatParams) (originalContent: string) : Async = if IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) formatParams.File then async { return FormatResult.IgnoredFile formatParams.File } else @@ -123,7 +123,7 @@ module Format = let formatContentAsync = formatContentInternalAsync - let private formatFileInternalAsync (parms: FormatParams) = + let formatFileInternalAsync (parms: FormatParams) = if IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) parms.File then async { return FormatResult.IgnoredFile parms.File } else diff --git a/src/Fantomas/Format.fsi b/src/Fantomas/Format.fsi index 89729dd8b9..5a1801cd64 100644 --- a/src/Fantomas/Format.fsi +++ b/src/Fantomas/Format.fsi @@ -34,6 +34,10 @@ type CheckResult = member NeedsFormatting: bool module Format = + /// 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 -> FormatException + val formatContentAsync: (FormatParams -> string -> Async) val formatFileAsync: (FormatParams -> Async) diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs new file mode 100644 index 0000000000..9c7e968a70 --- /dev/null +++ b/src/Fantomas/FormatCommand.fs @@ -0,0 +1,224 @@ +module Fantomas.FormatCommand + +open System.IO +open System.Text +// 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.Logging +open Fantomas.Arguments +open Fantomas.CommandResult +open Fantomas.Paths + +let hasByteOrderMark (file: string) : Async = + 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 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 = Format.invalidResultException file + return FormatResult.Error(file, ex) + } + +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 = Format.invalidResultException file + return FormatResult.Error(file, ex) + } + +// 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) (profile: 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 processFile (force: bool) (profile: bool) (inputFile: string) (outputFile: string) : Async = + async { + try + if not (isSamePath inputFile outputFile) then + return! fileToFile force profile inputFile outputFile + else + logGrEqDetailed $"Processing %s{inputFile}" + let! content = File.ReadAllTextAsync inputFile |> Async.AwaitTask + let config = EditorConfig.readConfiguration inputFile + return! processSourceString force profile content inputFile config + with e -> + return FormatResult.Error(inputFile, e) + } + +let processFolder + (force: bool) + (profile: 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 profile i o) + +let filesAndFolders + (force: bool) + (profile: bool) + (files: string list) + (folders: string list) + : Async 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 profile file file) + + let folderTasks = + folders + |> List.collect (fun folder -> processFolder force profile folder folder) + + (fileTasks @ folderTasks) + +let asyncRunner (computations: Async list) : FormatResult array = + computations |> Async.Parallel |> Async.RunSynchronously + +let runFormatCommand + (force: bool) + (profile: bool) + (inputPath: InputPath) + (outputPath: OutputPath) + : FormatCommandResult = + try + match inputPath, outputPath with + | InputPath.NoFSharpFile s, _ -> FormatCommandResult.InvalidInput(InputProblem.UnsupportedFileType s) + | InputPath.NotFound s, _ -> FormatCommandResult.InvalidInput(InputProblem.NotFound s) + | InputPath.Unspecified, _ -> FormatCommandResult.InvalidInput InputProblem.NoPathGiven + | InputPath.File f, _ when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> + FormatCommandResult.IgnoredFile f + | InputPath.Folder p1, OutputPath.NotKnown -> + processFolder force profile p1 p1 + |> asyncRunner + |> FormatCommandResult.Completed + | InputPath.File p1, OutputPath.NotKnown -> + processFile force profile p1 p1 + |> List.singleton + |> asyncRunner + |> FormatCommandResult.Completed + | InputPath.File p1, OutputPath.IO p2 -> + processFile force profile p1 p2 + |> List.singleton + |> asyncRunner + |> FormatCommandResult.Completed + | InputPath.Folder p1, OutputPath.IO p2 -> + processFolder force profile p1 p2 + |> asyncRunner + |> FormatCommandResult.Completed + | InputPath.Multiple(files, folders), OutputPath.NotKnown -> + filesAndFolders force profile files folders + |> asyncRunner + |> FormatCommandResult.Completed + | InputPath.Multiple _, OutputPath.IO _ -> FormatCommandResult.InvalidInput InputProblem.MultiplePathsWithOut + with exn -> + FormatCommandResult.Failed exn diff --git a/src/Fantomas/FormatCommand.fsi b/src/Fantomas/FormatCommand.fsi new file mode 100644 index 0000000000..b5303f6976 --- /dev/null +++ b/src/Fantomas/FormatCommand.fsi @@ -0,0 +1,10 @@ +module Fantomas.FormatCommand + +open Fantomas.Arguments +open Fantomas.CommandResult + +/// 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: + force: bool -> profile: bool -> inputPath: InputPath -> outputPath: OutputPath -> FormatCommandResult diff --git a/src/Fantomas/Paths.fs b/src/Fantomas/Paths.fs new file mode 100644 index 0000000000..59886ac3fb --- /dev/null +++ b/src/Fantomas/Paths.fs @@ -0,0 +1,38 @@ +module Fantomas.Paths + +open System +open System.IO + +let extensions = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] + +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 + +let findAllFilesRecursively path = + let searchOption = SearchOption.AllDirectories + + Directory.GetFiles(path, "*.*", searchOption) + |> Seq.filter (fun f -> isFSharpFile f && not (isInExcludedDir f)) + +let ensureParentFolderExists (file: string) : unit = + let folder = Path.GetDirectoryName(file) + + if not (String.IsNullOrEmpty folder) then + Directory.CreateDirectory(folder) |> ignore + +let isSamePath (left: string) (right: string) : bool = + String.Equals(Path.GetFullPath left, Path.GetFullPath right, StringComparison.Ordinal) + +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) diff --git a/src/Fantomas/Paths.fsi b/src/Fantomas/Paths.fsi new file mode 100644 index 0000000000..0d58e42580 --- /dev/null +++ b/src/Fantomas/Paths.fsi @@ -0,0 +1,26 @@ +module Fantomas.Paths + +/// 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: 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. Path.GetDirectoryName yields an empty string for a bare file name. +val ensureParentFolderExists: 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: left: string -> right: string -> bool + +/// Is a file located inside a folder, at any depth? +val isInFolder: folder: string -> file: string -> bool diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 16e294466b..5054891614 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -1,526 +1,17 @@ +module Program + open System -open System.IO +// 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.Daemon open Fantomas.Logging +open Fantomas.Arguments +open Fantomas.FormatCommand +open Fantomas.Report +open Fantomas.CheckCommand open Argu -open System.Text -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 - -/// 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. -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 hasByteOrderMark (file: string) : Async = - 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 invalidResultException (file: string) : FormatException = - FormatException($"Formatting %s{file} leads to invalid F# code") - -/// Format content that has already been read, and write the result back over `fileName`. The -/// byte order mark the file started with is put back, since formatting is not the place to -/// decide a file's encoding. With `force`, output that failed the validity check is written -/// anyway and reported as a success. -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 a file and write the result to `tw`. A file that needed no change is copied across -/// verbatim rather than skipped, so the caller receives the full content whatever the outcome. -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 - -/// Write one line per file that needs formatting, and a described failure for every file that -/// could not be formatted at all. -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" - -/// Report which files need formatting and write nothing. Returns the exit code the process -/// should end with: 0 when every file is already formatted, 99 when at least one needs -/// formatting, and 1 when an input path was unusable or a file could not be formatted. -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 - -/// Decide what the paths on the command line name. A single path is classified by asking the -/// file system about it. Several paths are all required to exist first, and are then told apart -/// by whether they carry a file extension, so `src` is taken as a folder and `src.fs` as a file. -let classifyInputPath (maybeInput: string list option) : InputPath = - 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) - - InputPath.Multiple(loop inputs id) - | None -> InputPath.Unspecified - -/// Format `inFile` and write the result to `outFile`, creating the folders leading up to it if -/// they are not there yet. -// 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) (profile: 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 - } - -/// Format one file to one destination. Writing back over the input is a different operation -/// from writing somewhere else, and is kept apart here: in place, the content has to be read -/// before anything is written. A failure is returned as an `Error` result rather than raised, so -/// that one unformattable file does not abandon the rest of the run. -let processFile (force: bool) (profile: bool) (inputFile: string) (outputFile: string) : Async = - async { - try - if not (isSamePath inputFile outputFile) then - return! fileToFile force profile inputFile outputFile - else - logGrEqDetailed $"Processing %s{inputFile}" - let! content = File.ReadAllTextAsync inputFile |> Async.AwaitTask - let config = EditorConfig.readConfiguration inputFile - return! processSourceString force profile content inputFile config - with e -> - return FormatResult.Error(inputFile, e) - } - -/// Format every F# file below `inputFolder`, writing each one to the matching place under -/// `outputFolder` so that the output mirrors the input tree. When the two folders name the same -/// place the files are formatted where they lie. -let processFolder - (force: bool) - (profile: 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 profile i o) - -/// Format an explicit list of files along with every F# file below the given folders. All of it -/// is formatted in place, which is the only thing on offer once more than one input path is -/// named. -let filesAndFolders - (force: bool) - (profile: bool) - (files: string list) - (folders: string list) - : Async 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 profile file file) - - let folderTasks = - folders - |> List.collect (fun folder -> processFolder force profile folder folder) - - (fileTasks @ folderTasks) - -/// Sort the results into what was formatted, ignored, left unchanged, and failed. Code that came -/// out invalid is counted as a failure and carries an exception saying so, which leaves the -/// caller one kind of thing to report rather than two. -let partitionResults - (results: #(FormatResult seq)) - : (string * ProfileInfo option) list * string list * (string * ProfileInfo option) list * (string * Exception) 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 = invalidResultException file - (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) - -/// Describe one failure on standard error. A parse failure is reported in full, positions and -/// surrounding source included. Anything else is reduced to a single line, unless the verbosity -/// asks for the whole exception. -let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = - 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 reportProfileInfo (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = - match profile, profileInfo with - | true, Some pI -> stdlog $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" - | _ -> () - -/// Print the line count and the time taken per file, when profiling was asked for. -let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) list) : unit = - 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 - -/// Report the outcome of a run. A single file is reported as a sentence naming it, and several -/// files as a table of counts, because a table of one row tells the reader less than the sentence -/// does. Returns the exit code the process should end with: 1 when anything failed, 0 otherwise. -let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : int = - match Seq.tryExactlyOne results with - | Some singleResult -> - match singleResult with - | FormatResult.Formatted(f, _, p) -> - stdlog $"%s{f} was formatted." - reportProfileInfo profile (f, p) - 0 - | FormatResult.IgnoredFile f -> - stdlog $"%s{f} was ignored." - 0 - | FormatResult.Unchanged(f, p) -> - stdlog $"%s{f} was unchanged." - reportProfileInfo profile (f, p) - 0 - | FormatResult.Error(f, e) -> - reportError verbosity (f, e) - 1 - | FormatResult.InvalidCode(f, _) -> - let ex = invalidResultException f - reportError verbosity (f, ex) - 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 verbosity e - - reportProfileInfos profile (oks @ unchanged) - - if errored.Length > 0 then 1 else 0 - -/// Read the `--verbosity` value. `None` means the value was not one Fantomas knows. -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 - -let asyncRunner (computations: Async list) : FormatResult array = - computations |> Async.Parallel |> Async.RunSynchronously [] let main argv = @@ -582,47 +73,7 @@ let main argv = daemon.WaitForClose.GetAwaiter().GetResult() 0 elif check then - runCheckCommand inputPath + runCheckCommand inputPath |> reportCheckCommand else - try - match inputPath, outputPath 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 "Input path is missing. Call with --help for usage information." - 1 - | InputPath.File f, _ when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> - logGrEqDetailed $"'%s{f}' was ignored" - 0 - | InputPath.Folder p1, OutputPath.NotKnown -> - processFolder force profile p1 p1 - |> asyncRunner - |> reportFormatResults profile verbosity - | InputPath.File p1, OutputPath.NotKnown -> - processFile force profile p1 p1 - |> List.singleton - |> asyncRunner - |> reportFormatResults profile verbosity - | InputPath.File p1, OutputPath.IO p2 -> - processFile force profile p1 p2 - |> List.singleton - |> asyncRunner - |> reportFormatResults profile verbosity - | InputPath.Folder p1, OutputPath.IO p2 -> - processFolder force profile p1 p2 - |> asyncRunner - |> reportFormatResults profile verbosity - | InputPath.Multiple(files, folders), OutputPath.NotKnown -> - filesAndFolders force profile files folders - |> asyncRunner - |> reportFormatResults profile verbosity - | InputPath.Multiple _, OutputPath.IO _ -> - elog "Multiple input files are not supported with the --out flag." - 1 - with exn -> - elog $"%s{exn.Message}" - 1 + runFormatCommand force profile inputPath outputPath + |> reportFormatCommand profile verbosity diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs new file mode 100644 index 0000000000..180b327dfb --- /dev/null +++ b/src/Fantomas/Report.fs @@ -0,0 +1,174 @@ +module Fantomas.Report + +open System +open System.IO +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.Logging +open Fantomas.CommandResult + +// 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 partitionResults + (results: #(FormatResult seq)) + : (string * ProfileInfo option) list * string list * (string * ProfileInfo option) list * (string * Exception) 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 = Format.invalidResultException file + (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) + +let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = + 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 reportProfileInfo (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = + match profile, profileInfo with + | true, Some pI -> stdlog $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" + | _ -> () + +let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) list) : unit = + 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 + +let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : int = + match Seq.tryExactlyOne results with + | Some singleResult -> + match singleResult with + | FormatResult.Formatted(f, _, p) -> + stdlog $"%s{f} was formatted." + reportProfileInfo profile (f, p) + 0 + | FormatResult.IgnoredFile f -> + stdlog $"%s{f} was ignored." + 0 + | FormatResult.Unchanged(f, p) -> + stdlog $"%s{f} was unchanged." + reportProfileInfo profile (f, p) + 0 + | FormatResult.Error(f, e) -> + reportError verbosity (f, e) + 1 + | FormatResult.InvalidCode(f, _) -> + let ex = Format.invalidResultException f + reportError verbosity (f, ex) + 1 + + | None -> + let oks, ignored, unchanged, errored = partitionResults results + let centeredColumn (v: string) = TableColumn(v).Centered() + + let summary = + 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 + AnsiConsole.Write summary + + for e in errored do + reportError verbosity e + + reportProfileInfos profile (oks @ unchanged) + + if errored.Length > 0 then 1 else 0 + +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 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 (profile: bool) (verbosity: VerbosityLevel) (result: FormatCommandResult) : int = + match result with + | FormatCommandResult.InvalidInput problem -> + elog (describeInputProblem problem) + 1 + | FormatCommandResult.IgnoredFile file -> + logGrEqDetailed $"'%s{file}' was ignored" + 0 + | FormatCommandResult.Failed error -> + elog $"%s{error.Message}" + 1 + | FormatCommandResult.Completed results -> reportFormatResults profile verbosity results + +let reportCheckCommand (result: CheckCommandResult) : int = + match result with + | CheckCommandResult.InvalidInput problem -> + elog (describeInputProblem problem) + 1 + | CheckCommandResult.IgnoredFile file -> + logGrEqDetailed $"'%s{file}' was ignored" + 0 + | CheckCommandResult.Completed checkResult -> + if checkResult.IsValid then + logGrEqDetailed "No changes required." + 0 + else + reportCheckResults 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..3224923519 --- /dev/null +++ b/src/Fantomas/Report.fsi @@ -0,0 +1,16 @@ +module Fantomas.Report + +open Fantomas.CommandResult +open Fantomas.Logging + +/// 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: profile: bool -> verbosity: VerbosityLevel -> 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: result: CheckCommandResult -> int From b94e74c4429f50350dc0b72c56f7ad6089ab8cbb Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 11:17:04 +0200 Subject: [PATCH 04/17] Decide once whether a file is ignored, and drop the Format module Whether a file was ignored was asked five times over on the way to formatting it: by the format command, by the walk over an explicit list of files, and three more times inside Format, each against the same process global. A new Plan module answers it once, turning the input and output paths into a list of work items that each say either skip this file or format it from here to there. The output tree is mirrored onto the input tree there too, so processFolder and filesAndFolders are no longer needed and running the format command is a fold over the plan. Deciding it in the caller leaves Format holding four types and two functions that only the CLI used, and the name never said how it differed from FormatCommand. It is gone: the outcome types and invalidResultException join CommandResult, formatContentAsync and FormatParams join FormatCommand, and checkCode joins CheckCommand, whose fan-out it was. main is now the only place that reaches for IgnoreFile.current, and it hands the result to whichever command runs. That is a step towards passing a file system in rather than reading one from a global. Two changes to what the tool prints. A single ignored file named on the command line is reported the way an ignored file found in a folder always was, rather than staying silent unless --verbosity d was given, and a --check run reports ignored files it found in a folder at detailed verbosity. Both follow from the special case for a directly named file going away. While reading the file for formatting, processSourceFile read it a second time from disk to write an unchanged file through unaltered. It now writes back the content it already has. --- src/Fantomas.Tests/CheckTests.fs | 2 +- src/Fantomas/CheckCommand.fs | 75 ++++++++--- src/Fantomas/CheckCommand.fsi | 6 +- src/Fantomas/CommandResult.fs | 29 ++++- src/Fantomas/CommandResult.fsi | 35 ++++- src/Fantomas/Fantomas.fsproj | 4 +- src/Fantomas/Format.fs | 178 ------------------------- src/Fantomas/Format.fsi | 53 -------- src/Fantomas/FormatCommand.fs | 215 +++++++++++++++++-------------- src/Fantomas/FormatCommand.fsi | 23 +++- src/Fantomas/Plan.fs | 56 ++++++++ src/Fantomas/Plan.fsi | 21 +++ src/Fantomas/Program.fs | 11 +- src/Fantomas/Report.fs | 16 +-- 14 files changed, 346 insertions(+), 378 deletions(-) delete mode 100644 src/Fantomas/Format.fs delete mode 100644 src/Fantomas/Format.fsi create mode 100644 src/Fantomas/Plan.fs create mode 100644 src/Fantomas/Plan.fsi diff --git a/src/Fantomas.Tests/CheckTests.fs b/src/Fantomas.Tests/CheckTests.fs index d98d2e3858..04bb558480 100644 --- a/src/Fantomas.Tests/CheckTests.fs +++ b/src/Fantomas.Tests/CheckTests.fs @@ -3,7 +3,7 @@ module Fantomas.Core.Tests.CheckTests open NUnit.Framework open FsUnit open Fantomas.Tests.TestHelpers -open Fantomas.Format +open Fantomas.CheckCommand [] let NeedsFormatting = diff --git a/src/Fantomas/CheckCommand.fs b/src/Fantomas/CheckCommand.fs index 8809eb9dc2..2179c5524c 100644 --- a/src/Fantomas/CheckCommand.fs +++ b/src/Fantomas/CheckCommand.fs @@ -1,25 +1,60 @@ module Fantomas.CheckCommand +open System.IO open Fantomas open Fantomas.Arguments open Fantomas.CommandResult -open Fantomas.Paths - -let runCheckCommand (inputPath: InputPath) : CheckCommandResult = - let check (files: string seq) : CheckCommandResult = - Async.RunSynchronously(Format.checkCode files) |> CheckCommandResult.Completed - - match inputPath with - | InputPath.NoFSharpFile s -> CheckCommandResult.InvalidInput(InputProblem.UnsupportedFileType s) - | InputPath.NotFound s -> CheckCommandResult.InvalidInput(InputProblem.NotFound s) - | InputPath.Unspecified -> CheckCommandResult.InvalidInput InputProblem.NoPathGiven - | InputPath.File f when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> - CheckCommandResult.IgnoredFile f - | InputPath.File path -> path |> Seq.singleton |> check - | InputPath.Folder path -> path |> findAllFilesRecursively |> check - | InputPath.Multiple(files, folders) -> - seq { - yield! files - yield! (Seq.collect findAllFilesRecursively folders) - } - |> check +open Fantomas.FormatCommand +open Fantomas.Plan + +let checkCode (filenames: string seq) : Async = + async { + let! formatted = + filenames + |> Seq.map (fun filename -> + async { + let! content = File.ReadAllTextAsync filename |> Async.AwaitTask + return! formatContentAsync (FormatParams.Create(true, false, filename)) content + }) + |> 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 } + } + +let runCheckCommand (ignoreFile: IgnoreFile option) (inputPath: InputPath) : CheckCommandResult = + // A check never writes, so the output path it plans against is the input itself. + match plan ignoreFile inputPath OutputPath.NotKnown with + | Error problem -> CheckCommandResult.InvalidInput problem + | Ok items -> + let ignored = + items + |> List.choose (fun item -> + match item with + | WorkItem.Ignored file -> Some file + | WorkItem.Format _ -> None) + + let toCheck = + items + |> List.choose (fun item -> + match item with + | WorkItem.Ignored _ -> None + | WorkItem.Format(inputFile, _) -> Some inputFile) + + CheckCommandResult.Completed(ignored, Async.RunSynchronously(checkCode toCheck)) diff --git a/src/Fantomas/CheckCommand.fsi b/src/Fantomas/CheckCommand.fsi index 23baf556e2..e20d85c046 100644 --- a/src/Fantomas/CheckCommand.fsi +++ b/src/Fantomas/CheckCommand.fsi @@ -1,8 +1,12 @@ module Fantomas.CheckCommand +open Fantomas open Fantomas.Arguments open Fantomas.CommandResult +/// Format every file in memory and report which ones came out different, without writing anything. +val checkCode: 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: inputPath: InputPath -> CheckCommandResult +val runCheckCommand: ignoreFile: IgnoreFile option -> inputPath: InputPath -> CheckCommandResult diff --git a/src/Fantomas/CommandResult.fs b/src/Fantomas/CommandResult.fs index 4150539e6a..8c37478421 100644 --- a/src/Fantomas/CommandResult.fs +++ b/src/Fantomas/CommandResult.fs @@ -1,6 +1,29 @@ module Fantomas.CommandResult -open 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 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 = @@ -12,12 +35,10 @@ type InputProblem = [] type FormatCommandResult = | InvalidInput of problem: InputProblem - | IgnoredFile of file: string | Completed of results: FormatResult array | Failed of error: exn [] type CheckCommandResult = | InvalidInput of problem: InputProblem - | IgnoredFile of file: string - | Completed of result: CheckResult + | Completed of ignored: string list * result: CheckResult diff --git a/src/Fantomas/CommandResult.fsi b/src/Fantomas/CommandResult.fsi index 5cda87149d..6b35795089 100644 --- a/src/Fantomas/CommandResult.fsi +++ b/src/Fantomas/CommandResult.fsi @@ -1,6 +1,32 @@ module Fantomas.CommandResult -open Fantomas +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: Exception + | 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. @@ -16,14 +42,13 @@ type InputProblem = [] type FormatCommandResult = | InvalidInput of problem: InputProblem - | IgnoredFile of file: string | 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. +/// 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 - | IgnoredFile of file: string - | Completed of result: CheckResult + | Completed of ignored: string list * result: CheckResult diff --git a/src/Fantomas/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index ff21db5500..bf96b517e3 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -29,8 +29,6 @@ - - @@ -41,6 +39,8 @@ + + diff --git a/src/Fantomas/Format.fs b/src/Fantomas/Format.fs deleted file mode 100644 index 124a5fc1ee..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 invalidResultException (file: string) : FormatException = - FormatException($"Formatting %s{file} leads to invalid F# code") - - let formatR = System.Text.RegularExpressions.Regex(@"\r") - - let 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 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 5a1801cd64..0000000000 --- a/src/Fantomas/Format.fsi +++ /dev/null @@ -1,53 +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 = - /// 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 -> FormatException - - 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 index 9c7e968a70..d330b9086c 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -1,15 +1,93 @@ module Fantomas.FormatCommand +open System open System.IO open System.Text -// 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.Logging open Fantomas.Arguments 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) = + { 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 } + +let private carriageReturn = Text.RegularExpressions.Regex(@"\r") + +let formatContentAsync (formatParams: FormatParams) (originalContent: string) : Async = + 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) = carriageReturn.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 hasByteOrderMark (file: string) : Async = async { @@ -25,7 +103,13 @@ let hasByteOrderMark (file: string) : Async = return false } -let processSourceString (force: bool) (profile: bool) s (fileName: string) config = +let processSourceString + (force: bool) + (profile: bool) + (s: string) + (fileName: string) + (config: FormatConfig) + : Async = let writeResult (formatted: string) = async { let! hasBom = hasByteOrderMark fileName @@ -40,7 +124,7 @@ let processSourceString (force: bool) (profile: bool) s (fileName: string) confi async { let formatParams = FormatParams.Create(config, false, profile, fileName) - let! formatted = s |> Format.formatContentAsync formatParams + let! formatted = formatContentAsync formatParams s match formatted with | FormatResult.Formatted(_, formattedContent, _) as r -> @@ -53,18 +137,15 @@ let processSourceString (force: bool) (profile: bool) s (fileName: string) confi | 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.IgnoredFile _ as r -> return r | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> - let ex = Format.invalidResultException file - return FormatResult.Error(file, ex) + | FormatResult.InvalidCode(file, _) -> return FormatResult.Error(file, invalidResultException file) } -let processSourceFile (force: bool) (profile: bool) inFile (tw: TextWriter) = +let processSourceFile (force: bool) (profile: bool) (inFile: string) (tw: TextWriter) : Async = async { - let! formatted = FormatParams.Create(false, profile, inFile) |> Format.formatFileAsync + let! originalContent = File.ReadAllTextAsync inFile |> Async.AwaitTask + let! formatted = formatContentAsync (FormatParams.Create(false, profile, inFile)) originalContent match formatted with | FormatResult.Formatted(_, formattedContent, _) as r -> @@ -75,16 +156,13 @@ let processSourceFile (force: bool) (profile: bool) inFile (tw: TextWriter) = 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" + // The content is already in hand, so an unchanged file is copied across from it + // rather than read a second time. + do! originalContent |> tw.WriteAsync |> Async.AwaitTask return r + | FormatResult.IgnoredFile _ as r -> return r | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> - let ex = Format.invalidResultException file - return FormatResult.Error(file, ex) + | FormatResult.InvalidCode(file, _) -> return FormatResult.Error(file, invalidResultException file) } // The formatted text is collected in memory and the output file is opened only once there @@ -131,94 +209,31 @@ let processFile (force: bool) (profile: bool) (inputFile: string) (outputFile: s return FormatResult.Error(inputFile, e) } -let processFolder - (force: bool) - (profile: 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 profile i o) - -let filesAndFolders - (force: bool) - (profile: bool) - (files: string list) - (folders: string list) - : Async 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 profile file file) - - let folderTasks = - folders - |> List.collect (fun folder -> processFolder force profile folder folder) - - (fileTasks @ folderTasks) - -let asyncRunner (computations: Async list) : FormatResult array = - computations |> Async.Parallel |> Async.RunSynchronously - let runFormatCommand (force: bool) (profile: bool) + (ignoreFile: IgnoreFile option) (inputPath: InputPath) (outputPath: OutputPath) : FormatCommandResult = 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.NoFSharpFile s, _ -> FormatCommandResult.InvalidInput(InputProblem.UnsupportedFileType s) - | InputPath.NotFound s, _ -> FormatCommandResult.InvalidInput(InputProblem.NotFound s) - | InputPath.Unspecified, _ -> FormatCommandResult.InvalidInput InputProblem.NoPathGiven - | InputPath.File f, _ when (IgnoreFile.isIgnoredFile (IgnoreFile.current.Force()) f) -> - FormatCommandResult.IgnoredFile f - | InputPath.Folder p1, OutputPath.NotKnown -> - processFolder force profile p1 p1 - |> asyncRunner - |> FormatCommandResult.Completed - | InputPath.File p1, OutputPath.NotKnown -> - processFile force profile p1 p1 - |> List.singleton - |> asyncRunner - |> FormatCommandResult.Completed - | InputPath.File p1, OutputPath.IO p2 -> - processFile force profile p1 p2 - |> List.singleton - |> asyncRunner - |> FormatCommandResult.Completed - | InputPath.Folder p1, OutputPath.IO p2 -> - processFolder force profile p1 p2 - |> asyncRunner - |> FormatCommandResult.Completed - | InputPath.Multiple(files, folders), OutputPath.NotKnown -> - filesAndFolders force profile files folders - |> asyncRunner + | InputPath.Folder _, OutputPath.IO outputFolder when not (Directory.Exists outputFolder) -> + Directory.CreateDirectory outputFolder |> ignore + | _ -> () + + match plan 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 force profile inputFile outputFile) + |> Async.Parallel + |> Async.RunSynchronously |> FormatCommandResult.Completed - | InputPath.Multiple _, OutputPath.IO _ -> FormatCommandResult.InvalidInput InputProblem.MultiplePathsWithOut with exn -> FormatCommandResult.Failed exn diff --git a/src/Fantomas/FormatCommand.fsi b/src/Fantomas/FormatCommand.fsi index b5303f6976..9e5ae03266 100644 --- a/src/Fantomas/FormatCommand.fsi +++ b/src/Fantomas/FormatCommand.fsi @@ -1,10 +1,31 @@ module Fantomas.FormatCommand +open Fantomas +open Fantomas.Core open Fantomas.Arguments open Fantomas.CommandResult +type FormatParams = + { Config: FormatConfig + CompareWithoutLineEndings: bool + Profile: bool + File: string } + + /// Read the configuration for the file from the `.editorconfig` files above it. + static member Create: bool * bool * string -> FormatParams + 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: - force: bool -> profile: bool -> inputPath: InputPath -> outputPath: OutputPath -> FormatCommandResult + force: bool -> + profile: bool -> + ignoreFile: IgnoreFile option -> + inputPath: InputPath -> + outputPath: OutputPath -> + FormatCommandResult diff --git a/src/Fantomas/Plan.fs b/src/Fantomas/Plan.fs new file mode 100644 index 0000000000..9a89405163 --- /dev/null +++ b/src/Fantomas/Plan.fs @@ -0,0 +1,56 @@ +module Fantomas.Plan + +open System.IO +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult +open Fantomas.Paths + +[] +type WorkItem = + | Ignored of file: string + | Format of inputFile: string * outputFile: string + +let plan + (ignoreFile: IgnoreFile option) + (inputPath: InputPath) + (outputPath: OutputPath) + : Result = + let item (inputFile: string) (outputFile: string) : WorkItem = + if IgnoreFile.isIgnoredFile ignoreFile inputFile then + WorkItem.Ignored inputFile + else + WorkItem.Format(inputFile, outputFile) + + let folder (inputFolder: string) (outputFolder: string) : WorkItem list = + 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.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. + Path.Combine(outputFolder, Path.GetRelativePath(inputFolder, i)) + + item i o) + |> 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..ee7f3ddc5c --- /dev/null +++ b/src/Fantomas/Plan.fsi @@ -0,0 +1,21 @@ +module Fantomas.Plan + +open Fantomas +open Fantomas.Arguments +open Fantomas.CommandResult + +/// 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: + ignoreFile: IgnoreFile option -> + inputPath: InputPath -> + outputPath: OutputPath -> + Result diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 5054891614..c122096da7 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -72,8 +72,11 @@ let main argv = daemon.WaitForClose.GetAwaiter().GetResult() 0 - elif check then - runCheckCommand inputPath |> reportCheckCommand else - runFormatCommand force profile inputPath outputPath - |> reportFormatCommand profile verbosity + let ignoreFile = IgnoreFile.current.Force() + + if check then + runCheckCommand ignoreFile inputPath |> reportCheckCommand + else + runFormatCommand force profile ignoreFile inputPath outputPath + |> reportFormatCommand profile verbosity diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index 180b327dfb..f12a2b698a 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -7,6 +7,7 @@ open Spectre.Console // FormatResult named here the one this project defines. open Fantomas.Core open Fantomas +open Fantomas.CommandResult open Fantomas.Logging open Fantomas.CommandResult @@ -29,7 +30,7 @@ let partitionResults | 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 = Format.invalidResultException file + let ex = invalidResultException file (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = @@ -96,7 +97,7 @@ let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #( reportError verbosity (f, e) 1 | FormatResult.InvalidCode(f, _) -> - let ex = Format.invalidResultException f + let ex = invalidResultException f reportError verbosity (f, ex) 1 @@ -149,9 +150,6 @@ let reportFormatCommand (profile: bool) (verbosity: VerbosityLevel) (result: For | FormatCommandResult.InvalidInput problem -> elog (describeInputProblem problem) 1 - | FormatCommandResult.IgnoredFile file -> - logGrEqDetailed $"'%s{file}' was ignored" - 0 | FormatCommandResult.Failed error -> elog $"%s{error.Message}" 1 @@ -162,10 +160,10 @@ let reportCheckCommand (result: CheckCommandResult) : int = | CheckCommandResult.InvalidInput problem -> elog (describeInputProblem problem) 1 - | CheckCommandResult.IgnoredFile file -> - logGrEqDetailed $"'%s{file}' was ignored" - 0 - | CheckCommandResult.Completed checkResult -> + | CheckCommandResult.Completed(ignored, checkResult) -> + for file in ignored do + logGrEqDetailed $"'%s{file}' was ignored" + if checkResult.IsValid then logGrEqDetailed "No changes required." 0 From 9217b032ede5898fcfe0f055fa3d79a8caeb4e8f Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 11:35:08 +0200 Subject: [PATCH 05/17] Pass a file system into the CLI instead of reaching for a global The command line tool read the real file system wherever it happened to need one, and resolved its ignore file from a module level Lazy built against Environment.CurrentDirectory at type initialisation. Nothing below main could be exercised without the process it was running in. A CliEnvironment now carries the file system, the ignore file for the run and a function that reads .editorconfig for a file. A CliSettings carries force, profile and verbosity. Both are built once in main and handed down. They are kept apart because a test varies the settings on every case and the environment on almost none. The commands and the reporting take both; Paths, Plan and classifyInputPath take an IFileSystem alone, since that is all they consult. IFileSystem appears only where the file system is genuinely touched. The three remaining direct uses of Path are GetExtension and DirectorySeparatorChar, which are string operations with no IO and no dependence on the current directory. IgnoreFile.current is gone, along with the FileSystem it constructed and the working directory it read on its own. It is now findInDirectory, called by main with the file system it built. Its Lazy went too: it existed so a global forced from five places would load once, and after deciding the matter in Plan there is one place. The test that asserted the caching now asserts what still holds, that the walk up stops at the first ignore file rather than loading another. Drop the FormatParams.Create overload that read .editorconfig inside a constructor. Callers pass the configuration in, so the read is visible at the call site and a test can put something else there. Widen the annotation rule in AGENTS.md to every let binding rather than only functions, local bindings included, and annotate the modules this refactor produced. Writing the type down is what showed that two function values in CheckCommand said nothing about what they matched on. --- AGENTS.md | 22 +++-- src/Fantomas.Tests/CheckTests.fs | 12 ++- src/Fantomas.Tests/IgnoreFileTests.fs | 21 ++--- src/Fantomas.Tests/TestHelpers.fs | 9 +++ src/Fantomas/Arguments.fs | 17 ++-- src/Fantomas/Arguments.fsi | 3 +- src/Fantomas/CheckCommand.fs | 31 +++---- src/Fantomas/CheckCommand.fsi | 6 +- src/Fantomas/Cli.fs | 17 ++++ src/Fantomas/Cli.fsi | 27 +++++++ src/Fantomas/Fantomas.fsproj | 2 + src/Fantomas/FormatCommand.fs | 111 +++++++++++++++----------- src/Fantomas/FormatCommand.fsi | 9 +-- src/Fantomas/IgnoreFile.fs | 16 ++-- src/Fantomas/IgnoreFile.fsi | 15 ++-- src/Fantomas/Paths.fs | 33 ++++---- src/Fantomas/Paths.fsi | 12 +-- src/Fantomas/Plan.fs | 34 ++++---- src/Fantomas/Plan.fsi | 2 + src/Fantomas/Program.fs | 55 ++++++++----- src/Fantomas/Report.fs | 49 +++++++----- src/Fantomas/Report.fsi | 6 +- 22 files changed, 308 insertions(+), 201 deletions(-) create mode 100644 src/Fantomas/Cli.fs create mode 100644 src/Fantomas/Cli.fsi diff --git a/AGENTS.md b/AGENTS.md index 1dc887abb7..b575e4a03b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,21 +23,27 @@ 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 diff --git a/src/Fantomas.Tests/CheckTests.fs b/src/Fantomas.Tests/CheckTests.fs index 04bb558480..ba2797f098 100644 --- a/src/Fantomas.Tests/CheckTests.fs +++ b/src/Fantomas.Tests/CheckTests.fs @@ -26,7 +26,9 @@ let ``formatted files should report no changes`` () = use fileFixture = new TemporaryFileCodeSample(CorrectlyFormatted) let result = - fileFixture.Filename |> Seq.singleton |> checkCode |> Async.RunSynchronously + Seq.singleton fileFixture.Filename + |> checkCode realEnvironment + |> Async.RunSynchronously result.NeedsFormatting |> should equal false result.IsValid |> should equal true @@ -36,7 +38,9 @@ let ``files with errors should report an internal error`` () = use fileFixture = new TemporaryFileCodeSample(WithErrors) let result = - fileFixture.Filename |> Seq.singleton |> checkCode |> Async.RunSynchronously + Seq.singleton fileFixture.Filename + |> checkCode realEnvironment + |> Async.RunSynchronously result.HasErrors |> should equal true List.length result.Errors |> should equal 1 @@ -46,7 +50,9 @@ 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 + Seq.singleton fileFixture.Filename + |> checkCode realEnvironment + |> Async.RunSynchronously result.HasErrors |> should equal false result.NeedsFormatting |> should equal true 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/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 5e40f6f4f5..65afe8845f 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -3,8 +3,10 @@ module Fantomas.Tests.TestHelpers open System open System.Diagnostics open System.IO +open System.IO.Abstractions open System.Text open Fantomas +open Fantomas.Cli [] module String = @@ -108,6 +110,13 @@ type FantomasIgnoreFile internal (content: string) = if File.Exists(filename) then File.Delete(filename) +/// 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 } + type FantomasToolResult = { ExitCode: int Output: string diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs index aca7d3f5e7..d3f1664036 100644 --- a/src/Fantomas/Arguments.fs +++ b/src/Fantomas/Arguments.fs @@ -1,7 +1,7 @@ module Fantomas.Arguments open System -open System.IO +open System.IO.Abstractions open Argu open Fantomas.Logging open Fantomas.Paths @@ -49,26 +49,27 @@ type OutputPath = | IO of string | NotKnown -let classifyInputPath (maybeInput: string list option) : InputPath = +let classifyInputPath (fs: IFileSystem) (maybeInput: string list option) : InputPath = match maybeInput with | Some [ input ] -> - if Directory.Exists(input) then + if fs.Directory.Exists(input) then InputPath.Folder input - elif File.Exists input && isFSharpFile input then + elif fs.File.Exists input && isFSharpFile input then InputPath.File input - elif File.Exists input then + elif fs.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))) + 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 -> let isFolder (path: string) = - String.IsNullOrWhiteSpace(Path.GetExtension(path)) + String.IsNullOrWhiteSpace(fs.Path.GetExtension(path)) let rec loop (files: string list) diff --git a/src/Fantomas/Arguments.fsi b/src/Fantomas/Arguments.fsi index cdbf9d3173..cebd38bc4a 100644 --- a/src/Fantomas/Arguments.fsi +++ b/src/Fantomas/Arguments.fsi @@ -1,5 +1,6 @@ module Fantomas.Arguments +open System.IO.Abstractions open Argu open Fantomas.Logging @@ -35,7 +36,7 @@ type OutputPath = /// Decide what the paths on the command line name. A single path is classified by asking the /// file system about it. Several paths are all required to exist first, and are then told apart /// by whether they carry a file extension, so `src` is taken as a folder and `src.fs` as a file. -val classifyInputPath: maybeInput: string list option -> InputPath +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 index 2179c5524c..089d83946a 100644 --- a/src/Fantomas/CheckCommand.fs +++ b/src/Fantomas/CheckCommand.fs @@ -1,24 +1,27 @@ module Fantomas.CheckCommand -open System.IO -open Fantomas open Fantomas.Arguments +open Fantomas.Cli open Fantomas.CommandResult open Fantomas.FormatCommand open Fantomas.Plan -let checkCode (filenames: string seq) : Async = +let checkCode (env: CliEnvironment) (filenames: string seq) : Async = async { let! formatted = filenames |> Seq.map (fun filename -> async { - let! content = File.ReadAllTextAsync filename |> Async.AwaitTask - return! formatContentAsync (FormatParams.Create(true, false, filename)) content + let! content = 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 = + let getChangedFile: FormatResult -> string option = function | FormatResult.Unchanged _ | FormatResult.IgnoredFile _ -> None @@ -26,35 +29,35 @@ let checkCode (filenames: string seq) : Async = | FormatResult.Error(f, _) | FormatResult.InvalidCode(f, _) -> Some f - let changes = formatted |> Seq.choose getChangedFile |> Seq.toList + let changes: string list = formatted |> Seq.choose getChangedFile |> Seq.toList - let getErrors = + let getErrors: FormatResult -> (string * exn) option = function | FormatResult.Error(f, e) -> Some(f, e) | _ -> None - let errors = formatted |> Seq.choose getErrors |> Seq.toList + let errors: (string * exn) list = formatted |> Seq.choose getErrors |> Seq.toList return { Errors = errors; Formatted = changes } } -let runCheckCommand (ignoreFile: IgnoreFile option) (inputPath: InputPath) : CheckCommandResult = +let runCheckCommand (env: CliEnvironment) (inputPath: InputPath) : CheckCommandResult = // A check never writes, so the output path it plans against is the input itself. - match plan ignoreFile inputPath OutputPath.NotKnown with + match plan env.FileSystem env.IgnoreFile inputPath OutputPath.NotKnown with | Error problem -> CheckCommandResult.InvalidInput problem | Ok items -> - let ignored = + let ignored: string list = items |> List.choose (fun item -> match item with | WorkItem.Ignored file -> Some file | WorkItem.Format _ -> None) - let toCheck = + 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 toCheck)) + CheckCommandResult.Completed(ignored, Async.RunSynchronously(checkCode env toCheck)) diff --git a/src/Fantomas/CheckCommand.fsi b/src/Fantomas/CheckCommand.fsi index e20d85c046..3aa517cbd0 100644 --- a/src/Fantomas/CheckCommand.fsi +++ b/src/Fantomas/CheckCommand.fsi @@ -1,12 +1,12 @@ module Fantomas.CheckCommand -open Fantomas open Fantomas.Arguments +open Fantomas.Cli open Fantomas.CommandResult /// Format every file in memory and report which ones came out different, without writing anything. -val checkCode: filenames: string seq -> Async +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: ignoreFile: IgnoreFile option -> inputPath: InputPath -> CheckCommandResult +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..5e2029aa81 --- /dev/null +++ b/src/Fantomas/Cli.fs @@ -0,0 +1,17 @@ +module Fantomas.Cli + +open System.IO.Abstractions +open Fantomas +open Fantomas.Core +open Fantomas.Logging + +[] +type CliEnvironment = + { FileSystem: IFileSystem + IgnoreFile: IgnoreFile option + ReadConfiguration: string -> FormatConfig } + +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..de2c82db8f --- /dev/null +++ b/src/Fantomas/Cli.fsi @@ -0,0 +1,27 @@ +module Fantomas.Cli + +open System.IO.Abstractions +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 + } + +/// 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/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index bf96b517e3..73dccbae97 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -33,6 +33,8 @@ + + diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index d330b9086c..e76e024e67 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -2,11 +2,13 @@ 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 @@ -23,33 +25,27 @@ type FormatParams = Profile = profile File = file } - static member Create(compareWithoutLineEndings: bool, profile: bool, file: string) = - { Config = EditorConfig.readConfiguration file - CompareWithoutLineEndings = compareWithoutLineEndings - Profile = profile - File = file } - let private carriageReturn = Text.RegularExpressions.Regex(@"\r") let formatContentAsync (formatParams: FormatParams) (originalContent: string) : Async = async { try - let isSignatureFile = Path.GetExtension(formatParams.File) = ".fsi" + let isSignatureFile: bool = Path.GetExtension(formatParams.File) = ".fsi" let! { Code = formattedContent }, profileInfo = if formatParams.Profile then async { - let sw = Diagnostics.Stopwatch.StartNew() + let sw: Diagnostics.Stopwatch = Diagnostics.Stopwatch.StartNew() let! res = CodeFormatter.FormatDocumentAsync(isSignatureFile, originalContent, formatParams.Config) sw.Stop() - let count = + let count: int = originalContent.Length - originalContent.Replace(Environment.NewLine, "").Length - let profileInfo = + let profileInfo: ProfileInfo = { LineCount = count TimeTaken = sw.Elapsed } @@ -63,7 +59,7 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : return res, None } - let contentChanged = + let contentChanged: bool = if formatParams.CompareWithoutLineEndings then let stripNewlines (s: string) = carriageReturn.Replace(s, String.Empty) @@ -89,41 +85,46 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : return FormatResult.Error(formatParams.File, ex) } -let hasByteOrderMark (file: string) : Async = +let hasByteOrderMark (fs: IFileSystem) (file: string) : Async = async { - if File.Exists(file) then - let preamble = Encoding.UTF8.GetPreamble() + if fs.File.Exists(file) then + let preamble: byte array = Encoding.UTF8.GetPreamble() - use file = new FileStream(file, FileMode.Open, FileAccess.Read) + use stream = fs.File.OpenRead(file) - let mutable bom = Array.zeroCreate 3 - do! file.ReadAsync(bom, 0, 3) |> Async.AwaitTask |> Async.Ignore + let mutable bom: byte array = Array.zeroCreate 3 + do! stream.ReadAsync(bom, 0, 3) |> Async.AwaitTask |> Async.Ignore return bom = preamble else return false } let processSourceString - (force: bool) - (profile: bool) + (env: CliEnvironment) + (settings: CliSettings) (s: string) (fileName: string) (config: FormatConfig) : Async = + let fs: IFileSystem = env.FileSystem + let force: bool = settings.Force + let writeResult (formatted: string) = async { - let! hasBom = hasByteOrderMark fileName + let! hasBom = hasByteOrderMark fs fileName if hasBom then - do! File.WriteAllTextAsync(fileName, formatted, Encoding.UTF8) |> Async.AwaitTask + do! fs.File.WriteAllTextAsync(fileName, formatted, Encoding.UTF8) |> Async.AwaitTask else - do! File.WriteAllTextAsync(fileName, formatted) |> Async.AwaitTask + do! fs.File.WriteAllTextAsync(fileName, formatted) |> Async.AwaitTask logGrEqDetailed $"%s{fileName} has been written." } async { - let formatParams = FormatParams.Create(config, false, profile, fileName) + let formatParams: FormatParams = + FormatParams.Create(config, false, settings.Profile, fileName) + let! formatted = formatContentAsync formatParams s match formatted with @@ -142,10 +143,21 @@ let processSourceString | FormatResult.InvalidCode(file, _) -> return FormatResult.Error(file, invalidResultException file) } -let processSourceFile (force: bool) (profile: bool) (inFile: string) (tw: TextWriter) : Async = +let processSourceFile + (env: CliEnvironment) + (settings: CliSettings) + (inFile: string) + (tw: TextWriter) + : Async = + let force: bool = settings.Force + async { - let! originalContent = File.ReadAllTextAsync inFile |> Async.AwaitTask - let! formatted = formatContentAsync (FormatParams.Create(false, profile, inFile)) originalContent + let! originalContent = env.FileSystem.File.ReadAllTextAsync inFile |> Async.AwaitTask + + let formatParams: FormatParams = + FormatParams.Create(env.ReadConfiguration inFile, false, settings.Profile, inFile) + + let! formatted = formatContentAsync formatParams originalContent match formatted with | FormatResult.Formatted(_, formattedContent, _) as r -> @@ -169,23 +181,25 @@ let processSourceFile (force: bool) (profile: bool) (inFile: string) (tw: TextWr // 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) (profile: bool) (inFile: string) (outFile: string) : Async = +let fileToFile (env: CliEnvironment) (settings: CliSettings) (inFile: string) (outFile: string) : Async = + let fs: IFileSystem = env.FileSystem + async { logGrEqDetailed $"Processing %s{inFile}" use buffer = new StringWriter() - let! processResult = processSourceFile force profile inFile buffer + let! processResult = processSourceFile env settings inFile buffer match processResult with | FormatResult.Formatted _ | FormatResult.Unchanged _ -> - let! hasByteOrderMark = hasByteOrderMark inFile - ensureParentFolderExists outFile - let contents = buffer.ToString() + let! hasByteOrderMark = hasByteOrderMark fs inFile + ensureParentFolderExists fs outFile + let contents: string = buffer.ToString() if hasByteOrderMark then - do! File.WriteAllTextAsync(outFile, contents, Encoding.UTF8) |> Async.AwaitTask + do! fs.File.WriteAllTextAsync(outFile, contents, Encoding.UTF8) |> Async.AwaitTask else - do! File.WriteAllTextAsync(outFile, contents) |> Async.AwaitTask + do! fs.File.WriteAllTextAsync(outFile, contents) |> Async.AwaitTask logGrEqDetailed $"%s{outFile} has been written." | FormatResult.IgnoredFile _ @@ -195,43 +209,48 @@ let fileToFile (force: bool) (profile: bool) (inFile: string) (outFile: string) return processResult } -let processFile (force: bool) (profile: bool) (inputFile: string) (outputFile: string) : Async = +let processFile + (env: CliEnvironment) + (settings: CliSettings) + (inputFile: string) + (outputFile: string) + : Async = async { try - if not (isSamePath inputFile outputFile) then - return! fileToFile force profile inputFile outputFile + if not (isSamePath env.FileSystem inputFile outputFile) then + return! fileToFile env settings inputFile outputFile else logGrEqDetailed $"Processing %s{inputFile}" - let! content = File.ReadAllTextAsync inputFile |> Async.AwaitTask - let config = EditorConfig.readConfiguration inputFile - return! processSourceString force profile content inputFile config + let! content = env.FileSystem.File.ReadAllTextAsync inputFile |> Async.AwaitTask + return! processSourceString env settings content inputFile (env.ReadConfiguration inputFile) with e -> return FormatResult.Error(inputFile, e) } let runFormatCommand - (force: bool) - (profile: bool) - (ignoreFile: IgnoreFile option) + (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 (Directory.Exists outputFolder) -> - Directory.CreateDirectory outputFolder |> ignore + | InputPath.Folder _, OutputPath.IO outputFolder when not (fs.Directory.Exists outputFolder) -> + fs.Directory.CreateDirectory outputFolder |> ignore | _ -> () - match plan ignoreFile inputPath outputPath with + match plan fs 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 force profile inputFile outputFile) + | WorkItem.Format(inputFile, outputFile) -> processFile env settings inputFile outputFile) |> Async.Parallel |> Async.RunSynchronously |> FormatCommandResult.Completed diff --git a/src/Fantomas/FormatCommand.fsi b/src/Fantomas/FormatCommand.fsi index 9e5ae03266..5d345ee08b 100644 --- a/src/Fantomas/FormatCommand.fsi +++ b/src/Fantomas/FormatCommand.fsi @@ -1,8 +1,8 @@ module Fantomas.FormatCommand -open Fantomas open Fantomas.Core open Fantomas.Arguments +open Fantomas.Cli open Fantomas.CommandResult type FormatParams = @@ -11,8 +11,6 @@ type FormatParams = Profile: bool File: string } - /// Read the configuration for the file from the `.editorconfig` files above it. - static member Create: bool * bool * string -> FormatParams 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 @@ -23,9 +21,8 @@ val formatContentAsync: formatParams: FormatParams -> originalContent: string -> /// happened is returned rather than printed, so that a caller can inspect it before any of it /// reaches a console. val runFormatCommand: - force: bool -> - profile: bool -> - ignoreFile: IgnoreFile option -> + env: CliEnvironment -> + settings: CliSettings -> inputPath: InputPath -> outputPath: OutputPath -> FormatCommandResult diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index 4a7bf2b002..7e74fd0d93 100644 --- a/src/Fantomas/IgnoreFile.fs +++ b/src/Fantomas/IgnoreFile.fs @@ -70,15 +70,13 @@ module IgnoreFile = 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 = match ignoreFile with diff --git a/src/Fantomas/IgnoreFile.fsi b/src/Fantomas/IgnoreFile.fsi index e12134a589..1150e53235 100644 --- a/src/Fantomas/IgnoreFile.fsi +++ b/src/Fantomas/IgnoreFile.fsi @@ -32,15 +32,10 @@ module IgnoreFile = val loadIgnoreList: fs: IFileSystem -> ignoreFilePath: string -> IsPathIgnored - val internal current': - fs: IFileSystem -> - currentDirectory: string -> - loadIgnoreList: (string -> IsPathIgnored) -> - Lazy - - /// 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 + /// 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 val isIgnoredFile: ignoreFile: IgnoreFile option -> file: string -> bool diff --git a/src/Fantomas/Paths.fs b/src/Fantomas/Paths.fs index 59886ac3fb..61205dcbc4 100644 --- a/src/Fantomas/Paths.fs +++ b/src/Fantomas/Paths.fs @@ -2,37 +2,36 @@ module Fantomas.Paths open System open System.IO +open System.IO.Abstractions -let extensions = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] +let extensions: Set = set [| ".fs"; ".fsx"; ".fsi"; ".ml"; ".mli" |] -let isInExcludedDir (fullPath: string) = +let isInExcludedDir (fullPath: string) : bool = 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) = +let isFSharpFile (s: string) : bool = Set.contains (Path.GetExtension s) extensions -let findAllFilesRecursively path = - let searchOption = SearchOption.AllDirectories - - Directory.GetFiles(path, "*.*", searchOption) +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 (file: string) : unit = - let folder = Path.GetDirectoryName(file) +let ensureParentFolderExists (fs: IFileSystem) (file: string) : unit = + let folder: string = fs.Path.GetDirectoryName(file) if not (String.IsNullOrEmpty folder) then - Directory.CreateDirectory(folder) |> ignore + fs.Directory.CreateDirectory(folder) |> ignore -let isSamePath (left: string) (right: string) : bool = - String.Equals(Path.GetFullPath left, Path.GetFullPath right, StringComparison.Ordinal) +let isSamePath (fs: IFileSystem) (left: string) (right: string) : bool = + String.Equals(fs.Path.GetFullPath left, fs.Path.GetFullPath right, StringComparison.Ordinal) -let isInFolder (folder: string) (file: string) : bool = - let folder = +let isInFolder (fs: IFileSystem) (folder: string) (file: string) : bool = + let folder: string = String.Concat( - Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar), - string Path.DirectorySeparatorChar + fs.Path.GetFullPath(folder).TrimEnd(fs.Path.DirectorySeparatorChar), + string fs.Path.DirectorySeparatorChar ) - Path.GetFullPath(file).StartsWith(folder, StringComparison.Ordinal) + fs.Path.GetFullPath(file).StartsWith(folder, StringComparison.Ordinal) diff --git a/src/Fantomas/Paths.fsi b/src/Fantomas/Paths.fsi index 0d58e42580..7ece3d3038 100644 --- a/src/Fantomas/Paths.fsi +++ b/src/Fantomas/Paths.fsi @@ -1,5 +1,7 @@ module Fantomas.Paths +open System.IO.Abstractions + /// The file extensions Fantomas formats. val extensions: Set @@ -10,17 +12,17 @@ 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: path: string -> string seq +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. Path.GetDirectoryName yields an empty string for a bare file name. -val ensureParentFolderExists: file: string -> unit +/// 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: left: string -> right: string -> bool +val isSamePath: fs: IFileSystem -> left: string -> right: string -> bool /// Is a file located inside a folder, at any depth? -val isInFolder: folder: string -> file: string -> bool +val isInFolder: fs: IFileSystem -> folder: string -> file: string -> bool diff --git a/src/Fantomas/Plan.fs b/src/Fantomas/Plan.fs index 9a89405163..ce87b2c81f 100644 --- a/src/Fantomas/Plan.fs +++ b/src/Fantomas/Plan.fs @@ -1,6 +1,6 @@ module Fantomas.Plan -open System.IO +open System.IO.Abstractions open Fantomas open Fantomas.Arguments open Fantomas.CommandResult @@ -12,6 +12,7 @@ type WorkItem = | Format of inputFile: string * outputFile: string let plan + (fs: IFileSystem) (ignoreFile: IgnoreFile option) (inputPath: InputPath) (outputPath: OutputPath) @@ -23,22 +24,27 @@ let plan WorkItem.Format(inputFile, outputFile) let folder (inputFolder: string) (outputFolder: string) : WorkItem list = - let inPlace = isSamePath inputFolder outputFolder + 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)) - 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.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. - Path.Combine(outputFolder, Path.GetRelativePath(inputFolder, i)) - - item i o) + 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 diff --git a/src/Fantomas/Plan.fsi b/src/Fantomas/Plan.fsi index ee7f3ddc5c..40342af2ec 100644 --- a/src/Fantomas/Plan.fsi +++ b/src/Fantomas/Plan.fsi @@ -1,5 +1,6 @@ module Fantomas.Plan +open System.IO.Abstractions open Fantomas open Fantomas.Arguments open Fantomas.CommandResult @@ -15,6 +16,7 @@ type WorkItem = /// 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 -> ignoreFile: IgnoreFile option -> inputPath: InputPath -> outputPath: OutputPath -> diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index c122096da7..9366ddd9f2 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -1,13 +1,13 @@ module Program open System -// Fantomas.Core has a FormatResult of its own. Opening Fantomas last is what makes the -// FormatResult named here the one this project defines. +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 @@ -17,23 +17,26 @@ open Argu 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 = results.TryGetResult <@ Arguments.Input @> |> classifyInputPath + let fileSystem: IFileSystem = FileSystem() - let force = results.Contains <@ Arguments.Force @> - let profile = results.Contains <@ Arguments.Profile @> - let version = results.TryGetResult <@ Arguments.Version @> + let inputPath: InputPath = + results.TryGetResult <@ Arguments.Input @> |> classifyInputPath fileSystem - let verbosityLevel = + let force: bool = results.Contains <@ Arguments.Force @> + let profile: bool = results.Contains <@ Arguments.Profile @> + let version: Arguments option = results.TryGetResult <@ Arguments.Version @> + + let verbosityLevel: VerbosityLevel = match parseVerbosity (results.TryGetResult <@ Arguments.Verbosity @>) with | Some level -> level | None -> @@ -41,10 +44,10 @@ let main argv = 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 @@ -52,10 +55,10 @@ let main argv = AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> closeAndFlushLog ()) - let check = results.Contains <@ Arguments.Check @> + let check: bool = results.Contains <@ Arguments.Check @> - let versionLog = - let version = CodeFormatter.GetVersion() + let versionLog: string = + let version: string = CodeFormatter.GetVersion() $"Fantomas v%s{version}" if Option.isNone version then @@ -65,7 +68,7 @@ let main argv = stdlog versionLog 0 elif isDaemon then - let daemon = + let daemon: FantomasDaemon = new FantomasDaemon(Console.OpenStandardOutput(), Console.OpenStandardInput()) AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> (daemon :> IDisposable).Dispose()) @@ -73,10 +76,22 @@ let main argv = daemon.WaitForClose.GetAwaiter().GetResult() 0 else - let ignoreFile = IgnoreFile.current.Force() + let environment: CliEnvironment = + { FileSystem = fileSystem + IgnoreFile = + IgnoreFile.findInDirectory + fileSystem + Environment.CurrentDirectory + (IgnoreFile.loadIgnoreList fileSystem) + ReadConfiguration = EditorConfig.readConfiguration } + + let settings: CliSettings = + { Force = force + Profile = profile + Verbosity = verbosity } if check then - runCheckCommand ignoreFile inputPath |> reportCheckCommand + runCheckCommand environment inputPath |> reportCheckCommand environment else - runFormatCommand force profile ignoreFile inputPath outputPath - |> reportFormatCommand profile verbosity + runFormatCommand environment settings inputPath outputPath + |> reportFormatCommand environment settings diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index f12a2b698a..b6fe0b5c2f 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -1,21 +1,22 @@ module Fantomas.Report open System -open System.IO +open System.IO.Abstractions 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 open Fantomas.CommandResult // 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 = +let sourceOf (fs: IFileSystem) (file: string) : string = try - File.ReadAllText file + fs.File.ReadAllText file with _ -> String.Empty @@ -30,17 +31,17 @@ let partitionResults | 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 + let ex: FormatException = invalidResultException file (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) -let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = +let reportError (fs: IFileSystem) (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = let describeOther () : string = - let message = + let message: string = match verbosity with | VerbosityLevel.Normal -> match exn with | :? DefineParseException as dpe -> - let combinations = + let combinations: string = dpe.Combinations |> List.map (fun c -> if c = "no defines" then "no defines" else $"[%s{c}]") |> String.concat ", " @@ -57,7 +58,7 @@ let reportError (verbosity: VerbosityLevel) (file: string, exn: Exception) : uni // 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 + match Diagnostics.describeParseFailure file (sourceOf fs file) exn with | Some parseFailure -> elog parseFailure | None -> elog (describeOther ()) @@ -68,7 +69,7 @@ let reportProfileInfo (profile: bool) (file: string, profileInfo: ProfileInfo op let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) list) : unit = if profile && not (List.isEmpty results) then - let table = Table().AddColumns([| "File"; "Line count"; "Time taken" |]) + let table: Table = Table().AddColumns([| "File"; "Line count"; "Time taken" |]) results |> List.choose (fun (f, p) -> p |> Option.map (fun p -> f, p)) @@ -78,7 +79,12 @@ let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) l table |> AnsiConsole.Write -let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #(FormatResult seq)) : int = +let reportFormatResults + (fs: IFileSystem) + (profile: bool) + (verbosity: VerbosityLevel) + (results: #(FormatResult seq)) + : int = match Seq.tryExactlyOne results with | Some singleResult -> match singleResult with @@ -94,18 +100,18 @@ let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #( reportProfileInfo profile (f, p) 0 | FormatResult.Error(f, e) -> - reportError verbosity (f, e) + reportError fs verbosity (f, e) 1 | FormatResult.InvalidCode(f, _) -> - let ex = invalidResultException f - reportError verbosity (f, ex) + let ex: FormatException = invalidResultException f + reportError fs verbosity (f, ex) 1 | None -> let oks, ignored, unchanged, errored = partitionResults results let centeredColumn (v: string) = TableColumn(v).Centered() - let summary = + let summary: Table = Table() .AddColumns( [| "[green]Formatted[/]" @@ -123,15 +129,15 @@ let reportFormatResults (profile: bool) (verbosity: VerbosityLevel) (results: #( AnsiConsole.Write summary for e in errored do - reportError verbosity e + reportError fs verbosity e reportProfileInfos profile (oks @ unchanged) if errored.Length > 0 then 1 else 0 -let reportCheckResults (checkResult: CheckResult) = +let reportCheckResults (fs: IFileSystem) (checkResult: CheckResult) = for filename, exn in checkResult.Errors do - match Diagnostics.describeParseFailure filename (sourceOf filename) exn with + match Diagnostics.describeParseFailure filename (sourceOf fs filename) exn with | Some parseFailure -> elog parseFailure | None -> elog $"error: Failed to format %s{filename}: %s{exn.ToString()}" @@ -145,7 +151,7 @@ let describeInputProblem (problem: InputProblem) : string = | 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 (profile: bool) (verbosity: VerbosityLevel) (result: FormatCommandResult) : int = +let reportFormatCommand (env: CliEnvironment) (settings: CliSettings) (result: FormatCommandResult) : int = match result with | FormatCommandResult.InvalidInput problem -> elog (describeInputProblem problem) @@ -153,9 +159,10 @@ let reportFormatCommand (profile: bool) (verbosity: VerbosityLevel) (result: For | FormatCommandResult.Failed error -> elog $"%s{error.Message}" 1 - | FormatCommandResult.Completed results -> reportFormatResults profile verbosity results + | FormatCommandResult.Completed results -> + reportFormatResults env.FileSystem settings.Profile settings.Verbosity results -let reportCheckCommand (result: CheckCommandResult) : int = +let reportCheckCommand (env: CliEnvironment) (result: CheckCommandResult) : int = match result with | CheckCommandResult.InvalidInput problem -> elog (describeInputProblem problem) @@ -168,5 +175,5 @@ let reportCheckCommand (result: CheckCommandResult) : int = logGrEqDetailed "No changes required." 0 else - reportCheckResults checkResult + reportCheckResults env.FileSystem checkResult if checkResult.HasErrors then 1 else 99 diff --git a/src/Fantomas/Report.fsi b/src/Fantomas/Report.fsi index 3224923519..3d0cc05bf7 100644 --- a/src/Fantomas/Report.fsi +++ b/src/Fantomas/Report.fsi @@ -1,7 +1,7 @@ module Fantomas.Report +open Fantomas.Cli open Fantomas.CommandResult -open Fantomas.Logging /// 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. @@ -9,8 +9,8 @@ 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: profile: bool -> verbosity: VerbosityLevel -> result: FormatCommandResult -> int +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: result: CheckCommandResult -> int +val reportCheckCommand: env: CliEnvironment -> result: CheckCommandResult -> int From 079f3a7cf877297e4a0d1366dff9617bc6855dd8 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 11:55:47 +0200 Subject: [PATCH 06/17] Hand the logger and the console in rather than reaching for them Formatting, reporting and the help page all wrote to process wide state: a Serilog logger held in a static, Spectre's global AnsiConsole, and System.Console inside the help page. None of it could be read back without capturing the output of a real process, which is why almost every test in the Integration folder starts one. CliEnvironment now carries an ILogger and an IAnsiConsole alongside the file system, and FormatCommand and Report hold no reference to either global. A test hands over a logger with a collecting sink and reads back what a run would have printed. The help page becomes a value. Its two lazy colour flags collapse into a Palette of NoColour, FourBit and EightBit, which removes a state that was representable and meaningless, and render returns the page as lines so it can be inspected without a console. print is now render composed with a write. Which palette a terminal gets is unchanged: colours are dropped when standard out is redirected and eight bit codes are used where the terminal takes them. IgnoreFile.isIgnoredFile took the logger it used from the static too. It is now a parameter, so the dependency is stated, and the message says which file and which ignore file could not be told apart instead of dumping the exception with %A. Give the daemon a DaemonEnvironment of its own rather than letting it build a file system and reach for a logger inside its constructor. It is deliberately narrower than the command line tool's: 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. FileSystem is now constructed in one place in the project, and the Serilog static is read in one place, both in main. --- src/Fantomas.Tests/Integration/DaemonTests.fs | 2 +- src/Fantomas.Tests/TestHelpers.fs | 13 +- src/Fantomas/CheckCommand.fs | 2 +- src/Fantomas/Cli.fs | 6 +- src/Fantomas/Cli.fsi | 7 + src/Fantomas/Daemon.fs | 20 +- src/Fantomas/Daemon.fsi | 14 +- src/Fantomas/FormatCommand.fs | 16 +- src/Fantomas/HelpPage.fs | 173 +++++++++++------- src/Fantomas/HelpPage.fsi | 17 +- src/Fantomas/IgnoreFile.fs | 15 +- src/Fantomas/IgnoreFile.fsi | 5 +- src/Fantomas/Logging.fs | 8 +- src/Fantomas/Logging.fsi | 8 - src/Fantomas/Plan.fs | 4 +- src/Fantomas/Plan.fsi | 2 + src/Fantomas/Program.fs | 21 ++- src/Fantomas/Report.fs | 70 ++++--- 18 files changed, 250 insertions(+), 153 deletions(-) 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/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 65afe8845f..c1237afc94 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -5,8 +5,11 @@ open System.Diagnostics open System.IO open System.IO.Abstractions open System.Text +open Serilog +open Spectre.Console open Fantomas open Fantomas.Cli +open Fantomas.Daemon [] module String = @@ -110,12 +113,20 @@ type FantomasIgnoreFile internal (content: string) = if File.Exists(filename) then File.Delete(filename) +/// 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 } + ReadConfiguration = EditorConfig.readConfiguration + Log = Log.Logger + Console = AnsiConsole.Console } type FantomasToolResult = { ExitCode: int diff --git a/src/Fantomas/CheckCommand.fs b/src/Fantomas/CheckCommand.fs index 089d83946a..ad74ac1441 100644 --- a/src/Fantomas/CheckCommand.fs +++ b/src/Fantomas/CheckCommand.fs @@ -43,7 +43,7 @@ let checkCode (env: CliEnvironment) (filenames: string seq) : Async let runCheckCommand (env: CliEnvironment) (inputPath: InputPath) : CheckCommandResult = // A check never writes, so the output path it plans against is the input itself. - match plan env.FileSystem env.IgnoreFile inputPath OutputPath.NotKnown with + match plan env.FileSystem env.Log env.IgnoreFile inputPath OutputPath.NotKnown with | Error problem -> CheckCommandResult.InvalidInput problem | Ok items -> let ignored: string list = diff --git a/src/Fantomas/Cli.fs b/src/Fantomas/Cli.fs index 5e2029aa81..ec7c9dc48a 100644 --- a/src/Fantomas/Cli.fs +++ b/src/Fantomas/Cli.fs @@ -1,6 +1,8 @@ module Fantomas.Cli open System.IO.Abstractions +open Serilog +open Spectre.Console open Fantomas open Fantomas.Core open Fantomas.Logging @@ -9,7 +11,9 @@ open Fantomas.Logging type CliEnvironment = { FileSystem: IFileSystem IgnoreFile: IgnoreFile option - ReadConfiguration: string -> FormatConfig } + ReadConfiguration: string -> FormatConfig + Log: ILogger + Console: IAnsiConsole } type CliSettings = { Force: bool diff --git a/src/Fantomas/Cli.fsi b/src/Fantomas/Cli.fsi index de2c82db8f..1868312500 100644 --- a/src/Fantomas/Cli.fsi +++ b/src/Fantomas/Cli.fsi @@ -1,6 +1,8 @@ module Fantomas.Cli open System.IO.Abstractions +open Serilog +open Spectre.Console open Fantomas open Fantomas.Core open Fantomas.Logging @@ -17,6 +19,11 @@ type CliEnvironment = /// 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 settled by `Logging.createLogger`. + 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 diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index c5af67aaa1..b68160f845 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 ()) @@ -47,6 +54,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 +63,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 @@ -99,9 +107,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 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/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index e76e024e67..d8518d1501 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -118,7 +118,7 @@ let processSourceString else do! fs.File.WriteAllTextAsync(fileName, formatted) |> Async.AwaitTask - logGrEqDetailed $"%s{fileName} has been written." + env.Log.Debug $"%s{fileName} has been written." } async { @@ -132,11 +132,11 @@ let processSourceString do! formattedContent |> writeResult return r | FormatResult.InvalidCode(file, formattedContent) when force -> - stdlog $"%s{file} was not valid after formatting." + env.Log.Information $"%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" + env.Log.Debug $"'%s{file}' was unchanged" return r | FormatResult.IgnoredFile _ as r -> return r | FormatResult.Error _ as r -> return r @@ -164,7 +164,7 @@ let processSourceFile do! tw.WriteAsync(formattedContent) |> Async.AwaitTask return r | FormatResult.InvalidCode(file, formattedContent) when force -> - stdlog $"%s{file} was not valid after formatting." + env.Log.Information $"%s{file} was not valid after formatting." do! tw.WriteAsync(formattedContent) |> Async.AwaitTask return FormatResult.Formatted(inFile, formattedContent, None) | FormatResult.Unchanged _ as r -> @@ -185,7 +185,7 @@ let fileToFile (env: CliEnvironment) (settings: CliSettings) (inFile: string) (o let fs: IFileSystem = env.FileSystem async { - logGrEqDetailed $"Processing %s{inFile}" + env.Log.Debug $"Processing %s{inFile}" use buffer = new StringWriter() let! processResult = processSourceFile env settings inFile buffer @@ -201,7 +201,7 @@ let fileToFile (env: CliEnvironment) (settings: CliSettings) (inFile: string) (o else do! fs.File.WriteAllTextAsync(outFile, contents) |> Async.AwaitTask - logGrEqDetailed $"%s{outFile} has been written." + env.Log.Debug $"%s{outFile} has been written." | FormatResult.IgnoredFile _ | FormatResult.InvalidCode _ | FormatResult.Error _ -> () @@ -220,7 +220,7 @@ let processFile if not (isSamePath env.FileSystem inputFile outputFile) then return! fileToFile env settings inputFile outputFile else - logGrEqDetailed $"Processing %s{inputFile}" + env.Log.Debug $"Processing %s{inputFile}" let! content = env.FileSystem.File.ReadAllTextAsync inputFile |> Async.AwaitTask return! processSourceString env settings content inputFile (env.ReadConfiguration inputFile) with e -> @@ -243,7 +243,7 @@ let runFormatCommand fs.Directory.CreateDirectory outputFolder |> ignore | _ -> () - match plan fs env.IgnoreFile inputPath outputPath with + match plan fs env.Log env.IgnoreFile inputPath outputPath with | Error problem -> FormatCommandResult.InvalidInput problem | Ok items -> items diff --git a/src/Fantomas/HelpPage.fs b/src/Fantomas/HelpPage.fs index 81aa917517..42732dce30 100644 --- a/src/Fantomas/HelpPage.fs +++ b/src/Fantomas/HelpPage.fs @@ -6,63 +6,75 @@ 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)) @@ -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 writeExample (write: string -> unit) (palette: Palette) (command: string, description: string) : unit = let name, arguments = 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..604b32a355 100644 --- a/src/Fantomas/HelpPage.fsi +++ b/src/Fantomas/HelpPage.fsi @@ -1,8 +1,21 @@ 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 /// Error handler for Argu. `--help` renders the page above, and an argument error is diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index 7e74fd0d93..e3662a5974 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 @@ -78,15 +78,20 @@ module IgnoreFile = // `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}" + false diff --git a/src/Fantomas/IgnoreFile.fsi b/src/Fantomas/IgnoreFile.fsi index 1150e53235..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 @@ -38,4 +39,6 @@ module IgnoreFile = val findInDirectory: fs: IFileSystem -> currentDirectory: string -> loadIgnoreList: (string -> IsPathIgnored) -> IgnoreFile option - 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..68cbbbca4c 100644 --- a/src/Fantomas/Logging.fsi +++ b/src/Fantomas/Logging.fsi @@ -16,12 +16,4 @@ val initLogger: level: VerbosityLevel -> VerbosityLevel 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 - val closeAndFlushLog: unit -> unit diff --git a/src/Fantomas/Plan.fs b/src/Fantomas/Plan.fs index ce87b2c81f..05ef4911fe 100644 --- a/src/Fantomas/Plan.fs +++ b/src/Fantomas/Plan.fs @@ -4,6 +4,7 @@ open System.IO.Abstractions open Fantomas open Fantomas.Arguments open Fantomas.CommandResult +open Serilog open Fantomas.Paths [] @@ -13,12 +14,13 @@ type WorkItem = let plan (fs: IFileSystem) + (log: ILogger) (ignoreFile: IgnoreFile option) (inputPath: InputPath) (outputPath: OutputPath) : Result = let item (inputFile: string) (outputFile: string) : WorkItem = - if IgnoreFile.isIgnoredFile ignoreFile inputFile then + if IgnoreFile.isIgnoredFile log ignoreFile inputFile then WorkItem.Ignored inputFile else WorkItem.Format(inputFile, outputFile) diff --git a/src/Fantomas/Plan.fsi b/src/Fantomas/Plan.fsi index 40342af2ec..22d5429a21 100644 --- a/src/Fantomas/Plan.fsi +++ b/src/Fantomas/Plan.fsi @@ -4,6 +4,7 @@ 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. @@ -17,6 +18,7 @@ type WorkItem = /// onto an input tree, and where the ignore file is consulted. val plan: fs: IFileSystem -> + log: ILogger -> ignoreFile: IgnoreFile option -> inputPath: InputPath -> outputPath: OutputPath -> diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 9366ddd9f2..29fd4a5bda 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -12,6 +12,8 @@ open Fantomas.FormatCommand open Fantomas.Report open Fantomas.CheckCommand open Argu +open Serilog +open Spectre.Console [] let main argv = @@ -55,6 +57,9 @@ let main argv = AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> closeAndFlushLog ()) + // The logger the calls above configured, now handed down rather than reached for. + let log: ILogger = Log.Logger + let check: bool = results.Contains <@ Arguments.Check @> let versionLog: string = @@ -62,14 +67,20 @@ let main argv = $"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: FantomasDaemon = - new FantomasDaemon(Console.OpenStandardOutput(), Console.OpenStandardInput()) + new FantomasDaemon( + Console.OpenStandardOutput(), + Console.OpenStandardInput(), + { FileSystem = fileSystem + ReadConfiguration = EditorConfig.readConfiguration + Log = log } + ) AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> (daemon :> IDisposable).Dispose()) @@ -83,7 +94,9 @@ let main argv = fileSystem Environment.CurrentDirectory (IgnoreFile.loadIgnoreList fileSystem) - ReadConfiguration = EditorConfig.readConfiguration } + ReadConfiguration = EditorConfig.readConfiguration + Log = log + Console = AnsiConsole.Console } let settings: CliSettings = { Force = force diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index b6fe0b5c2f..2dc426de78 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -2,6 +2,8 @@ module Fantomas.Report open System open System.IO.Abstractions +open Serilog +open Spectre.Console 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. @@ -34,7 +36,7 @@ let partitionResults let ex: FormatException = invalidResultException file (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) -let reportError (fs: IFileSystem) (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = +let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = let describeOther () : string = let message: string = match verbosity with @@ -58,16 +60,16 @@ let reportError (fs: IFileSystem) (verbosity: VerbosityLevel) (file: string, exn // 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 fs file) exn with - | Some parseFailure -> elog parseFailure - | None -> elog (describeOther ()) + match Diagnostics.describeParseFailure file (sourceOf env.FileSystem file) exn with + | Some parseFailure -> env.Log.Error parseFailure + | None -> env.Log.Error(describeOther ()) -let reportProfileInfo (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = +let reportProfileInfo (log: ILogger) (profile: bool) (file: string, profileInfo: ProfileInfo option) : unit = match profile, profileInfo with - | true, Some pI -> stdlog $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" + | true, Some pI -> log.Information $"%s{file} Line count: %d{pI.LineCount} Time taken %A{pI.TimeTaken}" | _ -> () -let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) list) : unit = +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" |]) @@ -77,34 +79,29 @@ let reportProfileInfos (profile: bool) (results: (string * ProfileInfo option) l |> List.fold (fun (t: Table) (f, p) -> t.AddRow([| f; string p.LineCount; p.TimeTaken.ToString("mm\:ss\.fff") |])) table - |> AnsiConsole.Write + |> console.Write -let reportFormatResults - (fs: IFileSystem) - (profile: bool) - (verbosity: VerbosityLevel) - (results: #(FormatResult seq)) - : int = +let reportFormatResults (env: CliEnvironment) (settings: CliSettings) (results: #(FormatResult seq)) : int = match Seq.tryExactlyOne results with | Some singleResult -> match singleResult with | FormatResult.Formatted(f, _, p) -> - stdlog $"%s{f} was formatted." - reportProfileInfo profile (f, p) + env.Log.Information $"%s{f} was formatted." + reportProfileInfo env.Log settings.Profile (f, p) 0 | FormatResult.IgnoredFile f -> - stdlog $"%s{f} was ignored." + env.Log.Information $"%s{f} was ignored." 0 | FormatResult.Unchanged(f, p) -> - stdlog $"%s{f} was unchanged." - reportProfileInfo profile (f, p) + env.Log.Information $"%s{f} was unchanged." + reportProfileInfo env.Log settings.Profile (f, p) 0 | FormatResult.Error(f, e) -> - reportError fs verbosity (f, e) + reportError env settings.Verbosity (f, e) 1 | FormatResult.InvalidCode(f, _) -> let ex: FormatException = invalidResultException f - reportError fs verbosity (f, ex) + reportError env settings.Verbosity (f, ex) 1 | None -> @@ -126,23 +123,23 @@ let reportFormatResults ) summary.Border <- TableBorder.MinimalDoubleHead - AnsiConsole.Write summary + env.Console.Write summary for e in errored do - reportError fs verbosity e + reportError env settings.Verbosity e - reportProfileInfos profile (oks @ unchanged) + reportProfileInfos env.Console settings.Profile (oks @ unchanged) if errored.Length > 0 then 1 else 0 -let reportCheckResults (fs: IFileSystem) (checkResult: CheckResult) = +let reportCheckResults (env: CliEnvironment) (checkResult: CheckResult) : unit = for filename, exn in checkResult.Errors do - match Diagnostics.describeParseFailure filename (sourceOf fs filename) exn with - | Some parseFailure -> elog parseFailure - | None -> elog $"error: Failed to format %s{filename}: %s{exn.ToString()}" + match Diagnostics.describeParseFailure filename (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 - stdlog $"%s{filename} needs formatting" + env.Log.Information $"%s{filename} needs formatting" let describeInputProblem (problem: InputProblem) : string = match problem with @@ -154,26 +151,25 @@ let describeInputProblem (problem: InputProblem) : string = let reportFormatCommand (env: CliEnvironment) (settings: CliSettings) (result: FormatCommandResult) : int = match result with | FormatCommandResult.InvalidInput problem -> - elog (describeInputProblem problem) + env.Log.Error(describeInputProblem problem) 1 | FormatCommandResult.Failed error -> - elog $"%s{error.Message}" + env.Log.Error $"%s{error.Message}" 1 - | FormatCommandResult.Completed results -> - reportFormatResults env.FileSystem settings.Profile settings.Verbosity results + | FormatCommandResult.Completed results -> reportFormatResults env settings results let reportCheckCommand (env: CliEnvironment) (result: CheckCommandResult) : int = match result with | CheckCommandResult.InvalidInput problem -> - elog (describeInputProblem problem) + env.Log.Error(describeInputProblem problem) 1 | CheckCommandResult.Completed(ignored, checkResult) -> for file in ignored do - logGrEqDetailed $"'%s{file}' was ignored" + env.Log.Debug $"'%s{file}' was ignored" if checkResult.IsValid then - logGrEqDetailed "No changes required." + env.Log.Debug "No changes required." 0 else - reportCheckResults env.FileSystem checkResult + reportCheckResults env checkResult if checkResult.HasErrors then 1 else 99 From aa93c9abbe88f0d00ff8aad0be7e3b189260f01e Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 13:01:26 +0200 Subject: [PATCH 07/17] Test path handling, argument parsing and planning in memory The behaviour that decides what a run will do had no direct tests at all. It was covered only through the Integration folder, where each case starts a real fantomas process against temporary files, so a failure pointed at a process's standard error rather than at a function. Add tests for Paths, Arguments and Plan, all against a MockFileSystem. Nothing touches the disk, nothing depends on the working directory the test host happens to have, and there are no temporary files to clean up. Plan is the one worth having most: it holds every combination of input path and output path, the mirroring of an input tree onto an output folder, the guard against formatting a previous run's output again, and the ignore file. TestHelpers gains what these need: building a file hierarchy in a mock file system, the root to hang paths from so no test writes a path by hand, a logger that writes nowhere, and one that keeps what was written for the reporting tests still to come. The process tests stay as they are. They are the safety net that made the preceding refactor possible, and retiring the ones these replace is a separate step. Every one of these passed on the first run, which says nothing on its own, so each was checked by breaking the code it covers: flattening the output tree rather than mirroring it, dropping the guard against re-formatting output, and removing the trailing separator in isInFolder. That found a test that passed for the wrong reason. It claimed a sibling folder starting with the folder's name is not inside it, but used `source` against `src`, which is not a prefix at all, so it could never have caught the bug it was named for. It now uses `src-generated` and does fail when the separator is dropped. --- src/Fantomas.Tests/ArgumentsTests.fs | 102 ++++++++++++++ src/Fantomas.Tests/Fantomas.Tests.fsproj | 3 + src/Fantomas.Tests/PathsTests.fs | 153 ++++++++++++++++++++ src/Fantomas.Tests/PlanTests.fs | 170 +++++++++++++++++++++++ src/Fantomas.Tests/TestHelpers.fs | 52 +++++++ 5 files changed, 480 insertions(+) create mode 100644 src/Fantomas.Tests/ArgumentsTests.fs create mode 100644 src/Fantomas.Tests/PathsTests.fs create mode 100644 src/Fantomas.Tests/PlanTests.fs diff --git a/src/Fantomas.Tests/ArgumentsTests.fs b/src/Fantomas.Tests/ArgumentsTests.fs new file mode 100644 index 0000000000..929cfb0781 --- /dev/null +++ b/src/Fantomas.Tests/ArgumentsTests.fs @@ -0,0 +1,102 @@ +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 by whether they carry an extension`` () = + 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 ``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/Fantomas.Tests.fsproj b/src/Fantomas.Tests/Fantomas.Tests.fsproj index 6c5009575b..4ea14db975 100644 --- a/src/Fantomas.Tests/Fantomas.Tests.fsproj +++ b/src/Fantomas.Tests/Fantomas.Tests.fsproj @@ -16,6 +16,9 @@ + + + diff --git a/src/Fantomas.Tests/PathsTests.fs b/src/Fantomas.Tests/PathsTests.fs new file mode 100644 index 0000000000..61cb57c132 --- /dev/null +++ b/src/Fantomas.Tests/PathsTests.fs @@ -0,0 +1,153 @@ +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 ``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 ``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..be8c1834f7 --- /dev/null +++ b/src/Fantomas.Tests/PlanTests.fs @@ -0,0 +1,170 @@ +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) = + 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) = + 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 ``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 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/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index c1237afc94..1240f0d2c0 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -6,6 +6,8 @@ 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 @@ -113,6 +115,56 @@ 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 + Error: 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.filter (fun (e: LogEvent) -> e.Level = level) + |> List.map (fun (e: LogEvent) -> e.RenderMessage()) + + { Information = atLevel LogEventLevel.Information + Error = atLevel LogEventLevel.Error + Debug = atLevel LogEventLevel.Debug } + + logger, collected + /// A `DaemonEnvironment` over the real file system, as the tool itself builds one. let realDaemonEnvironment: DaemonEnvironment = { FileSystem = FileSystem() From 9f4323b3da9d02967b55b47f78c8b45173e52a93 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 13:10:54 +0200 Subject: [PATCH 08/17] Test formatting, reporting and the help page in memory Formatting a file, reporting what a run did, and rendering the help page were covered only by starting a real fantomas process and reading its output. Now that the file system, the logger and the console are handed in, all three can be exercised directly. FormatCommandTests runs the real format command, with real Fantomas.Core formatting and real byte order mark handling, against a MockFileSystem, and asserts on what the file system holds afterwards. That covers what WriteTests and ByteOrderMarkTests prove by writing to temporary folders, without touching a disk or leaving anything to clean up. ReportTests pins the exit code and the message for every shape a command result can take, using a Serilog sink that keeps what was written and a Spectre console drawing into a string with colour and width fixed. It states outright that a single file gets a sentence and several get a table, which was implied before but asserted nowhere. HelpPageTests works on the rendered page rather than on captured output, which reaches two things a process test cannot: that stripping the escape sequences from a coloured page yields exactly the plain page, and that every line has the same visible width either way, which is what keeps the fixed columns aligned. Expose HelpPage.complaint, which reduces Argu's message to the line carrying the actual complaint. It is a pure function that no test could reach. Each of these was checked by breaking the code it covers. Three mutations to FormatCommand failed six tests, but reading which ones showed that the test for a file not gaining a byte order mark failed because of the mutation to folder creation rather than the one to the mark. Applying the inverse mutation on its own, always writing the mark, confirms that test and only that test fails. --- src/Fantomas.Tests/Fantomas.Tests.fsproj | 3 + src/Fantomas.Tests/FormatCommandTests.fs | 212 +++++++++++++++++++++ src/Fantomas.Tests/HelpPageTests.fs | 106 +++++++++++ src/Fantomas.Tests/ReportTests.fs | 224 +++++++++++++++++++++++ src/Fantomas.Tests/TestHelpers.fs | 51 ++++++ src/Fantomas/HelpPage.fsi | 4 + 6 files changed, 600 insertions(+) create mode 100644 src/Fantomas.Tests/FormatCommandTests.fs create mode 100644 src/Fantomas.Tests/HelpPageTests.fs create mode 100644 src/Fantomas.Tests/ReportTests.fs diff --git a/src/Fantomas.Tests/Fantomas.Tests.fsproj b/src/Fantomas.Tests/Fantomas.Tests.fsproj index 4ea14db975..0e9ab716fc 100644 --- a/src/Fantomas.Tests/Fantomas.Tests.fsproj +++ b/src/Fantomas.Tests/Fantomas.Tests.fsproj @@ -19,6 +19,9 @@ + + + diff --git a/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs new file mode 100644 index 0000000000..89f03d1030 --- /dev/null +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -0,0 +1,212 @@ +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 + +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 ``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 ``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/ReportTests.fs b/src/Fantomas.Tests/ReportTests.fs new file mode 100644 index 0000000000..8910470097 --- /dev/null +++ b/src/Fantomas.Tests/ReportTests.fs @@ -0,0 +1,224 @@ +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) = + let recorded: RecordedRun = run () + let code: int = reportFormatCommand recorded.Environment settings result + code, recorded.Log(), recorded.Drawn() + +let private reportCheck (result: CheckCommandResult) = + 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 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.last |> shouldContainText "Line count: 12" + +[] +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 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 1240f0d2c0..9eae26e173 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -11,6 +11,8 @@ open Serilog.Events open Spectre.Console open Fantomas open Fantomas.Cli +open Fantomas.Core +open Fantomas.Logging open Fantomas.Daemon [] @@ -165,6 +167,55 @@ let collectingLogger () : ILogger * (unit -> CollectedLog) = 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 + 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() diff --git a/src/Fantomas/HelpPage.fsi b/src/Fantomas/HelpPage.fsi index 604b32a355..cb14a1231a 100644 --- a/src/Fantomas/HelpPage.fsi +++ b/src/Fantomas/HelpPage.fsi @@ -18,6 +18,10 @@ val render: palette: Palette -> string list /// Write the `fantomas --help` page to standard out. 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. From a90628ccfbde5ab60604a3e93a0f988cb953211f Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 13:26:00 +0200 Subject: [PATCH 09/17] Retire the process tests the in-memory ones replace Nine test files started a real fantomas process to assert behaviour that is now covered directly, against a MockFileSystem, by the tests beside them. They are gone. What is left of Integration is a deliberate set rather than a residue: SmokeTests says why it exists in a header comment, and covers what only a real process can show, that the arguments are parsed at all, that 0, 99 and 1 reach the operating system, that a byte order mark survives a real disk rather than only the mock's account of one, and that .fantomasignore is found relative to the directory the tool was started in. ConfigTests, StandardStreamTests and the remains of the integration HelpPageTests stay for the same reason: .editorconfig is deliberately never mocked, and which stream a message lands on and how much colour a terminal gets are not observable from inside the process. HelpPageTests keeps only those; what the page says is settled against HelpPage.render. Two regression tests were carried over rather than dropped: that line endings alone do not make a file need formatting, and that a difference in the number of newlines does, which is issue 2461. Add CheckCommandTests, which the check command had none of, and the force and truncation cases FormatCommandTests was missing. Measure coverage for every test project rather than only Fantomas.Core.Tests. AltCover reads | as the separator between filters rather than as alternation, so one filter cannot name three assemblies; each project runs with the filter for the assembly it exercises and ReportGenerator merges the three reports. Locating the fantomas dll from the test assembly's own location broke under coverage, because AltCover runs the tests from an instrumented copy of the output folder. Resolve it from the source directory instead, which does not move. The suite goes from 129 tests in 17 seconds to 200 in 8, and 81.9% of the command line tool is now reachable without starting it. --- build.fsx | 68 ++++-- .../Fantomas.Client.Tests.fsproj | 1 + src/Fantomas.Client.Tests/packages.lock.json | 6 + src/Fantomas.Tests/CheckCommandTests.fs | 136 +++++++++++ src/Fantomas.Tests/CheckTests.fs | 59 ----- src/Fantomas.Tests/Fantomas.Tests.fsproj | 12 +- src/Fantomas.Tests/FormatCommandTests.fs | 59 +++++ .../Integration/ByteOrderMarkTests.fs | 79 ------- src/Fantomas.Tests/Integration/CheckTests.fs | 148 ------------ .../Integration/ExitCodeTests.fs | 36 --- src/Fantomas.Tests/Integration/ForceTests.fs | 31 --- .../Integration/HelpPageTests.fs | 40 +--- .../Integration/IgnoreFilesTests.fs | 136 ----------- .../Integration/MultiplePathsTests.fs | 61 ----- .../Integration/ReportedPathTests.fs | 83 ------- src/Fantomas.Tests/Integration/SmokeTests.fs | 105 +++++++++ src/Fantomas.Tests/Integration/WriteTests.fs | 218 ------------------ src/Fantomas.Tests/TestHelpers.fs | 13 +- src/Fantomas.Tests/packages.lock.json | 6 + 19 files changed, 382 insertions(+), 915 deletions(-) create mode 100644 src/Fantomas.Tests/CheckCommandTests.fs delete mode 100644 src/Fantomas.Tests/CheckTests.fs delete mode 100644 src/Fantomas.Tests/Integration/ByteOrderMarkTests.fs delete mode 100644 src/Fantomas.Tests/Integration/CheckTests.fs delete mode 100644 src/Fantomas.Tests/Integration/ExitCodeTests.fs delete mode 100644 src/Fantomas.Tests/Integration/ForceTests.fs delete mode 100644 src/Fantomas.Tests/Integration/IgnoreFilesTests.fs delete mode 100644 src/Fantomas.Tests/Integration/MultiplePathsTests.fs delete mode 100644 src/Fantomas.Tests/Integration/ReportedPathTests.fs create mode 100644 src/Fantomas.Tests/Integration/SmokeTests.fs delete mode 100644 src/Fantomas.Tests/Integration/WriteTests.fs diff --git a/build.fsx b/build.fsx index 5a7a26b2a4..910a3ead21 100755 --- a/build.fsx +++ b/build.fsx @@ -29,8 +29,26 @@ 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 +126,51 @@ 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, and whichever shipped assembly it touches is measured, +// so the merged report says what the whole suite reaches rather than what one project does. // -// 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. +// 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/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/CheckCommandTests.fs b/src/Fantomas.Tests/CheckCommandTests.fs new file mode 100644 index 0000000000..23f3bdc209 --- /dev/null +++ b/src/Fantomas.Tests/CheckCommandTests.fs @@ -0,0 +1,136 @@ +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 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 ``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 ba2797f098..0000000000 --- a/src/Fantomas.Tests/CheckTests.fs +++ /dev/null @@ -1,59 +0,0 @@ -module Fantomas.Core.Tests.CheckTests - -open NUnit.Framework -open FsUnit -open Fantomas.Tests.TestHelpers -open Fantomas.CheckCommand - -[] -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 = - Seq.singleton fileFixture.Filename - |> checkCode realEnvironment - |> 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 = - Seq.singleton fileFixture.Filename - |> checkCode realEnvironment - |> 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 = - Seq.singleton fileFixture.Filename - |> checkCode realEnvironment - |> 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/Fantomas.Tests.fsproj b/src/Fantomas.Tests/Fantomas.Tests.fsproj index 0e9ab716fc..74177ac991 100644 --- a/src/Fantomas.Tests/Fantomas.Tests.fsproj +++ b/src/Fantomas.Tests/Fantomas.Tests.fsproj @@ -20,23 +20,16 @@ + - - - + - - - - - - @@ -48,5 +41,6 @@ + \ No newline at end of file diff --git a/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs index 89f03d1030..594406ab64 100644 --- a/src/Fantomas.Tests/FormatCommandTests.fs +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -204,6 +204,65 @@ let ``several files and folders are all formatted where they lie`` () = 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 ``an unusable input path never reaches the file system`` () = let fs: IFileSystem = MockFileSystem() 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/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..1eebd65836 --- /dev/null +++ b/src/Fantomas.Tests/Integration/SmokeTests.fs @@ -0,0 +1,105 @@ +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. + +[] +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 |> 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 |> 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 + +// 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/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 9eae26e173..a163a148d9 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -236,18 +236,19 @@ type FantomasToolResult = 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, )", From e26c7f8b73156c6de731522d9529dddeee31d790 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 13:54:35 +0200 Subject: [PATCH 10/17] Fix what reviewing the split turned up Four bugs, three of which predate this branch and one of which it introduced. Each is covered by a test that was checked by putting the bug back. A trailing separator made two spellings of one folder compare as different places, so `fantomas src/ --out src` planned no work at all: every file below the input was taken for a previous run's output and skipped, leaving an empty table and exit 0. isSamePath now trims the separator before comparing. An extension was matched with case, so `A.FS` was refused as an unsupported file type and skipped when found in a folder. On a volume that ignores case, which is the usual one on macOS and Windows, that is a refusal to format a file the compiler builds. Given several input paths, which of them were folders was guessed from whether they carried an extension rather than asked of the file system, though every path had already been shown to exist. A folder named `my.stuff` was taken for a file and failed to format; a file with no extension was taken for a folder. Asking is both correct and shorter than the continuation-passing walk it replaces. Introduced by this branch: reading `.fantomasignore` moved up into main when the file system was passed in, which left it outside every handler. A pattern the ignore library cannot compile ended the process with a stack trace where it used to report a message and exit 1. Building the environment now happens under the same guard the commands run under. Give runCheckCommand the failure case runFormatCommand already had, so a check that cannot read a file exits 1 as its help text promises rather than throwing. Also drop a duplicated open in Report and a doc comment left pointing at nothing in Logging.fsi after the functions above it were removed. --- src/Fantomas.Tests/ArgumentsTests.fs | 23 +++++++++ src/Fantomas.Tests/Integration/SmokeTests.fs | 13 ++++++ src/Fantomas.Tests/PathsTests.fs | 14 ++++++ src/Fantomas.Tests/PlanTests.fs | 12 +++++ src/Fantomas.Tests/ReportTests.fs | 8 ++++ src/Fantomas/Arguments.fs | 23 +++------ src/Fantomas/CheckCommand.fs | 41 ++++++++-------- src/Fantomas/CommandResult.fs | 1 + src/Fantomas/CommandResult.fsi | 2 + src/Fantomas/Logging.fsi | 2 +- src/Fantomas/Paths.fs | 13 +++++- src/Fantomas/Program.fs | 49 +++++++++++--------- src/Fantomas/Report.fs | 5 +- 13 files changed, 144 insertions(+), 62 deletions(-) diff --git a/src/Fantomas.Tests/ArgumentsTests.fs b/src/Fantomas.Tests/ArgumentsTests.fs index 929cfb0781..b9d8fda427 100644 --- a/src/Fantomas.Tests/ArgumentsTests.fs +++ b/src/Fantomas.Tests/ArgumentsTests.fs @@ -56,6 +56,29 @@ let ``several paths are told apart by whether they carry an extension`` () = 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() diff --git a/src/Fantomas.Tests/Integration/SmokeTests.fs b/src/Fantomas.Tests/Integration/SmokeTests.fs index 1eebd65836..27740bc1d1 100644 --- a/src/Fantomas.Tests/Integration/SmokeTests.fs +++ b/src/Fantomas.Tests/Integration/SmokeTests.fs @@ -91,6 +91,19 @@ let ``a byte order mark survives a round trip through a real file`` () = 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. [] diff --git a/src/Fantomas.Tests/PathsTests.fs b/src/Fantomas.Tests/PathsTests.fs index 61cb57c132..0585053a8a 100644 --- a/src/Fantomas.Tests/PathsTests.fs +++ b/src/Fantomas.Tests/PathsTests.fs @@ -18,6 +18,12 @@ 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 + [] [] [] @@ -118,6 +124,14 @@ let ``two spellings of the same location are the same path`` () = 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() diff --git a/src/Fantomas.Tests/PlanTests.fs b/src/Fantomas.Tests/PlanTests.fs index be8c1834f7..65e239b383 100644 --- a/src/Fantomas.Tests/PlanTests.fs +++ b/src/Fantomas.Tests/PlanTests.fs @@ -127,6 +127,18 @@ let ``an input folder that is also the output folder is formatted in place`` () 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() diff --git a/src/Fantomas.Tests/ReportTests.fs b/src/Fantomas.Tests/ReportTests.fs index 8910470097..76aeed7e18 100644 --- a/src/Fantomas.Tests/ReportTests.fs +++ b/src/Fantomas.Tests/ReportTests.fs @@ -177,6 +177,14 @@ let ``a check of an unusable input path exits 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 = diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs index d3f1664036..cae53de4ec 100644 --- a/src/Fantomas/Arguments.fs +++ b/src/Fantomas/Arguments.fs @@ -68,24 +68,13 @@ let classifyInputPath (fs: IFileSystem) (maybeInput: string list option) : Input match missing with | Some x -> InputPath.NotFound x | None -> - let isFolder (path: string) = - String.IsNullOrWhiteSpace(fs.Path.GetExtension(path)) + // 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) - 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) - - InputPath.Multiple(loop inputs id) + InputPath.Multiple(files, folders) | None -> InputPath.Unspecified let parseVerbosity (value: string option) : VerbosityLevel option = diff --git a/src/Fantomas/CheckCommand.fs b/src/Fantomas/CheckCommand.fs index ad74ac1441..d5905db228 100644 --- a/src/Fantomas/CheckCommand.fs +++ b/src/Fantomas/CheckCommand.fs @@ -42,22 +42,25 @@ let checkCode (env: CliEnvironment) (filenames: string seq) : Async } let runCheckCommand (env: CliEnvironment) (inputPath: InputPath) : CheckCommandResult = - // 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)) + 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/CommandResult.fs b/src/Fantomas/CommandResult.fs index 8c37478421..4bbdb87853 100644 --- a/src/Fantomas/CommandResult.fs +++ b/src/Fantomas/CommandResult.fs @@ -42,3 +42,4 @@ type FormatCommandResult = 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 index 6b35795089..3e9a045b50 100644 --- a/src/Fantomas/CommandResult.fsi +++ b/src/Fantomas/CommandResult.fsi @@ -52,3 +52,5 @@ type FormatCommandResult = 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/Logging.fsi b/src/Fantomas/Logging.fsi index 68cbbbca4c..257021a24a 100644 --- a/src/Fantomas/Logging.fsi +++ b/src/Fantomas/Logging.fsi @@ -15,5 +15,5 @@ val initLogger: level: VerbosityLevel -> VerbosityLevel /// corrupt the protocol stream and fault the client connection. val initDaemonLogger: level: VerbosityLevel -> VerbosityLevel -/// log a message +/// 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 index 61205dcbc4..21b08a6e39 100644 --- a/src/Fantomas/Paths.fs +++ b/src/Fantomas/Paths.fs @@ -11,8 +11,11 @@ let isInExcludedDir (fullPath: string) : bool = |> Set.map (fun dir -> sprintf "%c%s%c" Path.DirectorySeparatorChar dir Path.DirectorySeparatorChar) |> Set.exists fullPath.Contains +// 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. let isFSharpFile (s: string) : bool = - Set.contains (Path.GetExtension s) extensions + Set.contains (Path.GetExtension(s).ToLowerInvariant()) extensions let findAllFilesRecursively (fs: IFileSystem) (path: string) : string seq = fs.Directory.GetFiles(path, "*.*", SearchOption.AllDirectories) @@ -25,7 +28,13 @@ let ensureParentFolderExists (fs: IFileSystem) (file: string) : unit = fs.Directory.CreateDirectory(folder) |> ignore let isSamePath (fs: IFileSystem) (left: string) (right: string) : bool = - String.Equals(fs.Path.GetFullPath left, fs.Path.GetFullPath right, StringComparison.Ordinal) + // 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 = diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index 29fd4a5bda..548b2c81c8 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -87,24 +87,31 @@ let main argv = daemon.WaitForClose.GetAwaiter().GetResult() 0 else - 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 + // 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 + 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 -> + log.Error $"%s{exn.Message}" + 1 diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index 2dc426de78..cbc84a18c9 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -4,7 +4,6 @@ open System open System.IO.Abstractions open Serilog open Spectre.Console -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 @@ -12,7 +11,6 @@ open Fantomas open Fantomas.Cli open Fantomas.CommandResult open Fantomas.Logging -open Fantomas.CommandResult // 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. @@ -163,6 +161,9 @@ let reportCheckCommand (env: CliEnvironment) (result: CheckCommandResult) : int | 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" From 17ee2f59013e4d453b6d5473b2b711825d043391 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 14:36:41 +0200 Subject: [PATCH 11/17] Restore the ignored-file notice and close the gaps around it A folder run used to note each file it skipped at detailed verbosity. Deciding whether a file is ignored inside Plan meant such a file never reached the code that said so, leaving only the Ignored count in the summary table. The notice is back, in the one place a multi-file run can carry it. An ignore-match failure now keeps the exception as well. Naming the file and the ignore file is what a reader can act on, but reducing the exception to its message dropped the type and the stack trace; those go to Debug. Cover what the tests were quietly not asserting: - That a file is reported by the path it was given rather than by its name alone, across formatted, unchanged, ignored, failed and --check. Every existing assertion used a bare file name, so reducing the path to its file name passed the whole suite. This is what the deleted ReportedPathTests was for, and retiring it left nothing behind. - Ignore patterns naming a nested path and a nested folder, where every other ignore test used a flat one. - --force saying the output was not valid, rather than only writing it. - The debug trail a run leaves: Processing, has been written, was unchanged. - The --profile branch actually running, and staying quiet when not asked for. - The check command over files and folders named together. - Warning and Fatal in CollectedLog, so a level nothing writes today cannot start being written unnoticed. Correct four comments that described code this branch had already changed: Arguments.fsi still documented telling paths apart by their extension, Cli.fsi pointed at a Logging.createLogger that is no longer exported, Program.fs referred to the deleted elog, and the Coverage pipeline header claimed each run instruments three assemblies when it instruments one, which understates Fantomas.Core rather than measuring it wrongly. SmokeTests now names the three process-level files kept alongside it, so "the smoke set" is not read as all that remains. Also a let private in a file with a signature, two duplicated doc comments, and the annotations AGENTS.md asks for on five bindings. --- build.fsx | 8 +- src/Fantomas.Tests/CheckCommandTests.fs | 14 ++++ src/Fantomas.Tests/FormatCommandTests.fs | 79 ++++++++++++++++++++ src/Fantomas.Tests/Integration/SmokeTests.fs | 5 ++ src/Fantomas.Tests/PlanTests.fs | 24 ++++++ src/Fantomas.Tests/ReportTests.fs | 55 ++++++++++++++ src/Fantomas.Tests/TestHelpers.fs | 4 + src/Fantomas/Arguments.fsi | 6 +- src/Fantomas/Cli.fsi | 3 +- src/Fantomas/Daemon.fs | 1 - src/Fantomas/FormatCommand.fs | 11 ++- src/Fantomas/HelpPage.fs | 2 +- src/Fantomas/IgnoreFile.fs | 9 +-- src/Fantomas/Program.fs | 2 +- src/Fantomas/Report.fs | 5 +- 15 files changed, 207 insertions(+), 21 deletions(-) diff --git a/build.fsx b/build.fsx index 910a3ead21..3f1ada5429 100755 --- a/build.fsx +++ b/build.fsx @@ -37,7 +37,6 @@ 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 @@ -127,8 +126,11 @@ pipeline "Benchmark" { } // Line and branch coverage for the three projects Fantomas ships, via AltCover's MSBuild -// integration. Every test project is run, and whichever shipped assembly it touches is measured, -// so the merged report says what the whole suite reaches rather than what one project does. +// 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. +// +// 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 diff --git a/src/Fantomas.Tests/CheckCommandTests.fs b/src/Fantomas.Tests/CheckCommandTests.fs index 23f3bdc209..3b5ad59682 100644 --- a/src/Fantomas.Tests/CheckCommandTests.fs +++ b/src/Fantomas.Tests/CheckCommandTests.fs @@ -95,6 +95,20 @@ let ``every file below a folder is checked`` () = 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() diff --git a/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs index 594406ab64..328ecf165d 100644 --- a/src/Fantomas.Tests/FormatCommandTests.fs +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -32,6 +32,20 @@ let private formatWith 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) @@ -263,6 +277,71 @@ let ``without force, output that is not valid F# is not written`` () = 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 ``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 ``an unusable input path never reaches the file system`` () = let fs: IFileSystem = MockFileSystem() diff --git a/src/Fantomas.Tests/Integration/SmokeTests.fs b/src/Fantomas.Tests/Integration/SmokeTests.fs index 27740bc1d1..b2e4844bcf 100644 --- a/src/Fantomas.Tests/Integration/SmokeTests.fs +++ b/src/Fantomas.Tests/Integration/SmokeTests.fs @@ -13,6 +13,11 @@ open Fantomas.Tests.TestHelpers // 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" diff --git a/src/Fantomas.Tests/PlanTests.fs b/src/Fantomas.Tests/PlanTests.fs index 65e239b383..5ceb2a6d34 100644 --- a/src/Fantomas.Tests/PlanTests.fs +++ b/src/Fantomas.Tests/PlanTests.fs @@ -171,6 +171,30 @@ let ``an ignored file is skipped when found by walking a folder too`` () = 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() diff --git a/src/Fantomas.Tests/ReportTests.fs b/src/Fantomas.Tests/ReportTests.fs index 76aeed7e18..17a26591e8 100644 --- a/src/Fantomas.Tests/ReportTests.fs +++ b/src/Fantomas.Tests/ReportTests.fs @@ -65,6 +65,61 @@ let ``a single formatted file is reported as a sentence naming it`` () = // 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, _ = diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index a163a148d9..20a30df196 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -136,7 +136,9 @@ let silentLogger: ILogger = LoggerConfiguration().CreateLogger() /// `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() = @@ -162,7 +164,9 @@ let collectingLogger () : ILogger * (unit -> CollectedLog) = |> List.map (fun (e: LogEvent) -> e.RenderMessage()) { Information = atLevel LogEventLevel.Information + Warning = atLevel LogEventLevel.Warning Error = atLevel LogEventLevel.Error + Fatal = atLevel LogEventLevel.Fatal Debug = atLevel LogEventLevel.Debug } logger, collected diff --git a/src/Fantomas/Arguments.fsi b/src/Fantomas/Arguments.fsi index cebd38bc4a..da98292abf 100644 --- a/src/Fantomas/Arguments.fsi +++ b/src/Fantomas/Arguments.fsi @@ -33,9 +33,9 @@ type OutputPath = | IO of string | NotKnown -/// Decide what the paths on the command line name. A single path is classified by asking the -/// file system about it. Several paths are all required to exist first, and are then told apart -/// by whether they carry a file extension, so `src` is taken as a folder and `src.fs` as a file. +/// 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. diff --git a/src/Fantomas/Cli.fsi b/src/Fantomas/Cli.fsi index 1868312500..8a902a32e2 100644 --- a/src/Fantomas/Cli.fsi +++ b/src/Fantomas/Cli.fsi @@ -20,7 +20,8 @@ type CliEnvironment = /// 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 settled by `Logging.createLogger`. + /// 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 diff --git a/src/Fantomas/Daemon.fs b/src/Fantomas/Daemon.fs index b68160f845..3e29e1f971 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -43,7 +43,6 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme traceListener.Dispose() disconnectEvent.Dispose() - /// returns a hot task that resolves when the stream has terminated member this.WaitForClose = rpc.Completion [] diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index d8518d1501..a391162b23 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -19,13 +19,16 @@ type FormatParams = Profile: bool File: string } - static member Create(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 } -let private carriageReturn = Text.RegularExpressions.Regex(@"\r") +let carriageReturn: Text.RegularExpressions.Regex = + Text.RegularExpressions.Regex(@"\r") let formatContentAsync (formatParams: FormatParams) (originalContent: string) : Async = async { @@ -61,7 +64,7 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : let contentChanged: bool = if formatParams.CompareWithoutLineEndings then - let stripNewlines (s: string) = carriageReturn.Replace(s, String.Empty) + let stripNewlines (s: string) : string = carriageReturn.Replace(s, String.Empty) (stripNewlines originalContent) <> (stripNewlines formattedContent) else @@ -109,7 +112,7 @@ let processSourceString let fs: IFileSystem = env.FileSystem let force: bool = settings.Force - let writeResult (formatted: string) = + let writeResult (formatted: string) : Async = async { let! hasBom = hasByteOrderMark fs fileName diff --git a/src/Fantomas/HelpPage.fs b/src/Fantomas/HelpPage.fs index 42732dce30..4c11ca9528 100644 --- a/src/Fantomas/HelpPage.fs +++ b/src/Fantomas/HelpPage.fs @@ -148,7 +148,7 @@ let writeFlag List.iter (writeContinuation write descriptionColumn) rest let writeExample (write: string -> unit) (palette: Palette) (command: string, description: string) : unit = - let name, arguments = + let name, arguments: string * string = match command.IndexOf ' ' with | -1 -> command, "" | i -> command.Substring(0, i), command.Substring(i) diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index e3662a5974..f40407f52f 100644 --- a/src/Fantomas/IgnoreFile.fs +++ b/src/Fantomas/IgnoreFile.fs @@ -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 @@ -94,4 +88,7 @@ module IgnoreFile = 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/Program.fs b/src/Fantomas/Program.fs index 548b2c81c8..bc5b23cde9 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -42,7 +42,7 @@ let main argv = match parseVerbosity (results.TryGetResult <@ Arguments.Verbosity @>) with | Some level -> level | None -> - // The logger is not up yet, so this cannot go through elog. + // The logger is not configured yet, so this cannot go through it. eprintfn "Invalid verbosity level" exit 1 diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index cbc84a18c9..5620bdca22 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -104,7 +104,7 @@ let reportFormatResults (env: CliEnvironment) (settings: CliSettings) (results: | None -> let oks, ignored, unchanged, errored = partitionResults results - let centeredColumn (v: string) = TableColumn(v).Centered() + let centeredColumn (v: string) : TableColumn = TableColumn(v).Centered() let summary: Table = Table() @@ -123,6 +123,9 @@ let reportFormatResults (env: CliEnvironment) (settings: CliSettings) (results: 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 From 06bc80faa8b83525e45cddcf5e5b71d12bc16e8e Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 15:07:56 +0200 Subject: [PATCH 12/17] Read each file once, and only read one to describe a parse failure Formatting a file read it twice: once for its text, and again for the first three bytes, to find out whether it carried a byte order mark. The mark is in the same bytes the text is decoded from, and StreamReader has already looked at them to settle on an encoding, so it can be asked instead. readSourceFile now returns the text and the mark together from one read. That removes the reason processSourceString and processSourceFile were two functions. They held two copies of the same decision about --force and about output that is not valid F#, one writing to a file and one to a TextWriter that existed only to be buffered into a file afterwards. What is left is formatSource, which settles what a format run came to, and processFile, which reads once, decides once and writes at most once. The buffer and the TextWriter are gone, and the rule that the output is never opened before the input has been read now holds because there is nothing to open it with rather than because a buffer arranged it. describeParseFailure took the source eagerly but only uses it when the error turns out to be a parse failure, so a run that failed for any other reason read the whole file for nothing. It now takes a function, and the signature says when it is called. Three costs on the per-file paths were work that does not change between files: - isInExcludedDir built a set, formatted four fragments and built a second set, for every file walked. Computed once, and now covering both separators. - The closure loadIgnoreList returns asked the file system for the ignore file's parent directory on every call. Resolved once, when the list is loaded. - isFSharpFile lowercased a copy of every extension handed to it. A set that ignores case does the same without allocating. Discovery over 45,000 files, 15,000 of them F# and all ignored so nothing is formatted, goes from 0.30s to 0.27s. Against roughly 10ms to format a file that is a fraction of a percent of a real run, and the single read is below the noise of timing one at all. Neither is a reason on its own; the code being smaller is. One change to what is printed: the --out path now notes an unchanged file at detailed verbosity, which only formatting in place used to do. Both paths share formatSource now, and agreeing is better than the split. --- src/Fantomas.Tests/DiagnosticsTests.fs | 2 +- src/Fantomas/Daemon.fs | 4 +- src/Fantomas/Diagnostics.fs | 4 +- src/Fantomas/Diagnostics.fsi | 8 +- src/Fantomas/FormatCommand.fs | 184 ++++++++++--------------- src/Fantomas/IgnoreFile.fs | 8 +- src/Fantomas/Paths.fs | 31 ++++- src/Fantomas/Report.fs | 4 +- 8 files changed, 114 insertions(+), 131 deletions(-) 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/Daemon.fs b/src/Fantomas/Daemon.fs index 3e29e1f971..1c110db0ac 100644 --- a/src/Fantomas/Daemon.fs +++ b/src/Fantomas/Daemon.fs @@ -94,7 +94,7 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme // 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) @@ -133,7 +133,7 @@ type FantomasDaemon(sender: Stream, reader: Stream, environment: DaemonEnvironme 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/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/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index a391162b23..f2046e576d 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -88,144 +88,104 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : return FormatResult.Error(formatParams.File, ex) } -let hasByteOrderMark (fs: IFileSystem) (file: string) : Async = +/// 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 { - if fs.File.Exists(file) then - let preamble: byte array = Encoding.UTF8.GetPreamble() + use stream = fs.File.OpenRead file - use stream = fs.File.OpenRead(file) + use reader = + new StreamReader(stream, UTF8Encoding(false), detectEncodingFromByteOrderMarks = true) - let mutable bom: byte array = Array.zeroCreate 3 - do! stream.ReadAsync(bom, 0, 3) |> Async.AwaitTask |> Async.Ignore - return bom = preamble - else - return false - } - -let processSourceString - (env: CliEnvironment) - (settings: CliSettings) - (s: string) - (fileName: string) - (config: FormatConfig) - : Async = - let fs: IFileSystem = env.FileSystem - let force: bool = settings.Force - - let writeResult (formatted: string) : Async = - async { - let! hasBom = hasByteOrderMark fs fileName - - if hasBom then - do! fs.File.WriteAllTextAsync(fileName, formatted, Encoding.UTF8) |> Async.AwaitTask - else - do! fs.File.WriteAllTextAsync(fileName, formatted) |> Async.AwaitTask - - env.Log.Debug $"%s{fileName} has been written." - } - - async { - let formatParams: FormatParams = - FormatParams.Create(config, false, settings.Profile, fileName) + let! content = reader.ReadToEndAsync() |> Async.AwaitTask - let! formatted = formatContentAsync formatParams s + // 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 - match formatted with - | FormatResult.Formatted(_, formattedContent, _) as r -> - do! formattedContent |> writeResult - return r - | FormatResult.InvalidCode(file, formattedContent) when force -> - env.Log.Information $"%s{file} was not valid after formatting." - do! formattedContent |> writeResult - return FormatResult.Formatted(fileName, formattedContent, None) - | FormatResult.Unchanged(file, _) as r -> - env.Log.Debug $"'%s{file}' was unchanged" - return r - | FormatResult.IgnoredFile _ as r -> return r - | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> return FormatResult.Error(file, invalidResultException file) + return + { Content = content + HasByteOrderMark = encoding.CodePage = Encoding.UTF8.CodePage && encoding.GetPreamble().Length > 0 } } -let processSourceFile +/// 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) - (inFile: string) - (tw: TextWriter) + (source: SourceFile) + (file: string) + (config: FormatConfig) : Async = - let force: bool = settings.Force - async { - let! originalContent = env.FileSystem.File.ReadAllTextAsync inFile |> Async.AwaitTask - let formatParams: FormatParams = - FormatParams.Create(env.ReadConfiguration inFile, false, settings.Profile, inFile) + FormatParams.Create(config, false, settings.Profile, file) - let! formatted = formatContentAsync formatParams originalContent + let! formatted = formatContentAsync formatParams source.Content match formatted with - | FormatResult.Formatted(_, formattedContent, _) as r -> - do! tw.WriteAsync(formattedContent) |> Async.AwaitTask - return r - | FormatResult.InvalidCode(file, formattedContent) when force -> - env.Log.Information $"%s{file} was not valid after formatting." - do! tw.WriteAsync(formattedContent) |> Async.AwaitTask - return FormatResult.Formatted(inFile, formattedContent, None) - | FormatResult.Unchanged _ as r -> - // The content is already in hand, so an unchanged file is copied across from it - // rather than read a second time. - do! originalContent |> tw.WriteAsync |> Async.AwaitTask + | 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 - | FormatResult.IgnoredFile _ as r -> return r - | FormatResult.Error _ as r -> return r - | FormatResult.InvalidCode(file, _) -> return FormatResult.Error(file, invalidResultException file) - } - -// 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 (env: CliEnvironment) (settings: CliSettings) (inFile: string) (outFile: string) : Async = - let fs: IFileSystem = env.FileSystem - - async { - env.Log.Debug $"Processing %s{inFile}" - use buffer = new StringWriter() - let! processResult = processSourceFile env settings inFile buffer - - match processResult with - | FormatResult.Formatted _ - | FormatResult.Unchanged _ -> - let! hasByteOrderMark = hasByteOrderMark fs inFile - ensureParentFolderExists fs outFile - let contents: string = buffer.ToString() - - if hasByteOrderMark then - do! fs.File.WriteAllTextAsync(outFile, contents, Encoding.UTF8) |> Async.AwaitTask - else - do! fs.File.WriteAllTextAsync(outFile, contents) |> Async.AwaitTask - - env.Log.Debug $"%s{outFile} has been written." - | FormatResult.IgnoredFile _ - | FormatResult.InvalidCode _ - | FormatResult.Error _ -> () - - return processResult + | 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 - if not (isSamePath env.FileSystem inputFile outputFile) then - return! fileToFile env settings inputFile outputFile - else - env.Log.Debug $"Processing %s{inputFile}" - let! content = env.FileSystem.File.ReadAllTextAsync inputFile |> Async.AwaitTask - return! processSourceString env settings content inputFile (env.ReadConfiguration inputFile) + env.Log.Debug $"Processing %s{inputFile}" + let! source = readSourceFile fs inputFile + let inPlace: bool = isSamePath fs inputFile outputFile + let! result = 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) } diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index f40407f52f..4461fc2635 100644 --- a/src/Fantomas/IgnoreFile.fs +++ b/src/Fantomas/IgnoreFile.fs @@ -52,15 +52,17 @@ module IgnoreFile = (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("\\", "/") + fs.Path.GetRelativePath(ignoreRoot, absoluteFilePath.Path).Replace("\\", "/") fantomasIgnore.IsIgnored(relativePath) diff --git a/src/Fantomas/Paths.fs b/src/Fantomas/Paths.fs index 21b08a6e39..b70fadb683 100644 --- a/src/Fantomas/Paths.fs +++ b/src/Fantomas/Paths.fs @@ -1,21 +1,38 @@ 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" |] -let isInExcludedDir (fullPath: string) : bool = - set [| "obj"; ".fable"; "fable_modules"; "node_modules" |] - |> Set.map (fun dir -> sprintf "%c%s%c" Path.DirectorySeparatorChar dir Path.DirectorySeparatorChar) - |> Set.exists fullPath.Contains - // 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. +// 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. Both separators are covered, since a path can reach us spelled either way. +let excludedDirFragments: string array = + let separators: char array = + if Path.DirectorySeparatorChar = Path.AltDirectorySeparatorChar then + [| Path.DirectorySeparatorChar |] + else + [| Path.DirectorySeparatorChar; Path.AltDirectorySeparatorChar |] + + [| for dir in [| "obj"; ".fable"; "fable_modules"; "node_modules" |] do + for separator in separators -> String.Concat(string separator, dir, string separator) |] + +let isInExcludedDir (fullPath: string) : bool = + excludedDirFragments + |> Array.exists (fun (fragment: string) -> fullPath.Contains(fragment, StringComparison.Ordinal)) + let isFSharpFile (s: string) : bool = - Set.contains (Path.GetExtension(s).ToLowerInvariant()) extensions + extensionLookup.Contains(Path.GetExtension s) let findAllFilesRecursively (fs: IFileSystem) (path: string) : string seq = fs.Directory.GetFiles(path, "*.*", SearchOption.AllDirectories) diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index 5620bdca22..9a37015328 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -58,7 +58,7 @@ let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, // 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 env.FileSystem file) exn with + match Diagnostics.describeParseFailure file (fun () -> sourceOf env.FileSystem file) exn with | Some parseFailure -> env.Log.Error parseFailure | None -> env.Log.Error(describeOther ()) @@ -135,7 +135,7 @@ let reportFormatResults (env: CliEnvironment) (settings: CliSettings) (results: let reportCheckResults (env: CliEnvironment) (checkResult: CheckResult) : unit = for filename, exn in checkResult.Errors do - match Diagnostics.describeParseFailure filename (sourceOf env.FileSystem filename) exn with + 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()}" From 79df815aa252595ae6461601eda16e430027dafd Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 15:14:18 +0200 Subject: [PATCH 13/17] Add changelog and upgrade guide --- CHANGELOG.md | 7 +++++++ docs/docs/end-users/UpgradeGuide.md | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 298674913f..79b944ca17 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,10 @@ - `--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) ## [8.0.0-alpha-014] - 2026-08-20 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 From 091c45058e05f0f1ae9da2cac3cce70eda2ab33d Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 15:29:42 +0200 Subject: [PATCH 14/17] Fix the Windows build and the analyzer warnings it raised Five tests failed on Windows and none of them on Linux or macOS, because four assumed line feeds and the fifth found a bug. --profile counted occurrences of the platform's newline in the source to arrive at a line count, so a file saved with line feeds counted zero lines on Windows, and one saved with carriage returns counted zero everywhere else. It counts line breaks now, and a test pins both spellings against the same answer. The environment a mock-based test runs in pins end_of_line to lf, so what such a test formats no longer depends on the platform running it. That is what its stub configuration is for. The two smoke tests that drive the real tool normalise the newlines instead, since there the platform's choice is the point. The analyzer findings GitHub raised are addressed: annotate the three uses of the string function, replace a List.filter followed by List.map with List.choose, and mark Palette, OutputPath and InputProblem as struct unions. Those four sat in Fantomas.Tests, which the Analyze pipeline had been reporting all along. They were missed because the runs were read through a filter matching src/Fantomas/, which does not match src/Fantomas.Tests/. The pipeline writes analysis.sarif and exits 0 whatever it finds, so a passing run said nothing about whether there were findings to read. --- CHANGELOG.md | 1 + src/Fantomas.Tests/FormatCommandTests.fs | 19 +++++++++++++++++++ src/Fantomas.Tests/Integration/SmokeTests.fs | 10 ++++++++-- src/Fantomas.Tests/PathsTests.fs | 4 ++-- src/Fantomas.Tests/PlanTests.fs | 2 +- src/Fantomas.Tests/TestHelpers.fs | 8 +++++--- src/Fantomas/Arguments.fs | 2 +- src/Fantomas/Arguments.fsi | 2 +- src/Fantomas/CommandResult.fs | 2 +- src/Fantomas/CommandResult.fsi | 2 +- src/Fantomas/FormatCommand.fs | 5 +++-- src/Fantomas/HelpPage.fs | 2 +- src/Fantomas/HelpPage.fsi | 2 +- 13 files changed, 45 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79b944ca17..dc75063419 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ - 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/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs index 328ecf165d..4c89fa0e29 100644 --- a/src/Fantomas.Tests/FormatCommandTests.fs +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -332,6 +332,25 @@ let ``profiling collects a line count and a time for the file it formatted`` () | [| 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() diff --git a/src/Fantomas.Tests/Integration/SmokeTests.fs b/src/Fantomas.Tests/Integration/SmokeTests.fs index b2e4844bcf..42b1108aa5 100644 --- a/src/Fantomas.Tests/Integration/SmokeTests.fs +++ b/src/Fantomas.Tests/Integration/SmokeTests.fs @@ -37,7 +37,10 @@ let ``a file named on the command line is formatted where it lies`` () = exitCode |> should equal 0 output |> should contain "was formatted" - File.ReadAllText fileFixture.Filename |> should equal "let a = 1\n" + + 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`` () = @@ -49,7 +52,10 @@ let ``an out path is written to and the input is left alone`` () = exitCode |> should equal 0 File.ReadAllText inputFixture.Filename |> should equal NeedsFormatting - File.ReadAllText outputFixture.Filename |> should equal "let a = 1\n" + + 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. [] diff --git a/src/Fantomas.Tests/PathsTests.fs b/src/Fantomas.Tests/PathsTests.fs index 0585053a8a..11125f34fb 100644 --- a/src/Fantomas.Tests/PathsTests.fs +++ b/src/Fantomas.Tests/PathsTests.fs @@ -129,8 +129,8 @@ 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 + 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`` () = diff --git a/src/Fantomas.Tests/PlanTests.fs b/src/Fantomas.Tests/PlanTests.fs index 5ceb2a6d34..6e596004a8 100644 --- a/src/Fantomas.Tests/PlanTests.fs +++ b/src/Fantomas.Tests/PlanTests.fs @@ -136,7 +136,7 @@ let ``a folder spelled with a trailing separator is still formatted in place`` ( // `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) + planOn fs (InputPath.Folder(src + string fs.Path.DirectorySeparatorChar)) (OutputPath.IO src) |> shouldPlan [ WorkItem.Format(a, a) ] [] diff --git a/src/Fantomas.Tests/TestHelpers.fs b/src/Fantomas.Tests/TestHelpers.fs index 20a30df196..918b53e813 100644 --- a/src/Fantomas.Tests/TestHelpers.fs +++ b/src/Fantomas.Tests/TestHelpers.fs @@ -160,8 +160,7 @@ let collectingLogger () : ILogger * (unit -> CollectedLog) = let collected () : CollectedLog = let atLevel (level: LogEventLevel) : string list = sink.Events - |> List.filter (fun (e: LogEvent) -> e.Level = level) - |> List.map (fun (e: LogEvent) -> e.RenderMessage()) + |> List.choose (fun (e: LogEvent) -> if e.Level = level then Some(e.RenderMessage()) else None) { Information = atLevel LogEventLevel.Information Warning = atLevel LogEventLevel.Warning @@ -208,7 +207,10 @@ let recordingEnvironment (fs: IFileSystem) (ignoreFile: IgnoreFile option) : Rec { Environment = { FileSystem = fs IgnoreFile = ignoreFile - ReadConfiguration = fun _ -> FormatConfig.Default + ReadConfiguration = + fun _ -> + { FormatConfig.Default with + EndOfLine = EndOfLineStyle.LF } Log = logger Console = console } Log = collected diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs index cae53de4ec..e303cd3220 100644 --- a/src/Fantomas/Arguments.fs +++ b/src/Fantomas/Arguments.fs @@ -44,7 +44,7 @@ type InputPath = | NotFound of string | Unspecified -[] +[] type OutputPath = | IO of string | NotKnown diff --git a/src/Fantomas/Arguments.fsi b/src/Fantomas/Arguments.fsi index da98292abf..1f3e6f7d5c 100644 --- a/src/Fantomas/Arguments.fsi +++ b/src/Fantomas/Arguments.fsi @@ -28,7 +28,7 @@ type InputPath = | Unspecified /// Where the result should be written, which is back over the input unless `--out` said otherwise. -[] +[] type OutputPath = | IO of string | NotKnown diff --git a/src/Fantomas/CommandResult.fs b/src/Fantomas/CommandResult.fs index 4bbdb87853..9d040ed2a3 100644 --- a/src/Fantomas/CommandResult.fs +++ b/src/Fantomas/CommandResult.fs @@ -25,7 +25,7 @@ type CheckResult = let invalidResultException (file: string) : FormatException = FormatException($"Formatting %s{file} leads to invalid F# code") -[] +[] type InputProblem = | UnsupportedFileType of path: string | NotFound of path: string diff --git a/src/Fantomas/CommandResult.fsi b/src/Fantomas/CommandResult.fsi index 3e9a045b50..89550d086a 100644 --- a/src/Fantomas/CommandResult.fsi +++ b/src/Fantomas/CommandResult.fsi @@ -30,7 +30,7 @@ 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 diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index f2046e576d..87eb958ee4 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -45,8 +45,9 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : sw.Stop() - let count: int = - originalContent.Length - originalContent.Replace(Environment.NewLine, "").Length + // 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 diff --git a/src/Fantomas/HelpPage.fs b/src/Fantomas/HelpPage.fs index 4c11ca9528..b5fa8648b9 100644 --- a/src/Fantomas/HelpPage.fs +++ b/src/Fantomas/HelpPage.fs @@ -6,7 +6,7 @@ open Argu open Spectre.Console open Fantomas.Core -[] +[] type Palette = | NoColour | FourBit diff --git a/src/Fantomas/HelpPage.fsi b/src/Fantomas/HelpPage.fsi index cb14a1231a..315c2804b3 100644 --- a/src/Fantomas/HelpPage.fsi +++ b/src/Fantomas/HelpPage.fsi @@ -1,7 +1,7 @@ module Fantomas.HelpPage /// How much colour the page may use. -[] +[] type Palette = | NoColour | FourBit From 56c158a4a5ee1afb4a2f240e21bdba33a3399998 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 15:30:21 +0200 Subject: [PATCH 15/17] Read sarif --- AGENTS.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index b575e4a03b..21c77c9009 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,3 +75,11 @@ dotnet fsi build.fsx -- -p Analyze 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. From d169d00786ba48680c1f5873fda01028ae95155d Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 15:38:31 +0200 Subject: [PATCH 16/17] Remove Program signature file --- src/Fantomas/Fantomas.fsproj | 1 - src/Fantomas/Program.fs | 3 +++ src/Fantomas/Program.fsi | 6 ------ 3 files changed, 3 insertions(+), 7 deletions(-) delete mode 100644 src/Fantomas/Program.fsi diff --git a/src/Fantomas/Fantomas.fsproj b/src/Fantomas/Fantomas.fsproj index 73dccbae97..7189b17892 100644 --- a/src/Fantomas/Fantomas.fsproj +++ b/src/Fantomas/Fantomas.fsproj @@ -49,7 +49,6 @@ - diff --git a/src/Fantomas/Program.fs b/src/Fantomas/Program.fs index bc5b23cde9..6c12838553 100644 --- a/src/Fantomas/Program.fs +++ b/src/Fantomas/Program.fs @@ -15,6 +15,9 @@ open Argu open Serilog open Spectre.Console +/// 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 diff --git a/src/Fantomas/Program.fsi b/src/Fantomas/Program.fsi deleted file mode 100644 index 8b3157e287..0000000000 --- a/src/Fantomas/Program.fsi +++ /dev/null @@ -1,6 +0,0 @@ -module Program - -/// 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. -val main: argv: string array -> int From 73d18590b941bddb1f4371da467d64c56cd951bd Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 22 Aug 2026 16:05:21 +0200 Subject: [PATCH 17/17] Tidy what a second review of the branch turned up Two changes are more than tidying. isInExcludedDir matched the alternate directory separator as well as the platform one, which quietly widened what a folder walk skips on Windows. It also could never fire: the paths it sees come from Directory.GetFiles, which uses the platform separator, and the two characters are the same on Unix. Gone, so this matches what it did before the split. CheckCommand.checkCode no longer filters ignored files, because Plan settles that before anything reaches it, but it is exported and its signature said nothing about the arrangement. It does now. Cover three things nothing exercised: an unsupported file type through both commands, no input path at all through the format command, and writing over content already at the output path when the input carries a byte order mark. The last was covered before Integration/ByteOrderMarkTests.fs was retired and its replacement dropped the mark. Use exn rather than Exception. The two are the same type and the codebase used both; exn is the abbreviation F# offers, as string is for System.String. The parameter of reportError was itself named exn, which shadowed the abbreviation it was annotated with, and is now error. Annotate the let! bindings, HelpPage's three data lists and loadIgnoreList's locals, per the rule in AGENTS.md. The let! ones need parentheses: annotating one without them is recent syntax that the Fantomas the repository formats with does not parse, so the compiler accepted what dotnet fantomas could not read. Also: drop an unused open, say why carriageReturn is built at module level, fix a test name still describing the extension guessing this branch removed, replace a List.last that would throw rather than fail an assertion, and give four test helpers their return types. --- src/Fantomas.Tests/ArgumentsTests.fs | 2 +- src/Fantomas.Tests/CheckCommandTests.fs | 5 ++++ src/Fantomas.Tests/FormatCommandTests.fs | 32 ++++++++++++++++++++++++ src/Fantomas.Tests/PlanTests.fs | 13 ++++++++-- src/Fantomas.Tests/ReportTests.fs | 11 +++++--- src/Fantomas/Arguments.fs | 1 - src/Fantomas/CheckCommand.fs | 2 +- src/Fantomas/CheckCommand.fsi | 1 + src/Fantomas/CommandResult.fs | 2 +- src/Fantomas/CommandResult.fsi | 2 +- src/Fantomas/FormatCommand.fs | 11 ++++---- src/Fantomas/HelpPage.fs | 6 ++--- src/Fantomas/IgnoreFile.fs | 6 ++--- src/Fantomas/Paths.fs | 12 +++------ src/Fantomas/Report.fs | 12 ++++----- 15 files changed, 82 insertions(+), 36 deletions(-) diff --git a/src/Fantomas.Tests/ArgumentsTests.fs b/src/Fantomas.Tests/ArgumentsTests.fs index b9d8fda427..0dbdd40d39 100644 --- a/src/Fantomas.Tests/ArgumentsTests.fs +++ b/src/Fantomas.Tests/ArgumentsTests.fs @@ -46,7 +46,7 @@ let ``an existing file Fantomas does not format is reported as such`` () = |> shouldEqual (InputPath.NoFSharpFile file) [] -let ``several paths are told apart by whether they carry an extension`` () = +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") diff --git a/src/Fantomas.Tests/CheckCommandTests.fs b/src/Fantomas.Tests/CheckCommandTests.fs index 3b5ad59682..53f4bc1840 100644 --- a/src/Fantomas.Tests/CheckCommandTests.fs +++ b/src/Fantomas.Tests/CheckCommandTests.fs @@ -39,6 +39,11 @@ 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() diff --git a/src/Fantomas.Tests/FormatCommandTests.fs b/src/Fantomas.Tests/FormatCommandTests.fs index 4c89fa0e29..9e628addc2 100644 --- a/src/Fantomas.Tests/FormatCommandTests.fs +++ b/src/Fantomas.Tests/FormatCommandTests.fs @@ -184,6 +184,28 @@ let ``a byte order mark the input carried is put back on the 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() @@ -361,6 +383,16 @@ let ``nothing is profiled unless profiling was asked for`` () = | [| 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() diff --git a/src/Fantomas.Tests/PlanTests.fs b/src/Fantomas.Tests/PlanTests.fs index 6e596004a8..bee8f3f308 100644 --- a/src/Fantomas.Tests/PlanTests.fs +++ b/src/Fantomas.Tests/PlanTests.fs @@ -11,11 +11,20 @@ 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) = +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) = +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) diff --git a/src/Fantomas.Tests/ReportTests.fs b/src/Fantomas.Tests/ReportTests.fs index 17a26591e8..31b07e2a6e 100644 --- a/src/Fantomas.Tests/ReportTests.fs +++ b/src/Fantomas.Tests/ReportTests.fs @@ -13,12 +13,15 @@ open Fantomas.Tests.TestHelpers let private run () : RecordedRun = recordingEnvironment (MockFileSystem()) None -let private reportFormat (settings: Fantomas.Cli.CliSettings) (result: FormatCommandResult) = +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) = +let private reportCheck (result: CheckCommandResult) : int * CollectedLog = let recorded: RecordedRun = run () let code: int = reportCheckCommand recorded.Environment result code, recorded.Log() @@ -208,7 +211,9 @@ let ``profiling reports the line count and the time taken for a single file`` () let _, log, _ = reportFormat settings (FormatCommandResult.Completed [| FormatResult.Formatted("A.fs", "", profile) |]) - log.Information |> List.last |> shouldContainText "Line count: 12" + 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`` () = diff --git a/src/Fantomas/Arguments.fs b/src/Fantomas/Arguments.fs index e303cd3220..7c4049d8e7 100644 --- a/src/Fantomas/Arguments.fs +++ b/src/Fantomas/Arguments.fs @@ -1,6 +1,5 @@ module Fantomas.Arguments -open System open System.IO.Abstractions open Argu open Fantomas.Logging diff --git a/src/Fantomas/CheckCommand.fs b/src/Fantomas/CheckCommand.fs index d5905db228..3e015ee3ee 100644 --- a/src/Fantomas/CheckCommand.fs +++ b/src/Fantomas/CheckCommand.fs @@ -12,7 +12,7 @@ let checkCode (env: CliEnvironment) (filenames: string seq) : Async filenames |> Seq.map (fun filename -> async { - let! content = env.FileSystem.File.ReadAllTextAsync filename |> Async.AwaitTask + let! (content: string) = env.FileSystem.File.ReadAllTextAsync filename |> Async.AwaitTask let formatParams: FormatParams = FormatParams.Create(env.ReadConfiguration filename, true, false, filename) diff --git a/src/Fantomas/CheckCommand.fsi b/src/Fantomas/CheckCommand.fsi index 3aa517cbd0..be428439e4 100644 --- a/src/Fantomas/CheckCommand.fsi +++ b/src/Fantomas/CheckCommand.fsi @@ -5,6 +5,7 @@ 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 diff --git a/src/Fantomas/CommandResult.fs b/src/Fantomas/CommandResult.fs index 9d040ed2a3..960ef9ce0c 100644 --- a/src/Fantomas/CommandResult.fs +++ b/src/Fantomas/CommandResult.fs @@ -10,7 +10,7 @@ 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 + | Error of filename: string * formattingError: exn | IgnoredFile of filename: string [] diff --git a/src/Fantomas/CommandResult.fsi b/src/Fantomas/CommandResult.fsi index 89550d086a..4f996600ee 100644 --- a/src/Fantomas/CommandResult.fsi +++ b/src/Fantomas/CommandResult.fsi @@ -10,7 +10,7 @@ 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 + | Error of filename: string * formattingError: exn | IgnoredFile of filename: string [] diff --git a/src/Fantomas/FormatCommand.fs b/src/Fantomas/FormatCommand.fs index 87eb958ee4..6f5a9909d6 100644 --- a/src/Fantomas/FormatCommand.fs +++ b/src/Fantomas/FormatCommand.fs @@ -27,6 +27,7 @@ type FormatParams = 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") @@ -72,7 +73,7 @@ let formatContentAsync (formatParams: FormatParams) (originalContent: string) : originalContent <> formattedContent if contentChanged then - let! isValid = CodeFormatter.IsValidFSharpCodeAsync(isSignatureFile, formattedContent) + let! (isValid: bool) = CodeFormatter.IsValidFSharpCodeAsync(isSignatureFile, formattedContent) if not isValid then return FormatResult.InvalidCode(filename = formatParams.File, formattedContent = formattedContent) @@ -104,7 +105,7 @@ let readSourceFile (fs: IFileSystem) (file: string) : Async = use reader = new StreamReader(stream, UTF8Encoding(false), detectEncodingFromByteOrderMarks = true) - let! content = reader.ReadToEndAsync() |> Async.AwaitTask + 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 @@ -131,7 +132,7 @@ let formatSource let formatParams: FormatParams = FormatParams.Create(config, false, settings.Profile, file) - let! formatted = formatContentAsync formatParams source.Content + let! (formatted: FormatResult) = formatContentAsync formatParams source.Content match formatted with | FormatResult.InvalidCode(f, formattedContent) when settings.Force -> @@ -159,9 +160,9 @@ let processFile async { try env.Log.Debug $"Processing %s{inputFile}" - let! source = readSourceFile fs inputFile + let! (source: SourceFile) = readSourceFile fs inputFile let inPlace: bool = isSamePath fs inputFile outputFile - let! result = formatSource env settings source inputFile (env.ReadConfiguration inputFile) + let! (result: FormatResult) = formatSource env settings source inputFile (env.ReadConfiguration inputFile) let toWrite: string option = match result with diff --git a/src/Fantomas/HelpPage.fs b/src/Fantomas/HelpPage.fs index b5fa8648b9..6c40a071eb 100644 --- a/src/Fantomas/HelpPage.fs +++ b/src/Fantomas/HelpPage.fs @@ -80,7 +80,7 @@ let shortVersion () : string = | [| 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", "", @@ -107,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" ]) diff --git a/src/Fantomas/IgnoreFile.fs b/src/Fantomas/IgnoreFile.fs index 4461fc2635..e046f70abc 100644 --- a/src/Fantomas/IgnoreFile.fs +++ b/src/Fantomas/IgnoreFile.fs @@ -46,9 +46,9 @@ 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)) @@ -61,7 +61,7 @@ module IgnoreFile = // 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 = + let relativePath: string = fs.Path.GetRelativePath(ignoreRoot, absoluteFilePath.Path).Replace("\\", "/") fantomasIgnore.IsIgnored(relativePath) diff --git a/src/Fantomas/Paths.fs b/src/Fantomas/Paths.fs index b70fadb683..1954ef0472 100644 --- a/src/Fantomas/Paths.fs +++ b/src/Fantomas/Paths.fs @@ -16,16 +16,10 @@ let extensionLookup: HashSet = // 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. Both separators are covered, since a path can reach us spelled either way. +// needs to be. let excludedDirFragments: string array = - let separators: char array = - if Path.DirectorySeparatorChar = Path.AltDirectorySeparatorChar then - [| Path.DirectorySeparatorChar |] - else - [| Path.DirectorySeparatorChar; Path.AltDirectorySeparatorChar |] - - [| for dir in [| "obj"; ".fable"; "fable_modules"; "node_modules" |] do - for separator in separators -> String.Concat(string separator, dir, string separator) |] + [| for dir in [| "obj"; ".fable"; "fable_modules"; "node_modules" |] -> + String.Concat(string Path.DirectorySeparatorChar, dir, string Path.DirectorySeparatorChar) |] let isInExcludedDir (fullPath: string) : bool = excludedDirFragments diff --git a/src/Fantomas/Report.fs b/src/Fantomas/Report.fs index 9a37015328..9e67c145ad 100644 --- a/src/Fantomas/Report.fs +++ b/src/Fantomas/Report.fs @@ -22,7 +22,7 @@ let sourceOf (fs: IFileSystem) (file: string) : string = let partitionResults (results: #(FormatResult seq)) - : (string * ProfileInfo option) list * string list * (string * ProfileInfo option) list * (string * Exception) list = + : (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 @@ -32,14 +32,14 @@ let partitionResults | FormatResult.Error(file, e) -> (oks, ignores, unchanged, (file, e) :: errors) | FormatResult.InvalidCode(file, _) -> let ex: FormatException = invalidResultException file - (oks, ignores, unchanged, (file, ex :> Exception) :: errors)) + (oks, ignores, unchanged, (file, ex :> exn) :: errors)) -let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, exn: Exception) : unit = +let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, error: exn) : unit = let describeOther () : string = let message: string = match verbosity with | VerbosityLevel.Normal -> - match exn with + match error with | :? DefineParseException as dpe -> let combinations: string = dpe.Combinations @@ -49,7 +49,7 @@ let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, $"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}" + | VerbosityLevel.Detailed -> $"%A{error}" if String.IsNullOrEmpty message then $"Failed to format file: %s{file}" @@ -58,7 +58,7 @@ let reportError (env: CliEnvironment) (verbosity: VerbosityLevel) (file: string, // 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) exn with + match Diagnostics.describeParseFailure file (fun () -> sourceOf env.FileSystem file) error with | Some parseFailure -> env.Log.Error parseFailure | None -> env.Log.Error(describeOther ())