[project @ 2001-08-17 12:50:34 by simonmar]
[ghc-base.git] / System / Environment.hs
1 -----------------------------------------------------------------------------
2 -- 
3 -- Module      :  System.Environment
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/core/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- $Id: Environment.hs,v 1.2 2001/08/17 12:50:34 simonmar Exp $
12 --
13 -- Miscellaneous information about the system environment.
14 --
15 -----------------------------------------------------------------------------
16
17 module System.Environment
18     ( 
19     , getArgs       -- :: IO [String]
20     , getProgName   -- :: IO String
21     , getEnv        -- :: String -> IO String
22   ) where
23
24 import Prelude
25
26 import Foreign
27 import Foreign.C
28
29 #ifdef __GLASGOW_HASKELL__
30 import GHC.IOBase
31 #endif
32
33 -- ---------------------------------------------------------------------------
34 -- getArgs, getProgName, getEnv
35
36 -- Computation `getArgs' returns a list of the program's command
37 -- line arguments (not including the program name).
38
39 getArgs :: IO [String]
40 getArgs = 
41   alloca $ \ p_argc ->  
42   alloca $ \ p_argv -> do
43    getProgArgv p_argc p_argv
44    p    <- peek p_argc
45    argv <- peek p_argv
46    peekArray (p - 1) (advancePtr argv 1) >>= mapM peekCString
47    
48    
49 foreign import "getProgArgv" getProgArgv :: Ptr Int -> Ptr (Ptr CString) -> IO ()
50
51 -- Computation `getProgName' returns the name of the program
52 -- as it was invoked.
53
54 getProgName :: IO String
55 getProgName = 
56   alloca $ \ p_argc ->
57   alloca $ \ p_argv -> do
58      getProgArgv p_argc p_argv
59      argv <- peek p_argv
60      unpackProgName argv
61   
62 unpackProgName  :: Ptr (Ptr CChar) -> IO String   -- argv[0]
63 unpackProgName argv = do 
64   s <- peekElemOff argv 0 >>= peekCString
65   return (de_slash "" s)
66   where
67     -- re-start accumulating at every '/'
68     de_slash :: String -> String -> String
69     de_slash  acc []       = reverse acc
70     de_slash _acc ('/':xs) = de_slash []      xs
71     de_slash  acc (x:xs)   = de_slash (x:acc) xs
72
73 -- Computation `getEnv var' returns the value
74 -- of the environment variable {\em var}.  
75
76 -- This computation may fail with
77 --    NoSuchThing: The environment variable does not exist.
78
79 getEnv :: String -> IO String
80 getEnv name =
81     withCString name $ \s -> do
82       litstring <- c_getenv s
83       if litstring /= nullPtr
84         then peekCString litstring
85         else ioException (IOError Nothing NoSuchThing "getEnv"
86                           "no environment variable" (Just name))
87
88 foreign import ccall "getenv" unsafe 
89    c_getenv :: CString -> IO (Ptr CChar)