Repository navigation
Expand file tree
/
Copy pathConfig.hs
More file actions
82 lines (71 loc) · 2.39 KB
/
Copy pathConfig.hs
File metadata and controls
82 lines (71 loc) · 2.39 KB
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
80
81
82
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
module Config
( Config(..)
, TwitchConfig(..)
, DiscordConfig(..)
, GithubConfig(..)
, configFromFile
) where
import Control.Applicative
import Control.Monad
import Data.Either.Extra
import qualified Data.HashMap.Strict as HM
import Data.Ini
import qualified Data.Text as T
import Discord
import Safe
import Text.InterpolatedString.QM
data Config = Config
{ configTwitch :: Maybe TwitchConfig
, configDiscord :: Maybe DiscordConfig
, configGithub :: Maybe GithubConfig
}
newtype GithubConfig = GithubConfig
{ githubApiKey :: T.Text
}
data TwitchConfig = TwitchConfig
{ tcNick :: T.Text
, tcPass :: T.Text
, tcChannel :: T.Text
, tcTwitchClientId :: T.Text
, tcOwner :: T.Text
}
data DiscordConfig = DiscordConfig
{ dcAuthToken :: T.Text
, dcChannels :: [ChannelId]
, dcGuildId :: GuildId
}
hmLookupValue :: T.Text -> HM.HashMap T.Text T.Text -> Either String T.Text
hmLookupValue field ini =
maybeToEither [qms|Cannot find field {field}|] $ HM.lookup field ini
twitchConfigFromHm :: HM.HashMap T.Text T.Text -> Either String TwitchConfig
twitchConfigFromHm ini =
TwitchConfig <$> hmLookupValue "nick" ini <*> hmLookupValue "password" ini <*>
(T.cons '#' <$> hmLookupValue "channel" ini) <*>
hmLookupValue "clientId" ini <*>
hmLookupValue "owner" ini
discordConfigFromHm :: HM.HashMap T.Text T.Text -> Either String DiscordConfig
discordConfigFromHm ini =
DiscordConfig <$> hmLookupValue "authToken" ini <*>
fmap
(map Snowflake)
((maybeToEither "`channels` is not a list of numbers" . readMay . T.unpack) =<<
(hmLookupValue "channel" ini <|> hmLookupValue "channels" ini)) <*>
fmap
Snowflake
((maybeToEither "Guild ID is not a number" . readMay . T.unpack) =<<
hmLookupValue "guildId" ini)
githubConfigFromHm :: HM.HashMap T.Text T.Text -> Either String GithubConfig
githubConfigFromHm ini = GithubConfig <$> hmLookupValue "apiKey" ini
configFromFile :: FilePath -> IO Config
configFromFile filePath = do
ini <- readIniFile filePath
either (ioError . userError) return $
mapLeft ([qms|In file '{filePath}':\ |] <>) $ do
secs <- unIni <$> ini
liftM3
Config
(sequence (twitchConfigFromHm <$> HM.lookup "twitch" secs))
(sequence (discordConfigFromHm <$> HM.lookup "discord" secs))
(sequence (githubConfigFromHm <$> HM.lookup "github" secs))