module Data.SConfig
( readConfig
, writeConfig
, getValue
, Config
, Key
, Value
) where
import qualified Data.Map as M
import Data.List
import Data.Maybe (fromJust)
type Key = String
type Value = String
type Config = M.Map Key Value
writeConfig :: Config -> String
writeConfig cfg = concat
$ intersperse "\n"
$ map (\(key,value) -> key ++ "=" ++ value) $ M.toList cfg
readConfig :: String -> Config
readConfig str = foldl readConfigLine M.empty
$ filter (elem '=')
$ concatEscaped
$ filter (\x -> (not $ null x) && (take 1 x) /= "#")
$ lines str
readConfigLine :: Config -> String -> Config
readConfigLine config str = M.insert (filter (/=' ') key) value config
where (key,_:value) = break (=='=') str
concatEscaped :: [String] -> [String]
concatEscaped lines = foldr (\x (a:acc) -> if last x == '\\' then ((init x) ++ a):acc else x:a:acc) [""] lines
getValue :: Key -> M.Map Key Value -> Maybe Value
getValue = M.lookup