module System.Posix.Env.ByteString (
getEnv
, getEnvDefault
, getEnvironmentPrim
, getEnvironment
, putEnv
, setEnv
, unsetEnv
, getArgs
) where
import Foreign
import Foreign.C
import Control.Monad ( liftM )
import Data.Maybe ( fromMaybe )
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Data.ByteString (ByteString)
getEnv :: ByteString -> IO (Maybe ByteString)
getEnv name = do
litstring <- B.useAsCString name c_getenv
if litstring /= nullPtr
then liftM Just $ B.packCString litstring
else return Nothing
getEnvDefault :: ByteString -> ByteString -> IO ByteString
getEnvDefault name fallback = liftM (fromMaybe fallback) (getEnv name)
foreign import ccall unsafe "getenv"
c_getenv :: CString -> IO CString
getEnvironmentPrim :: IO [ByteString]
getEnvironmentPrim = do
c_environ <- getCEnviron
arr <- peekArray0 nullPtr c_environ
mapM B.packCString arr
getCEnviron :: IO (Ptr CString)
getCEnviron = peek c_environ_p
foreign import ccall unsafe "&environ"
c_environ_p :: Ptr (Ptr CString)
getEnvironment :: IO [(ByteString,ByteString)]
getEnvironment = do
env <- getEnvironmentPrim
return $ map (dropEq.(BC.break ((==) '='))) env
where
dropEq (x,y)
| BC.head y == '=' = (x,B.tail y)
| otherwise = error $ "getEnvironment: insane variable " ++ BC.unpack x
unsetEnv :: ByteString -> IO ()
unsetEnv name = B.useAsCString name $ \ s ->
throwErrnoIfMinus1_ "unsetenv" (c_unsetenv s)
foreign import ccall unsafe "__hsunix_unsetenv"
c_unsetenv :: CString -> IO CInt
putEnv :: ByteString -> IO ()
putEnv keyvalue = B.useAsCString keyvalue $ \s ->
throwErrnoIfMinus1_ "putenv" (c_putenv s)
foreign import ccall unsafe "putenv"
c_putenv :: CString -> IO CInt
setEnv :: ByteString -> ByteString -> Bool -> IO ()
setEnv key value ovrwrt = do
B.useAsCString key $ \ keyP ->
B.useAsCString value $ \ valueP ->
throwErrnoIfMinus1_ "setenv" $
c_setenv keyP valueP (fromIntegral (fromEnum ovrwrt))
foreign import ccall unsafe "setenv"
c_setenv :: CString -> CString -> CInt -> IO CInt
getArgs :: IO [ByteString]
getArgs =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
getProgArgv p_argc p_argv
p <- fromIntegral `liftM` peek p_argc
argv <- peek p_argv
peekArray (p 1) (advancePtr argv 1) >>= mapM B.packCString
foreign import ccall unsafe "getProgArgv"
getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()