Skip to content

Commit

Permalink
Merge pull request #25 from Tarmil/exec-newlines
Browse files Browse the repository at this point in the history
fix(Exec): Preserve newlines except the final one
  • Loading branch information
Tarmil authored Oct 15, 2022
2 parents eff138e + 66d2c14 commit 4c5148b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
28 changes: 24 additions & 4 deletions src/FSharp.Data.LiteralProviders.DesignTime/Exec.fs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,28 @@ let (|Args|_|) baseDir (args: obj[]) =
|> Some
| _ -> None

type OutputLineState =
| FirstLine
| SubsequentLine of lastLineWasEmpty: bool

/// We want to include all newlines except the final one, if any.
let readOutput (event: IEvent<DataReceivedEventHandler, DataReceivedEventArgs>) =
let output = StringBuilder()
event
|> Event.filter (fun e -> not (isNull e.Data))
|> Event.scan (fun lineState e ->
let thisLineIsEmpty = e.Data = ""
match lineState with
| FirstLine ->
output.Append(e.Data) |> ignore
| SubsequentLine lastLineWasEmpty when lastLineWasEmpty || not thisLineIsEmpty ->
output.AppendLine().Append(e.Data) |> ignore
| SubsequentLine _ -> ()
SubsequentLine thisLineIsEmpty
) FirstLine
|> Event.add ignore
output

let execute args =
let proc = new Process()
proc.StartInfo.UseShellExecute <- false
Expand All @@ -50,10 +72,8 @@ let execute args =
proc.StartInfo.RedirectStandardInput <- true
proc.StartInfo.RedirectStandardOutput <- true
proc.StartInfo.RedirectStandardError <- true
let output = StringBuilder()
let error = StringBuilder()
proc.OutputDataReceived.Add(fun e -> output.Append(e.Data) |> ignore)
proc.ErrorDataReceived.Add(fun e -> error.Append(e.Data) |> ignore)
let output = readOutput proc.OutputDataReceived
let error = readOutput proc.ErrorDataReceived
proc.Start() |> ignore
let startTime = try proc.StartTime with _ -> DateTime.Now
args.Input |> Option.iter proc.StandardInput.Write
Expand Down
13 changes: 11 additions & 2 deletions tests/FSharp.Data.LiteralProviders.Tests/Exec.fs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,17 @@ type DotnetListReference = Exec<"dotnet", "list reference">
let ``with success`` () =
test <@ DotnetListReference.ExitCode = 0 @>
test <@ DotnetListReference.Error = "" @>
test <@ DotnetListReference.Output.StartsWith("Project reference(s)") @>
test <@ DotnetListReference.Output.EndsWith(".fsproj") @>
test <@ DotnetListReference.Output =
([ @"Project reference(s)"
@"--------------------"
@"..\..\src\FSharp.Data.LiteralProviders.Runtime\FSharp.Data.LiteralProviders.Runtime.fsproj" ]
|> String.concat System.Environment.NewLine) @>

type DotnetVersion = Exec<"dotnet", "--version">

[<Test>]
let ``single line excludes newline`` () =
test <@ not <| DotnetVersion.Output.Contains("\n") @>

type DotnetListError = Exec<"dotnet", "list whatever">

Expand Down

0 comments on commit 4c5148b

Please sign in to comment.