module Sound.Sc3.Common.Base.System where

import Control.Exception {- base -}
import Data.Maybe {- base -}
import System.Environment {- base -}

{- | 'getEnv' with error handler to return default value.  This almost works in hugs (IOException should be Exception, the signature can be elided)

> get_env_with_default "undefined_environment_variable" "default"  -- > "default"
-}
get_env_with_default :: String -> String -> IO String
get_env_with_default :: String -> String -> IO String
get_env_with_default String
variableName String
defaultValue =
  forall e a. Exception e => IO a -> (e -> IO a) -> IO a
Control.Exception.catch (String -> IO String
getEnv String
variableName) ((\IOException
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return String
defaultValue) :: IOException -> IO String)

{- | 'getEnvironment' with lookup and default value.

> get_env_default "PATH" "/usr/bin"
-}
get_env_default :: String -> String -> IO String
get_env_default :: String -> String -> IO String
get_env_default String
variableName String
defaultValue = do
  [(String, String)]
env <- IO [(String, String)]
getEnvironment
  forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> Maybe a -> a
fromMaybe String
defaultValue (forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup String
variableName [(String, String)]
env))

{- | 'lookupEnv' with default value.

> lookup_env_default "PATH" "/usr/bin"
-}
lookup_env_default :: String -> String -> IO String
lookup_env_default :: String -> String -> IO String
lookup_env_default String
e String
k = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall a. a -> Maybe a -> a
fromMaybe String
k) (String -> IO (Maybe String)
lookupEnv String
e)