module Neovim.Util (
withCustomEnvironment,
whenM,
unlessM,
oneLineErrorMessage,
) where
import Control.Monad (forM, forM_, when, unless)
import Control.Monad.Catch (MonadMask, bracket)
import Neovim.Context
import System.SetEnv
import System.Environment
import qualified Text.PrettyPrint.ANSI.Leijen as P
withCustomEnvironment :: (MonadMask io, MonadIO io)
=> [(String, Maybe String)] -> io a -> io a
withCustomEnvironment modifiedEnvironment action =
bracket saveAndSet unset (const action)
where
saveAndSet = do
preservedValues <- forM modifiedEnvironment $ \(var, val) -> liftIO $ do
old <- lookupEnv var
maybe (unsetEnv var) (setEnv var) val
return (var, old)
return preservedValues
unset preservedValues = forM_ preservedValues $ \(var, val) -> liftIO $
maybe (unsetEnv var) (setEnv var) val
whenM :: (Monad m) => m Bool -> m () -> m ()
whenM mp a = mp >>= \p -> when p a
unlessM :: (Monad m) => m Bool -> m () -> m ()
unlessM mp a = mp >>= \p -> unless p a
oneLineErrorMessage :: P.Doc -> String
oneLineErrorMessage d = case lines $ P.displayS (P.renderCompact d) "" of
(x:_) -> x
[] -> ""