Skip to content
ConfigParser.fs 1.93 KiB
Newer Older
Yuanle Song's avatar
Yuanle Song committed
module Mbackup.ConfigParser

open System
open System.IO
open System.Text.RegularExpressions

open Mbackup.Lib

type WellsConfig(fn: string) =
  let mutable keyValuePairs: Map<string, string> = Map.empty
  do
    let dropEmptyLinesAndComments lines = Seq.filter (fun (line: string) -> not (line.TrimStart().StartsWith("#") || line.TrimEnd().Equals(""))) lines
    let dropQuotesMaybe (value: string) = if value.StartsWith("\"") || value.StartsWith("'") then value.Substring(1, value.Length - 2) else value
    let toKeyValue = Seq.map (fun (line: string) ->
                                let result: string[] = line.Split('=', 2)
                                (result.[0].Trim(), dropQuotesMaybe (result.[1].Trim())))
    let result = File.ReadAllLines(fn)  // file IO can throw Exception
                 |> dropEmptyLinesAndComments
                 |> toKeyValue
                 |> Seq.fold (fun (m: Map<string, string>) (k, v) -> m.Add(k, v)) keyValuePairs
    keyValuePairs <- result
  member this.ConfigFile = fn
  member this.GetStr key =
    let getEnv (varName: string) = Environment.GetEnvironmentVariable varName
    let configKeyToEnvVar (key: string) =
      key.ToUpper().Replace(".", "_").Replace("-", "_")
    match getEnv (configKeyToEnvVar key) with
      | null | "" -> keyValuePairs.TryFind key
      | envValue -> Some envValue
  member this.GetStrDefault key defaultValue =
    match this.GetStr key with
    | None -> defaultValue
    | Some value -> value
Yuanle Song's avatar
Yuanle Song committed
  member this.GetBool key =
    Option.map (fun value -> Regex.IsMatch(value, "^(yes|true|enable|1)$", RegexOptions.IgnoreCase)) (this.GetStr key)
  member this.GetFloat key =
    let value = keyValuePairs.TryGetValue key
    let parseFloat s = try Some (float s) with | _ -> None
    Option.map parseFloat (this.GetStr key)
  member this.GetInt key =
    let value = keyValuePairs.TryGetValue key
    let parseInt s = try Some (int s) with | _ -> None
    Option.map parseInt (this.GetStr key)