Re: [Libguestfs] [PATCH 1/2] mllib: add an hook to cleanup directories on exit
[Adding libguestfs CC this time] On Thu, Feb 20, 2014 at 03:04:19PM +0100, Pino Toscano wrote:
Much similar to unlink_on_exit, but recursively cleaning directories. --- mllib/common_utils.ml | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+)
diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml index 3943417..d02a2d3 100644 --- a/mllib/common_utils.ml +++ b/mllib/common_utils.ml @@ -386,6 +386,41 @@ let unlink_on_exit = registered_handlers := true )
+(* Remove a temporary directory on exit. *) +let rmdir_on_exit = + let dirs = ref [] in + let registered_handlers = ref false in + + let rec unlink_dirs () = + let rec recursive_rmdir fn = + match (Unix.lstat fn).Unix.st_kind with + | Unix.S_DIR -> + let names = Array.map (fun d -> fn // d) (Sys.readdir fn) in + Array.iter recursive_rmdir names; + Unix.rmdir fn + | Unix.S_REG + | Unix.S_CHR + | Unix.S_BLK + | Unix.S_LNK + | Unix.S_FIFO + | Unix.S_SOCK -> + Unix.unlink fn + in + List.iter ( + fun dir -> try recursive_rmdir dir with _ -> () + ) !dirs + and register_handlers () = + (* Remove on exit. *) + at_exit unlink_dirs + in + + fun dir -> + dirs := dir :: !dirs; + if not !registered_handlers then ( + register_handlers (); + registered_handlers := true + ) +
This is really very complicated compared to: let cmd = sprintf "rm -rf %s" (Filename.quote tmpdir) in ignore (Sys.command cmd)); It's also not likely to be as well debugged as coreutils, which has been working on multiple platforms for 25 years or so. Rich. -- Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones Read my programming blog: http://rwmj.wordpress.com Fedora now supports 80 OCaml packages (the OPEN alternative to F#)
participants (1)
-
Richard W.M. Jones