/// Formatting: the text of a file laid out as `bjo fmt` lays it out. /// /// The formatter is `bjo/format.bjo`, a Bjolang program, so the server runs /// `bjo fmt -`, which reads the text on standard input and writes it laid out /// on standard output. What an editor gets is then what the command line /// writes. module BjolangLsp.Format open System open System.Diagnostics open System.IO open System.Text /// How long `bjo fmt -` may take. The first run after the compiler changed /// builds `bjo`, which is the longest that it takes. let private limit = TimeSpan.FromSeconds 120.0 /// `text` laid out, or why it cannot be: the text does not read, or `bjo` is /// not there or failed. /// /// - `-q`: `bjo` then says nothing about a build of itself. /// - Standard output and standard error are read while the process runs, so /// that a long text does not fill a pipe and stop it. let source (text: string) : Result = let launcher = Path.Combine(Bjolang.Paths.root, "bjo", "bjo") if not (File.Exists launcher) then Error $"There is no bjo at %s{launcher}." else let info = ProcessStartInfo( launcher, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, StandardInputEncoding = UTF8Encoding false, StandardOutputEncoding = UTF8Encoding false, StandardErrorEncoding = UTF8Encoding false ) for argument in [ "-q"; "fmt"; "-" ] do info.ArgumentList.Add argument try use p = Process.Start info let out = p.StandardOutput.ReadToEndAsync() let err = p.StandardError.ReadToEndAsync() p.StandardInput.Write text p.StandardInput.Close() if not (p.WaitForExit(int limit.TotalMilliseconds)) then try p.Kill true with _ -> () Error "bjo fmt did not end in time." elif p.ExitCode <> 0 then // `bjo fmt: line 3: a ( that is never closed` match err.Result.Trim() with | "" -> Error $"bjo fmt failed with exit code %d{p.ExitCode}." | why -> Error why else Ok out.Result with ex -> Error $"bjo fmt could not be run: %s{ex.Message}"