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