{-# LANGUAGE OverloadedStrings #-}
module DarcsWeb.Config
( parseConfigFile
, CfgMap
, cfgLookup
, cfgLookupDefault
) where
import Data.Char (isSpace)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
type CfgMap = Map String String
-- | Parse a simple key = value config file.
-- Blank lines and lines starting with # are ignored.
parseConfigFile :: FilePath -> IO CfgMap
parseConfigFile path = do
contents <- readFile path
let ls = filter meaningful (lines contents)
return $ Map.fromList (map parseLine ls)
where
meaningful l =
let stripped = dropWhile isSpace l
in not (null stripped) && head stripped /= '#'
parseLine l =
case break (== '=') l of
(key, '=':val) -> (trim key, trim val)
(key, _) -> (trim key, "")
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
cfgLookup :: String -> CfgMap -> Maybe String
cfgLookup = Map.lookup
cfgLookupDefault :: String -> String -> CfgMap -> String
cfgLookupDefault key def m = maybe def id (Map.lookup key m)