Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"rollForward": false
},
"fsharp-analyzers": {
"version": "0.36.0",
"version": "0.37.2",
"commands": [
"fsharp-analyzers"
],
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,6 @@ tests/.repositories/**
coverage.xml
coveragereport/
coverage.xml.*.acv

# Analyzer reports (see the Analyze pipeline in build.fsx); analysis.sarif is covered by *.sarif
analysisreports/
21 changes: 13 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,18 @@ dotnet fsi build.fsx -- -p FormatAll
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.
Every project of the solution is analyzed in its own process, so findings are printed per project
as that project finishes rather than all at the end. The smallest projects report within seconds,
`Fantomas.Core.Tests` takes a couple of minutes and decides how long the run takes.

**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.
The findings also land in `analysis.sarif` in the repo root, merged from the per-project reports in
`analysisreports/`. **Read one of them afterwards.** The pipeline 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.
When you read the SARIF, 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.

`Fantomas.FCS` and `Fantomas.FCS.BuildTasks` are left out: both are vendored compiler sources, so a
finding in either is something to report upstream rather than something to fix here.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- 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)
- Breaking: `Fantomas.Core` is no longer binary compatible with `v7`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `v7` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407)

### Fixed

Expand Down
4 changes: 2 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
<PackageVersion Include="Ionide.KeepAChangelog.Tasks" Version="0.3.3"/>
<PackageVersion Include="DotNet.ReproducibleBuilds" Version="2.0.2"/>

<PackageVersion Include="G-Research.FSharp.Analyzers" Version="0.22.0" />
<PackageVersion Include="Ionide.Analyzers" Version="0.15.0" />
<PackageVersion Include="G-Research.FSharp.Analyzers" Version="0.23.0" />
<PackageVersion Include="Ionide.Analyzers" Version="0.17.0" />

<PackageVersion Include="StreamJsonRpc" Version="2.25.29" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
Expand Down
28 changes: 0 additions & 28 deletions Directory.Solution.targets

This file was deleted.

195 changes: 194 additions & 1 deletion build.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -859,11 +859,204 @@ pipeline "PublishAlpha" {
runIfOnlySpecified true
}

/// The projects the analyzers run over: every project in the solution, minus the ones whose source
/// is not ours to change. Fantomas.FCS is generated from the vendored compiler sources, and
/// Fantomas.FCS.BuildTasks compiles a single vendored compiler file, so a finding in either is
/// something to report upstream rather than something to fix here. Reading the solution rather than
/// globbing keeps build tooling out on its own: a project only gets analyzed once it is a real part
/// of the product.
let projectsToAnalyze: string list =
let excluded = set [ "Fantomas.FCS" ]

// Analyzing a project costs roughly what type checking it costs, so the largest one decides how
// long the whole run takes. Starting with it means it is never the one left waiting for a slot.
let sourceSize (project: string) =
Directory.EnumerateFiles(
Path.GetDirectoryName(__SOURCE_DIRECTORY__ </> project),
"*.fs",
SearchOption.AllDirectories
)
|> Seq.sumBy (fun file -> FileInfo(file).Length)

XDocument.Load(__SOURCE_DIRECTORY__ </> "fantomas.slnx").XPathSelectElements("//Project")
|> Seq.map (fun project -> project.Attribute(XName.Get "Path").Value.Replace('\\', '/'))
|> Seq.filter (fun path -> not (excluded.Contains(Path.GetFileNameWithoutExtension path)))
|> Seq.sortByDescending sourceSize
|> Seq.toList

/// Where the analyzers live on disk. Both are ordinary package references, so MSBuild already knows
/// the restored path of each and there is no second place to keep the version in sync.
let analyzerPaths () : Async<string list> =
async {
let! result =
Cli
.Wrap("dotnet")
.WithArguments(
"msbuild src/Fantomas/Fantomas.fsproj -getProperty:PkgIonide_Analyzers "
+ "-getProperty:PkgG-Research_FSharp_Analyzers"
)
.WithWorkingDirectory(__SOURCE_DIRECTORY__)
.WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync()
.Task
|> Async.AwaitTask

if result.ExitCode <> 0 then
failwith $"Could not resolve the analyzer packages. Run `dotnet restore` first.\n{result.StandardError}"

let properties = JsonValue.Parse(result.StandardOutput).GetProperty("Properties")

return
[ for property in properties.Properties() ->
let name, value = property

match value.AsString() with
| "" -> failwith $"MSBuild has no value for {name}. Run `dotnet restore` first."
| path -> path </> "analyzers" </> "dotnet" </> "fs" ]
}

/// The number of results a single analyzer report holds, used to report what a project turned up
/// the moment it finishes.
let sarifResultCount (report: string) : int =
if not (File.Exists report) then
0
else
JsonValue.Parse(File.ReadAllText report).GetProperty("runs").AsArray()
|> Array.sumBy (fun run ->
match run.TryGetProperty "results" with
| Some results -> results.AsArray().Length
| None -> 0)

/// Folds the per-project reports into the one SARIF run that GitHub code scanning takes.
///
/// SARIF carries a run per tool invocation, but code scanning rejects a file holding several unless
/// each names its own category, and one project of this solution is not an analysis of its own. The
/// runs all come from the same tool, so their results concatenate into a single run. Every
/// invocation is kept, which is what records that a project was looked at even when it turned up
/// nothing.
///
/// The reports carry no rule metadata, only a `ruleId` per result, so there is no rule table to
/// renumber against. Should a later version of the analyzers SDK start writing one, this has to
/// merge that too.
let mergeSarifReports (reports: string list) (target: string) : unit =
let documents =
reports
|> List.filter File.Exists
|> List.map (fun report -> JsonValue.Parse(File.ReadAllText report))

let runs =
documents
|> List.collect (fun document -> document.GetProperty("runs").AsArray() |> List.ofArray)

match documents, runs with
| firstDocument :: _, firstRun :: _ ->
let concat (name: string) =
runs
|> List.collect (fun run ->
match run.TryGetProperty name with
| Some array -> List.ofArray (array.AsArray())
| None -> [])
|> Array.ofList
|> JsonValue.Array

let merged =
JsonValue.Record
[| "$schema", firstDocument.GetProperty("$schema")
"version", firstDocument.GetProperty("version")
"runs",
JsonValue.Array
[| JsonValue.Record
[| "tool", firstRun.GetProperty("tool")
"columnKind", firstRun.GetProperty("columnKind")
"results", concat "results"
"invocations", concat "invocations" |] |] |]

File.WriteAllText(target, merged.ToString())
| _ -> failwith "The analyzers wrote no report to merge."

/// Runs the analyzers over the solution, one process per project, several at a time.
///
/// A single process walking every project in turn takes minutes and says nothing until the last one
/// is done, which is a long time to stare at a blank terminal. Each project is instead analyzed on
/// its own, and its output is held back and printed in one piece as that project finishes, so
/// findings arrive while the run is still going and no two projects can interleave their lines.
///
/// Returns the highest exit code of the runs, so a project the analyzers could not process fails
/// the stage rather than passing for want of findings.
let analyzeSolution () : Async<int> =
async {
let! analyzers = analyzerPaths ()

if Directory.Exists analysisReportsDir then
Directory.Delete(analysisReportsDir, true)

Directory.CreateDirectory analysisReportsDir |> ignore

let names =
projectsToAnalyze
|> List.map Path.GetFileNameWithoutExtension
|> String.concat ", "

printfn $"Analyzing {projectsToAnalyze.Length} projects: {names}"

let analyzeProject (project: string) =
async {
let name = Path.GetFileNameWithoutExtension project
let report = analysisReportsDir </> $"{name}.sarif"
let started = DateTime.UtcNow

let arguments =
[ "fsharp-analyzers"
for analyzer in analyzers do
"--analyzers-path"
analyzer
"--code-root"
__SOURCE_DIRECTORY__
"--report"
report
"--project"
__SOURCE_DIRECTORY__ </> project ]

let! result =
Cli
.Wrap("dotnet")
.WithArguments(arguments)
.WithWorkingDirectory(__SOURCE_DIRECTORY__)
.WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync()
.Task
|> Async.AwaitTask

let elapsed = DateTime.UtcNow - started
let findings = sarifResultCount report

let summary =
match findings with
| 0 -> "no findings"
| 1 -> "1 finding"
| n -> $"{n} findings"

printfn $"\n=== {name}: {summary} in {elapsed.TotalSeconds:F1}s"
printf "%s" result.StandardOutput
eprintf "%s" result.StandardError

return report, result.ExitCode
}

// Every analyzer process type checks a whole project, so a handful at a time is what keeps
// the machine busy without the runs starving each other of memory.
let! results = Async.Parallel(List.map analyzeProject projectsToAnalyze, max 2 (Environment.ProcessorCount / 2))

mergeSarifReports (results |> Array.map fst |> List.ofArray) (__SOURCE_DIRECTORY__ </> "analysis.sarif")

return results |> Array.map snd |> Array.fold max 0
}

pipeline "Analyze" {
workingDir __SOURCE_DIRECTORY__
stage "RestoreTools" { run "dotnet tool restore" }
stage "RestoreSolution" { run "dotnet restore --tl" }
stage "Analyze" { run "dotnet msbuild /t:AnalyzeSolution" }
stage "Analyze" { run (fun _ -> analyzeSolution ()) }
runIfOnlySpecified true
}

Expand Down
6 changes: 6 additions & 0 deletions docs/docs/end-users/UpgradeGuide.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,12 @@ let dotted ifaces =
These only affect you if you consume `Fantomas.Core` as a library. Formatting source text through
`CodeFormatter.FormatDocumentAsync` is unaffected.

#### No longer binary compatible with `v7`

Several discriminated unions are structs now. That changes nothing about how they are constructed,
matched or compared, so no source of yours has to be edited, but an assembly compiled against `v7`
has to be rebuilt against `v8`.

#### Exceptions

- `InvariantViolationException` was added. It derives from `FormatException` and is raised when Fantomas reaches a state its own model says is impossible, which always means a bug in Fantomas rather than a problem with your code.
Expand Down
12 changes: 6 additions & 6 deletions src/Fantomas.Benchmarks/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@
},
"G-Research.FSharp.Analyzers": {
"type": "Direct",
"requested": "[0.22.0, )",
"resolved": "0.22.0",
"contentHash": "H0OoKxTX4l6TaTB7feujped+dtg5HdRZczqysEYreBnYtx8YYRPOe/IaSQYxmz+L2v2FVvRXpVWBixtr9am6Vg=="
"requested": "[0.23.0, )",
"resolved": "0.23.0",
"contentHash": "OySQ+6afD54e0P4bhGFS7DS7ijVP0tm4MgKw+Qn+JSyr0ObSktOoRGYO2mxUX7wzNuxr/67xO2JkXrkwBWwlnA=="
},
"Ionide.Analyzers": {
"type": "Direct",
"requested": "[0.15.0, )",
"resolved": "0.15.0",
"contentHash": "Sz6bu/glU0cihF0RT8y8+v6FsXonQlN4WCl7yX9EjJW+RzZmQbCc4pxKHwGFwYJNZCLgOnXQj/KZqtFlyXdhWQ=="
"requested": "[0.17.0, )",
"resolved": "0.17.0",
"contentHash": "vTlenH0GbY+MGQHa26EeFaNIf4AfmVa9Jha2DJCTJxFZlYcr11Phi1ngq/Rabpn3Xii/Ri0ZWFqMjI90KgQEMQ=="
},
"BenchmarkDotNet.Annotations": {
"type": "Transitive",
Expand Down
12 changes: 6 additions & 6 deletions src/Fantomas.Client.Tests/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@
},
"G-Research.FSharp.Analyzers": {
"type": "Direct",
"requested": "[0.22.0, )",
"resolved": "0.22.0",
"contentHash": "H0OoKxTX4l6TaTB7feujped+dtg5HdRZczqysEYreBnYtx8YYRPOe/IaSQYxmz+L2v2FVvRXpVWBixtr9am6Vg=="
"requested": "[0.23.0, )",
"resolved": "0.23.0",
"contentHash": "OySQ+6afD54e0P4bhGFS7DS7ijVP0tm4MgKw+Qn+JSyr0ObSktOoRGYO2mxUX7wzNuxr/67xO2JkXrkwBWwlnA=="
},
"Ionide.Analyzers": {
"type": "Direct",
"requested": "[0.15.0, )",
"resolved": "0.15.0",
"contentHash": "Sz6bu/glU0cihF0RT8y8+v6FsXonQlN4WCl7yX9EjJW+RzZmQbCc4pxKHwGFwYJNZCLgOnXQj/KZqtFlyXdhWQ=="
"requested": "[0.17.0, )",
"resolved": "0.17.0",
"contentHash": "vTlenH0GbY+MGQHa26EeFaNIf4AfmVa9Jha2DJCTJxFZlYcr11Phi1ngq/Rabpn3Xii/Ri0ZWFqMjI90KgQEMQ=="
},
"Microsoft.NET.Test.Sdk": {
"type": "Direct",
Expand Down
1 change: 1 addition & 0 deletions src/Fantomas.Client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ This is the changelog for the Fantomas.Client package specifically. It's distinc

### Changed
- Bump `StreamJsonRpc` to `2.25.29`. [#3393](https://github.com/fsprojects/fantomas/pull/3393)
- Breaking: no longer binary compatible with `0.11.0`. Several discriminated unions are structs now, which changes nothing about how they are written or matched, but an assembly compiled against `0.11.0` has to be rebuilt. [#3407](https://github.com/fsprojects/fantomas/pull/3407)

## [0.11.0] - 2026-04-16

Expand Down
Loading
Loading