aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/bin/Utils/Prompt.hs
blob: 51b3f0c68fb52be437755fd80255ec1825161ce4 (plain) (blame)
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
-- |
-- Copyright   : (c) 2015 Egor Tensin <Egor.Tensin@gmail.com>
-- License     : MIT
-- Maintainer  : Egor.Tensin@gmail.com
-- Stability   : experimental
-- Portability : portable

module Utils.Prompt
    ( withPrompt
    , withoutPrompt
    ) where

import Control.Monad (void, when)
import Control.Monad.Trans.Class  (lift)
import Control.Monad.Trans.Except (ExceptT)
import Data.Char     (toLower)
import System.IO     (hFlush, stdout)

prompt :: String -> IO String
prompt msg = do
    putStr msg
    hFlush stdout
    getLine

promptYesNo :: String -> IO Bool
promptYesNo msg = do
    response <- map toLower <$> prompt msg
    if response `elem` yeses
        then return True
        else if response `elem` noes
            then return False
            else promptToContinue
  where
    yeses = ["y", "yes"]
    noes = ["n", "no"]

promptToContinue :: IO Bool
promptToContinue = promptYesNo "Continue? (y/n) "

withPrompt :: String -> ExceptT IOError IO a -> ExceptT IOError IO Bool
withPrompt msg m = do
    lift $ do
        putStr msg
        hFlush stdout
    agreed <- lift promptToContinue
    when agreed $ void m
    return agreed

withoutPrompt :: ExceptT IOError IO a -> ExceptT IOError IO Bool
withoutPrompt m = m >> return True