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
36 changes: 35 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,27 @@ The static `Proc.Start` has a timeout of `4 minutes` if not specified.

**NOTE** `ConsoleOut` will always be set regardless of whether an `IConsoleOutWriter` is provided

## Proc.StartLongRunning

Start a process that keeps running, such as a web server or a database, and go on once it says it is ready.
Disposing the returned subscription stops the process.

```csharp
var args = new LongRunningArguments("dotnet", "run", "--project", "api")
{
StartedConfirmationHandler = l => l.Line.Contains("Now listening"),
SendControlCFirst = true
};
using (var api = Proc.StartLongRunning(args, TimeSpan.FromMinutes(1)))
{
// api.ProcessId, api.ExitCode (once it exited on its own), api.WaitForCompletion(timeout)
}
```

`StartLongRunning` waits for a line that `StartedConfirmationHandler` accepts. Without a handler it returns straight away.
When no such line comes in time, it stops the process and throws `ProcExecException`.
`ExitCode` stays `null` while the process runs, and after disposing stopped it.

## ObservableProcess

The heart of it all this is an `IObservable<CharactersOut>`. It listens on the output buffers directly and does not wait on
Expand Down Expand Up @@ -166,7 +187,20 @@ let sha = shell {
}
```

See [src/Proc.Fs/README.md](src/Proc.Fs/README.md) for `shell { }`, the `Cmd` module, pipes and the `exec { }` builder.
A block can also start a background process and stop it at the end of a scope, run clean-up commands, and run blocks
at the same time:

```fsharp
shell {
use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening"))
use! _ = defer (sh $"docker compose down")
let! _ = concurrently [ steps { sh $"dotnet test tests/A" }; steps { sh $"dotnet test tests/B" } ]
return ()
}
```

See [src/Proc.Fs/README.md](src/Proc.Fs/README.md) for `shell { }`, background processes, the `Cmd` module, pipes and
the `exec { }` builder.

# .NET 11

Expand Down
10 changes: 5 additions & 5 deletions src/Proc.Fs/Bindings.fs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ type ExecBuilder() =
/// <param name="arguments">the arguments to pass on to the binary being executed</param>
[<CustomOperation("run")>]
member this.Execute(opts, binary, [<ParamArray>] arguments: string array) =
Runner.run { opts with Binary = binary; Arguments = Some (arguments |> List.ofArray)}
Runner.run System.Threading.CancellationToken.None { opts with Binary = binary; Arguments = Some (arguments |> List.ofArray)}

///<summary>Runs <paramref name="binary"/> using <paramref name="arguments"/> immediately</summary>
/// <param name="opts"><see cref="ExecOptions"/> the computation build thus far, not specified directly</param>
/// <param name="binary">The binary to execute</param>
/// <param name="arguments">the arguments to pass on to the binary being executed</param>
[<CustomOperation("run")>]
member this.Execute(opts, binary, arguments: string list) =
Runner.run { opts with Binary = binary; Arguments = Some arguments}
Runner.run System.Threading.CancellationToken.None { opts with Binary = binary; Arguments = Some arguments}

///<summary>
/// Runs the <see cref="ExecOptions"/> the computation build thus far.
Expand All @@ -33,7 +33,7 @@ type ExecBuilder() =
[<CustomOperation("run")>]
member this.Execute(opts) =
if opts.Binary = "" then failwithf "No binary specified to exec computation expression"
Runner.run opts
Runner.run System.Threading.CancellationToken.None opts

///<summary>Supply external <see cref="ExecOptions"/> to bootstrap</summary>
[<CustomOperation("options")>]
Expand Down Expand Up @@ -162,11 +162,11 @@ type ExecBuilder() =

[<CustomOperation("run_args")>]
member this.InvokeArgs(opts, [<ParamArray>] arguments: string array) =
Runner.run { opts with Arguments = Some (arguments |> List.ofArray) }
Runner.run System.Threading.CancellationToken.None { opts with Arguments = Some (arguments |> List.ofArray) }

[<CustomOperation("run_args")>]
member this.InvokeArgs(opts, arguments: string list) =
Runner.run { opts with Arguments = Some arguments }
Runner.run System.Threading.CancellationToken.None { opts with Arguments = Some arguments }

[<CustomOperation("exit_code_of")>]
member this.ReturnStatus(opts, binary, arguments: string list) =
Expand Down
48 changes: 30 additions & 18 deletions src/Proc.Fs/Cmd.fs
Original file line number Diff line number Diff line change
Expand Up @@ -225,15 +225,18 @@ module internal Runner =
lock buffer (fun () -> for line in buffer do console line)
reraise ()

/// Runs attempt again while it throws ProcExecException and the command's retry policy allows
let retrying (cmd: Cmd) (attempt: unit -> 'T) : 'T =
/// Runs attempt again while it throws ProcExecException and the command's retry policy allows.
/// Stops retrying once ct is cancelled.
let retrying (cmd: Cmd) (ct: CancellationToken) (attempt: unit -> 'T) : 'T =
let policy = cmd.Retry |> Option.defaultValue { Retries = 0; Delay = TimeSpan.Zero }
let rec go tries =
try attempt ()
with :? ProcExecException as e when tries < policy.Retries ->
with :? ProcExecException as e when tries < policy.Retries && not ct.IsCancellationRequested ->
if cmd.Quiet <> Some true then
Console.Error.WriteLine $"Retrying ({tries + 1} of {policy.Retries}) after: {e.Message}"
if policy.Delay > TimeSpan.Zero then Thread.Sleep policy.Delay
if policy.Delay > TimeSpan.Zero then
if ct.CanBeCanceled then ct.WaitHandle.WaitOne policy.Delay |> ignore else Thread.Sleep policy.Delay
ct.ThrowIfCancellationRequested()
go (tries + 1)
go 0

Expand Down Expand Up @@ -310,22 +313,24 @@ module internal Runner =
with :? OperationCanceledException when feedCts.IsCancellationRequested -> None
completed |> Option.iter (validate upstream))

/// Runs the command on the shared console and throws when it fails
let run (cmd: Cmd) =
retrying cmd (fun () ->
/// Runs the command on the shared console and throws when it fails.
/// Cancelling ct stops the process and throws OperationCanceledException.
let run (ct: CancellationToken) (cmd: Cmd) =
retrying cmd ct (fun () ->
match cmd with
| { Stdin = None; Stdout = None; Quiet = (None | Some false) } ->
// Proc.Exec takes no cancellation token, so a cancellable run streams instead
| { Stdin = None; Stdout = None; Quiet = (None | Some false) } when not ct.CanBeCanceled ->
Proc.Exec(Args.exec { cmd with Retry = None }) |> ignore
| _ ->
withConsole cmd printLine (fun console ->
stream cmd CancellationToken.None console console |> validate cmd))
stream cmd ct console console |> validate cmd))

/// Calls f for each line of standard out as it is printed; standard error goes to the console
let iter (f: string -> unit) (cmd: Cmd) =
retrying cmd (fun () ->
let iter (ct: CancellationToken) (f: string -> unit) (cmd: Cmd) =
retrying cmd ct (fun () ->
withConsole cmd printLine (fun console ->
let mutable error: exn = null
use cts = new CancellationTokenSource()
use cts = CancellationTokenSource.CreateLinkedTokenSource ct
let onLine (line: LineOut) =
if line.Error then console line
elif isNull error then
Expand All @@ -340,14 +345,14 @@ module internal Runner =
result |> Option.iter (validate cmd)))

/// Runs the command, collecting every line, and reads the result
let get (capture: Capture<'T>) : 'T =
retrying capture.Cmd (fun () ->
let get (ct: CancellationToken) (capture: Capture<'T>) : 'T =
retrying capture.Cmd ct (fun () ->
withConsole capture.Cmd printLine (fun console ->
let lines = ResizeArray<LineOut>()
let onLine (line: LineOut) =
lock lines (fun () -> lines.Add line)
if line.Error || capture.EchoStdout then console line
let result = stream capture.Cmd CancellationToken.None console onLine
let result = stream capture.Cmd ct console onLine
validate capture.Cmd result
capture.Read (ProcessCaptureResult(result.Completed, lines, result.ExitCode))))

Expand Down Expand Up @@ -437,6 +442,13 @@ module Cmd =
/// <summary>Terminates the process when this process exits (.NET 11+ on Windows and Linux only)</summary>
let killOnParentExit (cmd: Cmd) = { cmd with KillOnParentExit = Some true }

/// <summary>
/// For <c>background</c> in a <c>shell { }</c> block: wait until the command prints a line, on standard out or
/// standard error, for which <paramref name="isReady"/> is true. <c>Cmd.timeout</c> limits that wait.
/// </summary>
let waitFor (isReady: string -> bool) (cmd: Cmd) =
{ cmd with StartedConfirmationHandler = Some (fun (line: LineOut) -> isReady line.Line) }

/// <summary>Writes <paramref name="lines"/> to the standard input of the process, then closes it</summary>
let stdin (lines: string seq) (cmd: Cmd) = { cmd with Stdin = Some (StdinSource.Lines lines) }

Expand Down Expand Up @@ -531,16 +543,16 @@ module Cmd =
let choose (f: string -> 'U option) (capture: Capture<string list>) = mapCapture (List.choose f) capture

/// <summary>Runs the command on the shared console. Throws <see cref="ProcExecException"/> when it fails.</summary>
let run (cmd: Cmd) = Runner.run cmd
let run (cmd: Cmd) = Runner.run CancellationToken.None cmd

/// <summary>Runs the command and returns what the capture reads</summary>
let get (capture: Capture<'T>) : 'T = Runner.get capture
let get (capture: Capture<'T>) : 'T = Runner.get CancellationToken.None capture

/// <summary>
/// Calls <paramref name="f"/> for each line of standard out while the command runs, without buffering.
/// Standard error goes to the console. Throws when the command fails or <paramref name="f"/> throws.
/// </summary>
let iter (f: string -> unit) (cmd: Cmd) = Runner.iter f cmd
let iter (f: string -> unit) (cmd: Cmd) = Runner.iter CancellationToken.None f cmd

/// <summary>Brought into scope by <c>open Proc.Fs</c></summary>
[<AutoOpen>]
Expand Down
51 changes: 51 additions & 0 deletions src/Proc.Fs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,57 @@ shell {
A command's own `Cmd.cwd` resolves against the shell's directory, and its own `Cmd.env` wins over `setEnv`.
`do!` still works in front of commands and steps, for example `do! cd "src"`.

## Background processes, clean-up and running steps at the same time

```fsharp
shell {
use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening"))
use! _ = defer (sh $"docker compose down")
sh $"docker compose up -d db"
let! results = concurrently [
steps { cd "tests/Unit"; sh $"dotnet test" }
steps { cd "tests/Integration"; sh $"dotnet test" }
]
return results
} // the api gets Ctrl+C, then compose down runs
```

| Inside `shell { }` | Does |
|---|---|
| `use! p = background cmd` | starts `cmd` and goes on; stops it at the end of the scope |
| `Cmd.waitFor (fun line -> …)` | `background` first waits for a line that says the process is ready |
| `do! wait p` | waits until the background process exits; throws when its exit code is not accepted |
| `use! _ = defer cmd` | runs `cmd` at the end of the scope, also when the scope fails, like `trap … EXIT` |
| `let! rs = concurrently [ … ]` | runs `steps { }` blocks at the same time; results in the same order |
| `let! rs = concurrentlyAtMost n [ … ]` | the same, at most `n` at a time |

`background`:

- The process uses the block's `cd` and `env`. Its output goes to the console.
- Without `Cmd.waitFor`, the block goes on straight away. With it, `background` throws when the process exits before
it prints the line, or when the line does not come within `Cmd.timeout` (default 60 seconds).
On a background command, `Cmd.timeout` only limits that wait, as with `wait_until` in `exec { }`.
- When the process exits with an exit code that `Cmd.validExitCode` does not accept (by default anything but `0`),
the **next command** of the block throws, like `set -e`. An exit code of `0` does not fail the block.
- Stopping sends Ctrl+C first and kills the process when it has not exited after 10 seconds. Stopping never throws.
- The block stops background processes that are still running when it ends, also ones bound with `let!`.
- `p.ProcessId`, `p.HasExited`, `p.ExitCode`, `p.Stop()` and `p.SendControlC()` work on the handle.

`defer` runs its command in the directory and environment of the moment `defer` runs, so a later `cd` does not
change it. When the scope fails and the deferred command fails too, the scope's exception propagates and the
failure of the deferred command goes to standard error.

`steps { }` is a `shell { }` block that does not run when it is evaluated. It runs where you use it, with `do!`,
`let!` or on a line of its own, in the directory and environment of the block that uses it.

`concurrently`:

- Each branch starts with a copy of the directory and environment, so a `cd` in one branch does not reach the
others or the block.
- The first branch that fails stops the others, and its exception is the one that propagates.
- A background process the block started that fails also fails the branches.
- Output of the branches interleaves line by line on the console.

## Writing commands with `sh`

`sh` takes an interpolated string, `$"…"`. It splits **only the text you wrote**:
Expand Down
Loading
Loading