{-# LANGUAGE OverloadedStrings #-}
module Vimeta.UI.CommandLine.Config
( Options
, optionsParser
, run
) where
import Control.Monad
import Control.Monad.Except
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as Text
import Options.Applicative
import System.Console.Byline
import System.Exit
import Vimeta.Core
import Prelude
data Options = Options
{ optsKey :: Maybe Text
, optsTagger :: Tagger
}
optionsParser :: Parser Options
optionsParser = Options <$> optional (Text.pack <$> strOption getKey)
<*> pure AtomicParsley
where
getKey = mconcat [ short 'k'
, long "key"
, metavar "KEY"
, help "Set the API key to KEY"
]
run :: Options -> IO ()
run opts = do
let def = defaultConfig (optsTagger opts)
config = case optsKey opts of
Nothing -> def
Just k -> def {configTMDBKey = k}
result <- runExceptT (app opts config)
case result of
Left e -> byline Error e >> exitFailure
Right (Just w) -> byline Warning w
Right Nothing -> return ()
where
byline :: ReportType -> String -> IO ()
byline rt = void . runByline . reportLn rt . text . Text.pack
app :: Options -> Config -> ExceptT String IO (Maybe String)
app opts config = do
filename <- writeConfig config
return $ case optsKey opts of
Just _ -> Nothing
Nothing -> Just (missingKey filename)
where
missingKey = ("please edit the config file and set the API key: " ++)