1 % Copyright (C) 2003 David Roundy
3 % This program is free software; you can redistribute it and/or modify
4 % it under the terms of the GNU General Public License as published by
5 % the Free Software Foundation; either version 2, or (at your option)
8 % This program is distributed in the hope that it will be useful,
9 % but WITHOUT ANY WARRANTY; without even the implied warranty of
10 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 % GNU General Public License for more details.
13 % You should have received a copy of the GNU General Public License
14 % along with this program; see the file COPYING. If not, write to
15 % the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16 % Boston, MA 02110-1301, USA.
20 {-# OPTIONS_GHC -cpp -fffi -fglasgow-exts #-}
21 {-# LANGUAGE CPP, ForeignFunctionInterface #-}
22 -- , DeriveDataTypeable #-}
24 module Exec ( exec, exec_interactive,
26 Redirects, Redirect(..),
30 import Data.Typeable ( Typeable )
33 import Control.Exception ( bracket )
34 import System.Posix.Env ( setEnv, getEnv, unsetEnv )
35 import System.Posix.IO ( queryFdOption, setFdOption, FdOption(..), stdInput )
36 import System.IO ( stdin )
38 import Control.Exception ( catchJust, Exception(IOException) )
39 -- WARNING: isInfixOf is not present in ghc 6.4.2!
40 import Data.List ( isInfixOf )
43 import System.Exit ( ExitCode (..) )
44 import System.Cmd ( system )
45 import System.IO ( IOMode(..), openBinaryFile, stdout )
46 import System.Process ( runProcess, terminateProcess, waitForProcess )
47 import GHC.Handle ( hDuplicate )
48 -- urgh. hDuplicate isn't available from a standard place.
49 import Control.Exception ( bracketOnError )
51 import Darcs.Global ( whenDebugMode )
52 import Darcs.Progress ( withoutProgress )
55 A redirection is a three-tuple of values (in, out, err).
56 The most common values are:
59 Null /dev/null on Unix, NUL on Windows
60 File open a file for reading or writing
62 There is also the value Stdout, which is only meaningful for
63 redirection of errors, and is performed AFTER stdout is
64 redirected so that output and errors mix together. StdIn and
65 StdErr could be added as well if they are useful.
67 NOTE: Lots of care must be taken when redirecting stdin, stdout
68 and stderr to one of EACH OTHER, since the ORDER in which they
69 are changed have a significant effect on the result.
72 type Redirects = (Redirect, Redirect, Redirect)
73 data Redirect = AsIs | Null | File FilePath
78 ExecException is thrown by exec if any system call fails,
79 for example because the executable we're trying to run
82 -- ExecException cmd args redirecs errorDesc
83 data ExecException = ExecException String [String] Redirects String
84 deriving (Typeable,Show)
91 _dev_null = "/dev/null"
95 We use System.Process, which does the necessary quoting
96 and redirection for us behind the scenes.
99 exec :: String -> [String] -> Redirects -> IO ExitCode
100 exec cmd args (inp,out,err) = withoutProgress $ do
101 h_stdin <- redirect inp ReadMode
102 h_stdout <- redirect out WriteMode
103 h_stderr <- redirect err WriteMode
104 -- putStrLn (unwords (cmd:args ++ map show [inp,out,err]))
105 withExit127 $ bracketOnError
106 (do whenDebugMode $ putStrLn $ unwords $ cmd:args ++ ["; #"] ++ map show [inp,out,err]
107 runProcess cmd args Nothing Nothing h_stdin h_stdout h_stderr)
111 redirect AsIs _ = return Nothing
112 redirect Null mode = Just `fmap` openBinaryFile _dev_null mode
113 redirect (File "/dev/null") mode = redirect Null mode
114 redirect (File f) mode = Just `fmap` openBinaryFile f mode
115 redirect Stdout _ = Just `fmap` hDuplicate stdout
116 -- hDuplicate stdout rather than passing stdout itself,
117 -- because runProcess closes the Handles we pass it.
119 exec_interactive :: String -> String -> IO ExitCode
123 This should handle arbitrary commands interpreted by the shell on Unix since
124 that's what people expect. But we don't want to allow the shell to interpret
125 the argument in any way, so we set an environment variable and call
126 cmd "$DARCS_ARGUMENT"
128 exec_interactive cmd arg = withoutProgress $ do
129 let var = "DARCS_ARGUMENT"
130 stdin `seq` return ()
131 withoutNonBlock $ bracket
132 (do oldval <- getEnv var
137 Nothing -> unsetEnv var
138 Just val -> setEnv var val True)
139 (\_ -> withExit127 $ system $ cmd++" \"$"++var++"\"")
143 exec_interactive cmd arg = withoutProgress $ do
144 system $ cmd ++ " " ++ arg
147 withoutNonBlock :: IO a -> IO a
151 Do IO without NonBlockingRead on stdInput.
153 This is needed when running unsuspecting external commands with interactive
154 mode - if read from terminal is non-blocking also write to terminal is
158 do nb <- queryFdOption stdInput NonBlockingRead
161 (do setFdOption stdInput NonBlockingRead False)
162 (\_ -> setFdOption stdInput NonBlockingRead True)
166 withoutNonBlock x = do x
170 Ensure that we exit 127 if the thing we are trying to run does not exist
171 (Only needed under Windows)
173 withExit127 :: IO ExitCode -> IO ExitCode
175 withExit127 a = catchJust notFoundError a (const $ return $ ExitFailure 127)
177 notFoundError :: Exception -> Maybe ()
178 notFoundError (IOException e) | "runProcess: does not exist" `isInfixOf` show e = Just ()
179 notFoundError _ = Nothing