|
| 1 | +#r "../artifacts/bin/Fantomas.FCS/debug/Fantomas.FCS.dll" |
| 2 | +#r "../artifacts/bin/Fantomas.Core/debug/Fantomas.Core.dll" |
| 3 | +#r "nuget: editorconfig" |
| 4 | + |
| 5 | +#load "../src/Fantomas/EditorConfig.fs" |
| 6 | + |
| 7 | +open System.IO |
| 8 | +open Fantomas.Core |
| 9 | +open Fantomas.EditorConfig |
| 10 | + |
| 11 | +let parseEditorConfigContent (content: string) : FormatConfig = |
| 12 | + let tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()) |
| 13 | + Directory.CreateDirectory(tempDir) |> ignore |
| 14 | + let editorConfigPath = Path.Combine(tempDir, ".editorconfig") |
| 15 | + let fsharpFile = Path.Combine(tempDir, "temp.fs") |
| 16 | + File.WriteAllText(editorConfigPath, $"root = true\n\n[*.fs]\n%s{content}") |
| 17 | + File.WriteAllText(fsharpFile, "") |
| 18 | + |
| 19 | + try |
| 20 | + readConfiguration fsharpFile |
| 21 | + finally |
| 22 | + Directory.Delete(tempDir, true) |
| 23 | + |
| 24 | +/// Parses args and returns (source, isSignature, config). |
| 25 | +/// Accepts either a file path as last arg, or source code via stdin. |
| 26 | +/// Optional flags: --editorconfig <content>, --signature |
| 27 | +let parseArgs (args: string array) = |
| 28 | + let editorConfigIdx = args |> Array.tryFindIndex (fun a -> a = "--editorconfig") |
| 29 | + let hasSignatureFlag = args |> Array.exists (fun a -> a = "--signature") |
| 30 | + |
| 31 | + let config = |
| 32 | + match editorConfigIdx with |
| 33 | + | Some idx -> parseEditorConfigContent args.[idx + 1] |
| 34 | + | None -> FormatConfig.Default |
| 35 | + |
| 36 | + // Collect flag indices to determine which arg (if any) is the input file |
| 37 | + let flagIndices = |
| 38 | + [| match editorConfigIdx with |
| 39 | + | Some idx -> |
| 40 | + yield idx |
| 41 | + yield idx + 1 |
| 42 | + | None -> () |
| 43 | + yield! |
| 44 | + args |
| 45 | + |> Array.indexed |
| 46 | + |> Array.choose (fun (i, a) -> if a = "--signature" then Some i else None) |] |
| 47 | + |
| 48 | + let positionalArgs = |
| 49 | + args |
| 50 | + |> Array.indexed |
| 51 | + |> Array.filter (fun (i, _) -> not (Array.contains i flagIndices)) |
| 52 | + |> Array.map snd |
| 53 | + |
| 54 | + match Array.tryLast positionalArgs with |
| 55 | + | Some path when File.Exists(path) -> |
| 56 | + let sample = File.ReadAllText(path) |
| 57 | + let isSignature = hasSignatureFlag || path.EndsWith(".fsi") |
| 58 | + sample, isSignature, config |
| 59 | + | _ -> |
| 60 | + let sample = stdin.ReadToEnd() |
| 61 | + sample, hasSignatureFlag, config |
0 commit comments