gdritter repos hanzo / 6494ec8
add transformers instances Getty Ritter 5 years ago
2 changed file(s) with 35 addition(s) and 15 deletion(s). Collapse all Expand all
11 name: hanzo
22 version: 0.1.0.0
3 -- synopsis:
3 synopsis: Simple convenient wrappers for logic around @main@
44 -- description:
55 license: BSD3
6 author: Getty Ritter <gettylefou@gmail.com>
7 maintainer: Getty Ritter <gettylefou@gmail.com>
6 author: Getty Ritter <hanzo@infinitenegativeutility.com
7 maintainer: Getty Ritter <hanzo@infinitenegativeutility.com>
88 copyright: @2019 Getty Ritter
99 -- category:
1010 build-type: Simple
1414 hs-source-dirs: src
1515 ghc-options: -Wall
1616 build-depends: base >=4.7 && <5
17 , transformers
1718 default-language: Haskell2010
1819 exposed-modules: Hanzo
88 ) where
99
1010 import qualified Control.Exception as Exn
11 import qualified Control.Monad.Trans.Except as Except
1112 import qualified System.Environment as Env
1213 import qualified System.Exit as Exit
1314 import qualified System.IO as IO
1415
16 -- | The 'Mainable' class represents computations which can be
17 -- encapsulated as the 'main' function of a program.
1518 class Mainable k where
1619 main :: k -> IO ()
1720
21 guardExceptions :: IO a -> IO a
22 guardExceptions action = do
23 result <- Exn.try action
24 case result of
25 Left (e :: Exn.SomeException) -> do
26 IO.hPutStrLn IO.stderr (Exn.displayException e)
27 Exit.exitWith (Exit.ExitFailure 1)
28 Right x -> pure x
29
1830 instance Termination r => Mainable (IO r) where
1931 main action = do
20 exn <- Exn.try action
32 r <- guardExceptions action
33 code <- report r
34 Exit.exitWith code
35
36 instance Termination r => Mainable (Except.ExceptT String IO r) where
37 main action = do
38 exn <- guardExceptions (Except.runExceptT action)
2139 case exn of
22 Left (e :: Exn.SomeException) -> do
23 IO.hPutStrLn IO.stderr (Exn.displayException e)
40 Left err -> do
41 IO.hPutStrLn IO.stderr err
42 Exit.exitWith (Exit.ExitFailure 1)
2443 Right r -> do
2544 code <- report r
2645 Exit.exitWith code
2746
28 instance Termination r => Mainable ([String] -> IO r) where
47 instance Mainable k => Mainable ([String] -> k) where
2948 main action = do
3049 args <- Env.getArgs
31 exn <- Exn.try (action args)
32 case exn of
33 Left (e :: Exn.SomeException) -> do
34 IO.hPutStrLn IO.stderr (Exn.displayException e)
35 Right r -> do
36 code <- report r
37 Exit.exitWith code
50 let rest = action args
51 main rest
3852
39
53 -- | The 'Termination' class represents values which can be returned
54 -- from a 'Main' function which might represent success or failure.
4055 class Termination t where
4156 report :: t -> IO Exit.ExitCode
4257
4358 instance Termination () where
4459 report _ = pure Exit.ExitSuccess
60
61 instance Termination Bool where
62 report True = pure Exit.ExitSuccess
63 report False = pure (Exit.ExitFailure 1)
4564
4665 instance Termination Exit.ExitCode where
4766 report x = pure x