Skip to content

Commit

Permalink
mllib: Add 'protect' function (like try/finally).
Browse files Browse the repository at this point in the history
Use the function in the virt-v2v [Windows] module.

This is just refactoring.  There is no visible change in
functionality.
  • Loading branch information
rwmjones committed Jan 31, 2016
1 parent db3e202 commit 53cc037
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
7 changes: 7 additions & 0 deletions mllib/common_utils.ml
Expand Up @@ -273,6 +273,13 @@ let may f = function

type ('a, 'b) maybe = Either of 'a | Or of 'b

let protect ~f ~finally =
let r =
try Either (f ())
with exn -> Or exn in
finally ();
match r with Either ret -> ret | Or exn -> raise exn

let istty chan =
Unix.isatty (Unix.descr_of_out_channel chan)

Expand Down
12 changes: 12 additions & 0 deletions mllib/common_utils.mli
Expand Up @@ -130,6 +130,18 @@ val may : ('a -> unit) -> 'a option -> unit
type ('a, 'b) maybe = Either of 'a | Or of 'b
(** Like the Haskell [Either] type. *)

val protect : f:(unit -> 'a) -> finally:(unit -> unit) -> 'a
(** Execute [~f] and afterwards execute [~finally].
If [~f] throws an exception then [~finally] is run and the
original exception from [~f] is re-raised.
If [~finally] throws an exception, then the original exception
is lost. (NB: Janestreet core {!Exn.protectx}, on which this
function is modelled, doesn't throw away the exception in this
case, but requires a lot more work by the caller. Perhaps we
will change this in future.) *)

val prog : string
(** The program name (derived from {!Sys.executable_name}). *)

Expand Down
14 changes: 7 additions & 7 deletions v2v/windows.ml
Expand Up @@ -55,16 +55,16 @@ and (=~) str rex =
let with_hive (g : Guestfs.guestfs) hive_filename ~write f =
let verbose = verbose () in
g#hivex_open ~write ~verbose (* ~debug:verbose *) hive_filename;
let r =
try
protect ~f:(
fun () ->
let root = g#hivex_root () in
let ret = f root in
if write then g#hivex_commit None;
Either ret
with exn ->
Or exn in
g#hivex_close ();
match r with Either ret -> ret | Or exn -> raise exn
ret
) ~finally:(
fun () ->
g#hivex_close ()
)

(* Find the given node in the current hive, relative to the starting
* point. Returns [None] if the node is not found.
Expand Down

0 comments on commit 53cc037

Please sign in to comment.