{-# LANGUAGE NoImplicitPrelude #-}

{-|
Module      : Headroom.Command.Utils
Description : Shared code for individual command handlers
Copyright   : (c) 2019-2020 Vaclav Svejcar
License     : BSD-3-Clause
Maintainer  : vaclav.svejcar@gmail.com
Stability   : experimental
Portability : POSIX

Contains shared code common to all command handlers.
-}

module Headroom.Command.Utils
  ( bootstrap
  )
where

import           RIO

-- | Bootstraps /RIO/ application using provided environment data and flag
-- whether to run in debug mode.
bootstrap :: (LogFunc -> IO env)
          -- ^ function returning environment data
          -> Bool
          -- ^ whether to run in debug mode
          -> RIO env a
          -- ^ /RIO/ application to execute
          -> IO a
          -- ^ execution result
bootstrap :: (LogFunc -> IO env) -> Bool -> RIO env a -> IO a
bootstrap LogFunc -> IO env
getEnv Bool
isDebug RIO env a
logic = do
  LogOptions
logOptions <- Handle -> Bool -> IO LogOptions
forall (m :: * -> *). MonadIO m => Handle -> Bool -> m LogOptions
logOptionsHandle Handle
stderr Bool
isDebug
  let logOptions' :: LogOptions
logOptions' = Bool -> LogOptions -> LogOptions
setLogUseLoc Bool
False LogOptions
logOptions
  LogOptions -> (LogFunc -> IO a) -> IO a
forall (m :: * -> *) a.
MonadUnliftIO m =>
LogOptions -> (LogFunc -> m a) -> m a
withLogFunc LogOptions
logOptions' ((LogFunc -> IO a) -> IO a) -> (LogFunc -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \LogFunc
logFunc -> do
    env
env <- IO env -> IO env
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO env -> IO env) -> IO env -> IO env
forall a b. (a -> b) -> a -> b
$ LogFunc -> IO env
getEnv LogFunc
logFunc
    env -> RIO env a -> IO a
forall (m :: * -> *) env a. MonadIO m => env -> RIO env a -> m a
runRIO env
env RIO env a
logic