Removed dependency on imported merjislib.
[cocanwiki.git] / scripts / cocanwiki_files.ml
1 (* Basic file functions.
2  * Copyright (C) 2004 Merjis Ltd.
3  * Written By Richard W.M. Jones (rich@merjis.com)
4  * $Id: cocanwiki_files.ml,v 1.1 2004/09/07 14:58:34 rich Exp $
5  *)
6
7 open Printf
8
9 (*----- File functions. -----*)
10
11 let (//) = Filename.concat
12
13 let rec input_all_lines chan =
14   try
15     let line = input_line chan in
16     line :: input_all_lines chan
17   with
18       End_of_file -> []
19
20 let input_all chan =
21   let buf = Buffer.create 16384 in
22   let tmpsize = 16384 in
23   let tmp = String.create tmpsize in
24   let n = ref 0 in
25   while n := input chan tmp 0 tmpsize; !n > 0 do
26     Buffer.add_substring buf tmp 0 !n;
27   done;
28   Buffer.contents buf
29
30 let input_file filename =
31   let chan = open_in_bin filename in
32   let data = input_all chan in
33   close_in chan;
34   data
35
36 let output_file filename data =
37   let chan = open_out_bin filename in
38   output_string chan data;
39   close_out chan
40
41 let output_tempfile data =
42   let filename, chan = Filename.open_temp_file "tmp" ".tmp" in
43   output_string chan data;
44   close_out chan;
45   filename
46
47 (*----- Command functions. -----*)
48
49 let cmd cmd =
50   let code = Sys.command cmd in
51   if code <> 0 then failwith (cmd ^ ": error code " ^ string_of_int code)
52
53 let copy infile outfile =
54   cmd (sprintf "cp %s %s" infile outfile)
55
56 let pget cmd =
57   let chan = Unix.open_process_in cmd in
58   let lines = input_all_lines chan in
59   let stat = Unix.close_process_in chan in
60   (match stat with
61        Unix.WEXITED 0 -> ()
62      | Unix.WEXITED i ->
63          failwith ("command failed with code " ^ string_of_int i)
64      | Unix.WSIGNALED i ->
65          failwith ("command killed by signal " ^ string_of_int i)
66      | Unix.WSTOPPED i ->
67          failwith ("command stopped by signal " ^ string_of_int i));
68   lines
69
70 let unlink file =
71   try Unix.unlink file with Unix.Unix_error _ -> ()