summaryrefslogtreecommitdiff
path: root/SimpleConfig.hs
blob: 9ffe7b1893cce24f2a0e723d5e8a859c01edc830 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module SimpleConfig where

import qualified Data.Map as Map
import Data.Map ( Map )
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad

newtype SimpleConfig = SimpleConfig
    { configMap :: Map String (Map String String)
    }
 deriving (Eq,Show)

load :: FilePath -> IO SimpleConfig
load path = parse `fmap` readFile path

parse :: String -> SimpleConfig
parse txt = SimpleConfig $ Map.fromList ss
 where
    ls = lines txt
    cs = filter (not . null) $ map (takeWhile (/='#')) ls
    css = groupBy (\_ s -> take 1 s /= "[") cs
    ss = mapMaybe (\ds -> do
                        brkt <- listToMaybe $ take 1 ds
                        opn <- listToMaybe $ take 1 brkt
                        guard $ opn == '['
                        let sec = init (drop 1 brkt)
                        return (sec, Map.fromList $ map parseItem $ drop 1 ds)
                    )
                  css

parseItem txt = (key,val)
 where
    (key,rst) = span (not . isSpace) $ dropWhile isSpace txt
    val = dropWhile isSpace rst