1 {-# LANGUAGE FlexibleContexts #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# LANGUAGE MultiParamTypeClasses #-}
4 {-# LANGUAGE OverloadedStrings #-}
5 {-# OPTIONS_GHC -fno-warn-orphans #-}
6 module Hcompta.CLI.Write where
8 import Control.Monad (Monad(..), when)
11 import Data.Foldable (Foldable, forM_)
12 import Data.List (concat)
13 import Data.Maybe (Maybe(..))
14 import Data.Ord (Ord(..))
15 import Data.String (String)
16 import Prelude (($), Bounded(..), IO)
17 import qualified System.Console.ANSI as ANSI
18 import System.Exit (exitWith, ExitCode(..))
19 import qualified System.IO as IO
20 import Text.Show (Show)
22 import qualified Hcompta.CLI.Context as C
23 import qualified Hcompta.CLI.Lang as Lang
24 import Hcompta.Lib.Leijen ((<>))
25 import qualified Hcompta.Lib.Leijen as W
27 with_color :: C.Context -> IO.Handle -> IO Bool
30 Nothing -> IO.hIsTerminalDevice h
33 debug :: C.Context -> String -> IO ()
36 v | v >= C.Verbosity_Debug -> do
37 color <- with_color c IO.stderr
38 when color $ ANSI.hSetSGR IO.stderr
39 [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Magenta]
40 W.hPutDoc IO.stderr $ C.translate c Lang.Write_Debug
41 when color $ ANSI.hSetSGR IO.stderr [ANSI.Reset]
42 IO.hPutStr IO.stderr $ concat [": ", msg, "\n"]
45 error :: Lang.Translate msg W.Doc => C.Context -> msg -> IO ()
48 v | v >= C.Verbosity_Error -> do
49 color <- with_color c IO.stderr
50 when color $ ANSI.hSetSGR IO.stderr
51 [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Red]
52 W.hPutDoc IO.stderr $ C.translate c Lang.Write_Error
53 when color $ ANSI.hSetSGR IO.stderr [ANSI.Reset]
55 W.string ":" <> W.space <> C.translate c msg <> W.line
58 fatal :: Lang.Translate msg W.Doc => C.Context -> msg -> IO a
61 exitWith $ ExitFailure 1
63 fatals :: Foldable f => Lang.Translate msg W.Doc => C.Context -> f msg -> IO a
66 exitWith $ ExitFailure 1
74 { style_pretty :: Bool
84 write :: C.Context -> Style -> [(Mode, IO.FilePath)] -> W.Doc -> IO ()
85 write context sty files doc = do
88 then W.renderPretty False 1.0 maxBound doc
89 else W.renderCompact False doc
92 then W.renderPretty True 1.0 maxBound doc
93 else W.renderCompact True doc
95 color <- with_color context h
97 True -> W.displayIO h out_colored
98 False -> W.displayIO h out
99 Data.Foldable.forM_ files $ \(mode, path) ->
105 Mode_Over -> IO.WriteMode
106 Mode_Append -> IO.AppendMode)