never executed always true always false
1 module CommandLine.InfoFormatter
2 ( ToConsole(..), Loggable(..)
3 , onInfo, approve
4 , ExecuteMode(..), init, done
5 ) where
6
7 import Prelude hiding (init, putStrLn)
8
9 import CommandLine.World (World)
10 import qualified CommandLine.World as World
11 import Control.Monad.State
12 import Data.Text (Text)
13 import qualified Data.Text.Encoding as T
14 import qualified Data.Aeson as Aeson
15 import qualified Data.ByteString.Char8 as B
16 import qualified Data.ByteString.Lazy.Char8 as LB
17 import qualified Data.Aeson.Encoding.Internal as AesonInternal
18
19
20 class ToConsole a where
21 toConsole :: a -> Text
22
23
24 class ToConsole a => Loggable a where
25 jsonInfoMessage :: a -> Maybe Aeson.Encoding
26
27
28 onInfo :: (World m, Loggable info) => ExecuteMode -> info -> StateT Bool m ()
29 onInfo mode info =
30 case mode of
31 ForMachine ->
32 maybe (lift $ return ()) json $ jsonInfoMessage info
33
34 ForHuman usingStdout ->
35 lift $ putStrLn' usingStdout (toConsole info)
36
37
38 approve :: (World m, ToConsole prompt) => ExecuteMode -> Bool -> prompt -> m Bool
39 approve mode autoYes prompt =
40 case autoYes of
41 True -> return True
42
43 False ->
44 case mode of
45 ForMachine -> return False
46
47 ForHuman usingStdout ->
48 putStrLn' usingStdout (toConsole prompt) *> World.getYesOrNo
49
50
51 data ExecuteMode
52 = ForMachine
53 | ForHuman { _usingStdout :: Bool }
54
55
56 init :: World m => ExecuteMode -> (m (), Bool)
57 init ForMachine = (World.putStr "[", False)
58 init (ForHuman _) = (return (), undefined)
59
60
61 done :: World m => ExecuteMode -> Bool -> m ()
62 done ForMachine _ = World.putStrLn "]"
63 done (ForHuman _) _ = return ()
64
65
66 putStrLn' :: World m => Bool -> Text -> m ()
67 putStrLn' usingStdout =
68 -- we log to stdout unless it is being used for file output (in that case, we log to stderr)
69 case usingStdout of
70 True -> World.putStrLnStderr
71 False -> World.putStrLn
72
73
74 json :: World m => Aeson.Encoding -> StateT Bool m ()
75 json jsvalue =
76 do
77 printComma <- get
78 when printComma (lift $ World.putStr ",")
79 lift $ World.putStrLn $ T.decodeUtf8 $ B.concat $ LB.toChunks $ AesonInternal.encodingToLazyByteString jsvalue
80 put True