summaryrefslogtreecommitdiff
path: root/src/Config.hs
blob: 7f5895ccb94d13bd68aaf1041e5bdc43effc193f (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module Config (
    Config(..),
    findConfig,
    parseConfig,
) where

import Control.Monad.Combinators

import Data.ByteString.Lazy qualified as BS
import Data.Text qualified as T
import Data.YAML

import System.Directory
import System.Exit
import System.FilePath
import System.FilePath.Glob

data Config = Config
    { configTool :: Maybe FilePath
    , configTests :: [Pattern]
    }
    deriving (Show)

instance Semigroup Config where
    a <> b = Config
        { configTool = maybe (configTool b) Just (configTool a)
        , configTests = configTests a ++ configTests b
        }

instance Monoid Config where
    mempty = Config
        { configTool = Nothing
        , configTests = []
        }

instance FromYAML Config where
    parseYAML = withMap "Config" $ \m -> Config
        <$> (fmap T.unpack <$> m .:? "tool")
        <*> (map (compile . T.unpack) <$> foldr1 (<|>)
                [ fmap (:[]) (m .: "tests") -- single pattern
                , m .:? "tests" .!= []      -- list of patterns
                ]
            )

findConfig :: IO (Maybe FilePath)
findConfig = go "."
  where
    name = "erebos-tester.yaml"
    go path = do
        doesFileExist (path </> name) >>= \case
            True -> return $ Just $ path </> name
            False -> doesDirectoryExist (path </> "..") >>= \case
                True -> do
                    parent <- canonicalizePath $ path </> ".."
                    if parent /= path then go parent
                                      else return Nothing
                False -> return Nothing

parseConfig :: FilePath -> IO Config
parseConfig path = do
    contents <- BS.readFile path
    case decode1 contents of
        Left (pos, err) -> do
            putStr $ prettyPosWithSource pos contents err
            exitFailure
        Right conf -> return conf