diff options
author | Joris | 2016-03-16 21:09:44 +0100 |
---|---|---|
committer | Joris | 2016-03-16 22:09:54 +0100 |
commit | c6c01d7c248bca1078285c4afeaa25493e9974b3 (patch) | |
tree | 7b060664b16ffcae25cb62089dfbeed5a0b7c69a /Data/ConfigManager/Reader.hs | |
parent | f2dc23683ceae93135223713e4ca7fa3a12edbea (diff) |
Add import expression
Diffstat (limited to 'Data/ConfigManager/Reader.hs')
-rw-r--r-- | Data/ConfigManager/Reader.hs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/Data/ConfigManager/Reader.hs b/Data/ConfigManager/Reader.hs new file mode 100644 index 0000000..9f4cc3c --- /dev/null +++ b/Data/ConfigManager/Reader.hs @@ -0,0 +1,41 @@ +module Data.ConfigManager.Reader + ( readConfig + ) where + +import Control.Monad (foldM) + +import System.FilePath.Posix (dropFileName, (</>)) + +import qualified Data.HashMap.Strict as M +import Data.Text (Text) +import qualified Data.Text.IO as T + +import Data.ConfigManager.Parser (parseConfig) +import Data.ConfigManager.Expr +import Data.ConfigManager.Config + +readConfig :: FilePath -> IO (Either Text Config) +readConfig path = do + input <- T.readFile path + case parseConfig input of + Left errorMessage -> + return . Left $ errorMessage + Right exprs -> + foldM (go fileDir) (Right emptyConfig) exprs + where fileDir = dropFileName path + emptyConfig = Config $ M.fromList [] + +go :: String -> Either Text Config -> Expr -> IO (Either Text Config) +go _ errorMessage@(Left _) _ = return errorMessage +go fileDir (Right config) expr = + case expr of + Binding name value -> + return . Right . Config $ M.insert name value (hashMap config) + Import path -> do + eitherConfig <- readConfig (fileDir </> path) + case eitherConfig of + Left errorMessage -> + return . Left $ errorMessage + Right importedConfig -> + let unionConfig = (hashMap importedConfig) `M.union` (hashMap config) + in return . Right . Config $ unionConfig |