Skip to content

Commit

Permalink
Fs: additional functions
Browse files Browse the repository at this point in the history
  • Loading branch information
vouillon authored and hhugo committed Aug 25, 2024
1 parent afbe5ae commit 41020be
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
26 changes: 26 additions & 0 deletions compiler/lib/fs.ml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,29 @@ let read_file f =
Bytes.unsafe_to_string s
with e ->
failwith (Printf.sprintf "Cannot read content of %s.\n%s" f (Printexc.to_string e))

let write_file ~name ~contents =
let ch = open_out_bin name in
output_string ch contents;
close_out ch

let remove_file file = try Sys.remove file with Sys_error _ -> ()

let gen_file file f =
let f_tmp =
Filename.temp_file_name
~temp_dir:(Filename.dirname file)
(Filename.basename file)
".tmp"
in
try
let res = f f_tmp in
remove_file file;
Sys.rename f_tmp file;
res
with exc ->
remove_file f_tmp;
raise exc

let with_intermediate_file name f =
Fun.protect ~finally:(fun () -> remove_file name) (fun () -> f name)
6 changes: 6 additions & 0 deletions compiler/lib/fs.mli
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,9 @@ val find_in_path : string list -> string -> string option
val absolute_path : string -> string

val read_file : string -> string

val write_file : name:string -> contents:string -> unit

val gen_file : string -> (string -> 'a) -> 'a

val with_intermediate_file : string -> (string -> 'a) -> 'a

0 comments on commit 41020be

Please sign in to comment.