[project @ 2001-06-28 14:15:04 by simonmar]
[packages/old-time.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.1 2001/06/28 14:15:04 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 = do
41 argv <- peek prog_argv_label
42 argc <- peek prog_argc_label
43 peekArray (fromIntegral argc - 1) (advancePtr argv 1) >>= mapM peekCString
44
45 foreign label "prog_argv" prog_argv_label :: Ptr (Ptr (Ptr CChar))
46 foreign label "prog_argc" prog_argc_label :: Ptr CInt
47
48 -- Computation `getProgName' returns the name of the program
49 -- as it was invoked.
50
51 getProgName :: IO String
52 getProgName = do
53 argv <- peek prog_argv_label
54 unpackProgName argv
55
56 unpackProgName :: Ptr (Ptr CChar) -> IO String -- argv[0]
57 unpackProgName argv = do
58 s <- peekElemOff argv 0 >>= peekCString
59 return (de_slash "" s)
60 where
61 -- re-start accumulating at every '/'
62 de_slash :: String -> String -> String
63 de_slash acc [] = reverse acc
64 de_slash _acc ('/':xs) = de_slash [] xs
65 de_slash acc (x:xs) = de_slash (x:acc) xs
66
67 -- Computation `getEnv var' returns the value
68 -- of the environment variable {\em var}.
69
70 -- This computation may fail with
71 -- NoSuchThing: The environment variable does not exist.
72
73 getEnv :: String -> IO String
74 getEnv name =
75 withUnsafeCString name $ \s -> do
76 litstring <- c_getenv s
77 if litstring /= nullPtr
78 then peekCString litstring
79 else ioException (IOError Nothing NoSuchThing "getEnv"
80 "no environment variable" (Just name))
81
82 foreign import ccall "getenv" unsafe
83 c_getenv :: UnsafeCString -> IO (Ptr CChar)