From 709faaf0f7549a897948f9037af5c8472ac37611 Mon Sep 17 00:00:00 2001 From: Simon Grondin Date: Wed, 19 Jul 2023 08:33:06 -0500 Subject: [PATCH] Add Process.run is_success --- lib_eio/process.ml | 9 +++++---- lib_eio/process.mli | 3 +++ tests/process.md | 8 ++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib_eio/process.ml b/lib_eio/process.ml index 405a05f8d..b7cd62fd2 100644 --- a/lib_eio/process.ml +++ b/lib_eio/process.ml @@ -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) diff --git a/lib_eio/process.mli b/lib_eio/process.mli index 915b8c478..491dc062b 100644 --- a/lib_eio/process.mli +++ b/lib_eio/process.mli @@ -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. *) diff --git a/tests/process.md b/tests/process.md index 340a2b4bd..8e66552ad 100644 --- a/tests/process.md +++ b/tests/process.md @@ -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