Skip to content

Commit

Permalink
Add Process.run is_success
Browse files Browse the repository at this point in the history
  • Loading branch information
SGrondin committed Jul 19, 2023
1 parent 3fe5755 commit 709faaf
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib_eio/process.ml
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,13 @@ let spawn ~sw (t:#mgr) ?cwd ?stdin ?stdout ?stderr ?env ?executable args =
?stdout:(stdout :> Flow.sink option)
?stderr:(stderr :> Flow.sink option)

let run (t:#mgr) ?cwd ?stdin ?stdout ?stderr ?env ?executable args =
let run (t:#mgr) ?cwd ?stdin ?stdout ?stderr ?is_success ?env ?executable args =
Switch.run @@ fun sw ->
let child = spawn ~sw t ?cwd ?stdin ?stdout ?stderr ?env ?executable args in
match await child with
| `Exited 0 -> ()
| status ->
match await child, is_success with
| `Exited 0, None -> ()
| `Exited code, Some f when f code -> ()
| status, _ ->
let ex = err (Child_error status) in
raise (Exn.add_context ex "running command: %a" pp_args args)

Expand Down
3 changes: 3 additions & 0 deletions lib_eio/process.mli
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,14 @@ val run :
?stdin:#Flow.source ->
?stdout:#Flow.sink ->
?stderr:#Flow.sink ->
?is_success:(int -> bool) ->
?env:string array ->
?executable:string ->
string list -> unit
(** [run] does {!spawn} followed by {!await_exn}, with the advantage that if the process fails then
the error message includes the command that failed.
When [is_success] is present, it is called with the exit code to determine whether it indicates success or failure.
Without [is_success], success requires the process to return an exit code of 0.
Note: If [spawn] needed to create extra fibers to copy [stdin], etc, then it also waits for those to finish. *)

Expand Down
8 changes: 8 additions & 0 deletions tests/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,14 @@ Eio.Io Process Child_error Exited (code 3),
running command: bash -c "exit 3" "" foo
```

Exit code success can be determined by is_success:

```ocaml
# run @@ fun mgr env ->
Process.run ~is_success:(fun code -> Int.(code = 3)) mgr ["bash"; "-c"; "exit 3"; ""; "foo"];;
- : unit = ()
```

The default environment:

```ocaml
Expand Down

0 comments on commit 709faaf

Please sign in to comment.