File: misc.ml

package info (click to toggle)
misery 0.2-1.1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 380 kB
  • ctags: 298
  • sloc: ml: 1,295; xml: 180; makefile: 94
file content (54 lines) | stat: -rw-r--r-- 1,469 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
(* Miscellaneous functions. *)

let flag_verbose = ref false

let get_root_directory () =
  try
    Sys.getenv "ACCOUNTS_ROOT"
  with Not_found -> Sys.getcwd ()

let fail msg =
  prerr_endline msg;
  exit 1

let open_config_file leafname =
  let path = (get_root_directory ()) ^ "/config/" ^ leafname in
  try
    open_in path
  with Sys_error msg ->
    fail ("Error whilst opening config file " ^ path ^ ":\n  " ^ msg)

let open_config_file_fail_ok leafname =
  let path = (get_root_directory ()) ^ "/config/" ^ leafname in
  try
    open_in path
  with Sys_error msg -> raise Not_found

let round amount = (float_of_int (truncate (amount *. 100.0))) /. 100.0
let format_money sum =
  (* Note: don't use just "sum / 100" to get the minus sign, because
     when sum is zero, any minus won't appear.  *)
  let s = Printf.sprintf "%d.%02d" (abs (sum / 100)) (abs (sum mod 100)) in
    if sum < 0 then "-" ^ s else s

let verbose str =
  if !flag_verbose then print_endline str
                   else ()

let iter_files dir f =
  let path = (get_root_directory ()) ^ "/" ^ dir in
  let dir = Unix.opendir path in
  try
    while true do
      let name = Unix.readdir dir in
        if String.get name 0 <> '.' then
        begin
          verbose ("iter_initial_files: name=" ^ name);
          let channel = open_in (path ^ "/" ^ name) in
            (f name channel; close_in channel)
        end
        else ()
    done
  with End_of_file ->
    Unix.closedir dir