Newer
Older
// Copyright (C) 2019 Yuanle Song <root@emacsos.com>
//
// This file is part of mbackup-for-windows.
//
// mbackup-for-windows is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// mbackup-for-windows is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// mbackup-for-windows. If not, see <http://www.gnu.org/licenses/>.
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
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)