+
+{-|
+'withArgs' @args act@ - while executing action @act@, have 'getArgs'
+return @args@.
+-}
+withArgs :: [String] -> IO a -> IO a
+withArgs xs act = do
+ p <- System.Environment.getProgName
+ withArgv (p:xs) act
+
+{-|
+'withProgName' @name act@ - while executing action @act@,
+have 'getProgName' return @name@.
+-}
+withProgName :: String -> IO a -> IO a
+withProgName nm act = do
+ xs <- System.Environment.getArgs
+ withArgv (nm:xs) act
+
+-- Worker routine which marshals and replaces an argv vector for
+-- the duration of an action.
+
+withArgv :: [String] -> IO a -> IO a
+withArgv new_args act = do
+ pName <- System.Environment.getProgName
+ existing_args <- System.Environment.getArgs
+ bracket (setArgs new_args)
+ (\argv -> do _ <- setArgs (pName:existing_args)
+ freeArgv argv)
+ (const act)
+
+freeArgv :: Ptr CString -> IO ()
+freeArgv argv = do
+ size <- lengthArray0 nullPtr argv
+ sequence_ [peek (argv `advancePtr` i) >>= free | i <- [size, size-1 .. 0]]
+ free argv
+
+setArgs :: [String] -> IO (Ptr CString)
+setArgs argv = do
+ vs <- mapM newCString argv >>= newArray0 nullPtr
+ setArgsPrim (genericLength argv) vs
+ return vs
+
+foreign import ccall unsafe "setProgArgv"
+ setArgsPrim :: CInt -> Ptr CString -> IO ()
+
+-- |'getEnvironment' retrieves the entire environment as a
+-- list of @(key,value)@ pairs.
+--
+-- If an environment entry does not contain an @\'=\'@ character,
+-- the @key@ is the whole entry and the @value@ is the empty string.
+
+getEnvironment :: IO [(String, String)]
+getEnvironment = do
+ pBlock <- getEnvBlock
+ if pBlock == nullPtr then return []
+ else do
+ stuff <- peekArray0 nullPtr pBlock >>= mapM peekCString
+ return (map divvy stuff)
+ where
+ divvy str =
+ case break (=='=') str of
+ (xs,[]) -> (xs,[]) -- don't barf (like Posix.getEnvironment)
+ (name,_:value) -> (name,value)
+
+foreign import ccall unsafe "__hscore_environ"
+ getEnvBlock :: IO (Ptr CString)
+#endif /* __GLASGOW_HASKELL__ */