gdritter repos bb8 / master src / BB8 / Config.hs
master

Tree @master (Download .tar.gz)

Config.hs @masterraw · history · blame

{-# LANGUAGE RecordWildCards #-}

module BB8.Config where

import qualified Data.Ini.Config as Ini
import qualified Data.Text.IO as Text
import qualified System.Directory as Sys
import           System.FilePath ((</>))
import qualified System.Exit as Sys

import qualified BB8.Common as BB8
import qualified BB8.Types as Types


defaultConfig :: Types.Config
defaultConfig = Types.Config
  { Types.configSleepAmount   = 30
  , Types.configDBPath        = "safeware.db"
  , Types.configWorkDirectory = "bb8-work"
  }


fileSpec :: Ini.IniParser Types.Config
fileSpec = Ini.section "bb8" $ do
  configSleepAmount   <- Ini.fieldDefOf "sleep amount" Ini.number 30
  configDBPath        <- Ini.fieldDefOf "DB path" Ini.string "safeware.db"
  configWorkDirectory <- Ini.fieldDefOf "work directory" Ini.string "bb8-work"
  return Types.Config { .. }


-- this is always going to look in the current directory for the
-- config file, and if it doesn't find it, it will use a default. It
-- will exit the program with an informative error if there's a
-- problem parsing the config file, though.
getConfig :: IO Types.Config
getConfig = do
  exists <- Sys.doesFileExist "config.ini"
  if not exists
    then do
      BB8.debug "No config file found in cwd; using default values"
      return defaultConfig
    else do
      cwd <- Sys.getCurrentDirectory
      BB8.debug ("Reading config file from " ++ show (cwd </> "config.ini"))
      t <- Text.readFile "config.ini"
      case Ini.parseIniFile t fileSpec of
        Left err -> Sys.die err
        Right x  -> return x