blob: c0b0bc09eebfb36c366747e11d20e583df63b1bf (
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
67
68
69
70
71
72
73
74
75
76
77
78
79
|
{-# LANGUAGE OverloadedStrings #-}
module Config
( configUsage
, Config(..)
, getConfig
) where
import Data.Maybe (catMaybes, isJust)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Control.Monad (guard)
import System.Directory (doesFileExist)
import Model.URL
configUsage :: Text
configUsage =
T.intercalate
"\n"
[ T.concat
[ "Please provide an url for leboncoin in the file named: "
, T.pack configPath
]
, "url = http://…"
]
configPath :: FilePath
configPath = "conf"
data Config = Config
{ url :: URL
} deriving (Eq, Read, Show)
getConfig :: IO (Maybe Config)
getConfig = do
exists <- doesFileExist configPath
if exists
then
configFromFile <$> T.readFile configPath
else
return Nothing
configFromFile :: Text -> Maybe Config
configFromFile =
configFromMap
. M.fromList
. catMaybes
. map lineConfig
. filter (not . T.null)
. map T.strip
. T.lines
configFromMap :: Map Text Text -> Maybe Config
configFromMap map = do
url <- M.lookup "url" map
return $ Config { url = url }
lineConfig :: Text -> Maybe (Text, Text)
lineConfig line = do
(key, value) <- keyValue line
guard (T.length key > 0)
return (key, value)
keyValue :: Text -> Maybe (Text, Text)
keyValue line =
let sep = '='
in if isJust (T.find (== sep) line)
then
let key = T.takeWhile (/= sep) line
value = T.drop 1 . T.dropWhile (/= sep) $ line
in Just (T.strip key, T.strip value)
else
Nothing
|