Added GNU GPL/LGPL copyright notices everywhere.
[virt-top.git] / virt-top / virt_top_utils.ml
1 (* 'top'-like tool for libvirt domains.
2    (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 *)
19
20 let (//) = Filename.concat
21
22 (* Input a whole file as a list of lines. *)
23 let input_all_lines chan =
24   let lines = ref [] in
25   (try
26      while true; do
27        lines := input_line chan :: !lines
28      done
29    with
30      End_of_file -> ());
31   List.rev !lines
32
33 (* Trim whitespace from the beginning and end of strings. *)
34 let isspace c =
35   c = ' '
36   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
37
38 let triml ?(test = isspace) str =
39   let i = ref 0 in
40   let n = ref (String.length str) in
41   while !n > 0 && test str.[!i]; do
42     decr n;
43     incr i
44   done;
45   if !i = 0 then str
46   else String.sub str !i !n
47
48 let trimr ?(test = isspace) str =
49   let n = ref (String.length str) in
50   while !n > 0 && test str.[!n-1]; do
51     decr n
52   done;
53   if !n = String.length str then str
54   else String.sub str 0 !n
55
56 let trim ?(test = isspace) str =
57   trimr (triml str)
58
59 (* Read a configuration file as a list of (key, value) pairs.
60  * If the config file is missing this returns an empty list.
61  *)
62 let blanks_and_comments = Str.regexp "^[ \t]*\\(#.*\\)?$"
63
64 let read_config_file filename =
65   let lines =
66     try
67       let chan = open_in filename in
68       let lines = input_all_lines chan in
69       close_in chan;
70       lines
71     with
72       Sys_error _ -> [] in           (* Ignore errors opening file. *)
73
74   (* Line numbers. *)
75   let lines =
76     let i = ref 0 in List.map (fun line -> (incr i; !i), line) lines in
77
78   (* Remove blank lines and comment lines. *)
79   let lines =
80     List.filter
81       (fun (lineno, line) ->
82          not (Str.string_match blanks_and_comments line 0)) lines in
83
84   (* Convert to key, value pairs. *)
85   List.map (
86     fun (lineno, line) ->
87       let key, value = ExtString.String.split line " " in
88       lineno, trim key, trim value
89   ) lines