Added --script option.
[virt-top.git] / virt-top / virt_top_utils.ml
1 (* 'top'-like tool for libvirt domains.
2  * $Id: virt_top.ml,v 1.5 2007/08/30 13:52:40 rjones Exp $
3  *)
4
5 let (//) = Filename.concat
6
7 (* Input a whole file as a list of lines. *)
8 let input_all_lines chan =
9   let lines = ref [] in
10   (try
11      while true; do
12        lines := input_line chan :: !lines
13      done
14    with
15      End_of_file -> ());
16   List.rev !lines
17
18 (* Trim whitespace from the beginning and end of strings. *)
19 let isspace c =
20   c = ' '
21   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
22
23 let triml ?(test = isspace) str =
24   let i = ref 0 in
25   let n = ref (String.length str) in
26   while !n > 0 && test str.[!i]; do
27     decr n;
28     incr i
29   done;
30   if !i = 0 then str
31   else String.sub str !i !n
32
33 let trimr ?(test = isspace) str =
34   let n = ref (String.length str) in
35   while !n > 0 && test str.[!n-1]; do
36     decr n
37   done;
38   if !n = String.length str then str
39   else String.sub str 0 !n
40
41 let trim ?(test = isspace) str =
42   trimr (triml str)
43
44 (* Read a configuration file as a list of (key, value) pairs.
45  * If the config file is missing this returns an empty list.
46  *)
47 let blanks_and_comments = Str.regexp "^[ \t]*\\(#.*\\)?$"
48
49 let read_config_file filename =
50   let lines =
51     try
52       let chan = open_in filename in
53       let lines = input_all_lines chan in
54       close_in chan;
55       lines
56     with
57       Sys_error _ -> [] in           (* Ignore errors opening file. *)
58
59   (* Line numbers. *)
60   let lines =
61     let i = ref 0 in List.map (fun line -> (incr i; !i), line) lines in
62
63   (* Remove blank lines and comment lines. *)
64   let lines =
65     List.filter
66       (fun (lineno, line) ->
67          not (Str.string_match blanks_and_comments line 0)) lines in
68
69   (* Convert to key, value pairs. *)
70   List.map (
71     fun (lineno, line) ->
72       let key, value = ExtString.String.split line " " in
73       lineno, trim key, trim value
74   ) lines