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 =
  IO String -> (IOException -> IO String) -> IO String
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
Control.Exception.catch (String -> IO String
getEnv String
variableName) ((\IOException
_ -> String -> IO String
forall a. a -> IO a
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
  String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
defaultValue (String -> [(String, String)] -> Maybe String
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 = (Maybe String -> String) -> IO (Maybe String) -> IO String
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
k) (String -> IO (Maybe String)
lookupEnv String
e)