-- Copyright 2023 Lennart Augustsson-- See LICENSE file for full license.module System.Environment( getArgs, getProgName, withArgs, lookupEnv, getEnv, getEnvironment, setEnv, unsetEnv, getExecutablePath, ) whereimport qualified Prelude(); import MiniPreludeimport Primitivesimport Control.Exception(throwIO)import Data.Bifunctor(second)import Data.List(span)import Foreign.C.Errorimport Foreign.C.Stringimport Foreign.Marshal.Allocimport Foreign.Marshal.Arrayimport Foreign.Ptrimport System.IOimport System.IO.Error-- primArgRef returns an array containing a list of strings.-- The first element is the program name, the rest are the arguments.getArgs :: IO [String]getArgs = do aa <- primGetArgRef as <- primArrRead aa 0 return $ tail as -- drop program namegetProgName :: IO StringgetProgName = do aa <- primGetArgRef as <- primArrRead aa 0 return $ head as -- get program namewithArgs :: forall a . [String] -> IO a -> IO awithArgs as ioa = do aa <- primGetArgRef old <- primArrRead aa 0 primArrWrite aa 0 $ head old : as -- keep program name a <- ioa primArrWrite aa 0 old return aforeign import ccall "getenv" c_getenv :: CString -> IO CStringlookupEnv :: String -> IO (Maybe String)lookupEnv var = do cptr <- withCAString var c_getenv if cptr == nullPtr then return Nothing else Just <$> peekCAString cptrgetEnv :: String -> IO StringgetEnv var = do mval <- lookupEnv var case mval of Nothing -> throwIO (mkIOError NoSuchThing "getEnv" Nothing (Just var)) Just val -> return valforeign import capi "unistd.h value environ" c_environ :: Ptr CStringgetEnvironment :: IO [(String, String)]getEnvironment = do cstrs <- peekArray0 nullPtr c_environ strs <- mapM peekCAString cstrs let splitEq = second (drop 1) . span (/= '=') return $ map splitEq strssetEnv :: String -> String -> IO ()setEnv key value | null value = unsetEnv key | otherwise = do chkKey "setEnv" key; setEnv' key valuechkKey :: String -> String -> IO ()chkKey msg key | null key || '=' `elem` key = throwIO (mkIOError InvalidArgument msg Nothing Nothing) | otherwise = return ()foreign import ccall "setenv" c_setenv :: CString -> CString -> Int -> IO IntsetEnv' :: String -> String -> IO ()setEnv' key value = withCAString key $ \ ckey -> withCAString value $ \ cvalue -> throwErrnoIfMinus1_ "setenv" $ c_setenv ckey cvalue 1foreign import ccall "unsetenv" c_unsetenv :: CString -> IO IntunsetEnv :: String -> IO ()unsetEnv key = do chkKey "unsetEnv" key withCAString key $ \ ckey -> throwErrnoIfMinus1_ "unsetEnv" $ c_unsetenv ckeyforeign import ccall get_executable_path :: IO CStringgetExecutablePath :: IO FilePathgetExecutablePath = do p <- throwErrnoIfNull "get_executable_path" get_executable_path s <- peekCAString p free p return s