-- arch-tag: Command utilities main file{-# LANGUAGE CPP #-}{-
Copyright (c) 2004-2011 John Goerzen <jgoerzen@complete.org>
All rights reserved.
For license and copyright information, see the file LICENSE
-}{- |
Module : System.Cmd.Utils
Copyright : Copyright (C) 2004-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <jgoerzen@complete.org>
Stability : provisional
Portability: portable to platforms with POSIX process\/signal tools
Command invocation utilities.
Written by John Goerzen, jgoerzen\@complete.org
Please note: Most of this module is not compatible with Hugs.
Command lines executed will be logged using "System.Log.Logger" at the
DEBUG level. Failure messages will be logged at the WARNING level in addition
to being raised as an exception. Both are logged under
\"System.Cmd.Utils.funcname\" -- for instance,
\"System.Cmd.Utils.safeSystem\". If you wish to suppress these messages
globally, you can simply run:
> updateGlobalLogger "System.Cmd.Utils.safeSystem"
> (setLevel CRITICAL)
See also: 'System.Log.Logger.updateGlobalLogger',
"System.Log.Logger".
It is possible to set up pipelines with these utilities. Example:
> (pid1, x1) <- pipeFrom "ls" ["/etc"]
> (pid2, x2) <- pipeBoth "grep" ["x"] x1
> putStr x2
> ... the grep output is displayed ...
> forceSuccess pid2
> forceSuccess pid1
Remember, when you use the functions that return a String, you must not call
'forceSuccess' until after all data from the String has been consumed. Failure
to wait will cause your program to appear to hang.
Here is an example of the wrong way to do it:
> (pid, x) <- pipeFrom "ls" ["/etc"]
> forceSuccess pid -- Hangs; the called program hasn't terminated yet
> processTheData x
You must instead process the data before calling 'forceSuccess'.
When using the hPipe family of functions, this is probably more obvious.
Most of this module will be incompatible with Windows.
-}moduleSystem.Cmd.Utils(-- * High-Level ToolsPipeHandle(..),safeSystem,#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))forceSuccess,#ifndef __HUGS__posixRawSystem,forkRawSystem,-- ** Piping with lazy stringspipeFrom,pipeLinesFrom,pipeTo,pipeBoth,-- ** Piping with handleshPipeFrom,hPipeTo,hPipeBoth,#endif#endif-- * Low-Level ToolsPipeMode(..),#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__pOpen,pOpen3,pOpen3Raw#endif#endif)where-- FIXME - largely obsoleted by 6.4 - convert to wrappers.importSystem.ExitimportSystem.CmdimportSystem.Log.Logger#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))importSystem.Posix.IOimportSystem.Posix.ProcessimportSystem.Posix.SignalsimportqualifiedSystem.Posix.Signals#endifimportSystem.Posix.TypesimportSystem.IOimportSystem.IO.ErrorimportControl.Concurrent(forkIO)importControl.Exception(finally)dataPipeMode=ReadFromPipe|WriteToPipelogbase::Stringlogbase="System.Cmd.Utils"{- | Return value from 'pipeFrom', 'pipeLinesFrom', 'pipeTo', or
'pipeBoth'. Contains both a ProcessID and the original command that was
executed. If you prefer not to use 'forceSuccess' on the result of one
of these pipe calls, you can use (processID ph), assuming ph is your 'PipeHandle',
as a parameter to 'System.Posix.Process.getProcessStatus'. -}dataPipeHandle=PipeHandle{processID::ProcessID,phCommand::FilePath,phArgs::[String],phCreator::String-- ^ Function that created it}deriving(Eq,Show)#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Like 'pipeFrom', but returns data in lines instead of just a String.
Shortcut for calling lines on the result from 'pipeFrom'.
Note: this function logs as pipeFrom.
Not available on Windows. -}pipeLinesFrom::FilePath->[String]->IO(PipeHandle,[String])pipeLinesFromfpargs=do(pid,c)<-pipeFromfpargsreturn$(pid,linesc)#endif#endiflogRunning::String->FilePath->[String]->IO()logRunningfuncfpargs=debugM(logbase++"."++func)(showCmdfpargs)warnFail::[Char]->FilePath->[String]->[Char]->IOtwarnFailfuncnamefpargsmsg=letm=showCmdfpargs++": "++msgindowarningM(logbase++"."++funcname)mfailm#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Read data from a pipe. Returns a Handle and a 'PipeHandle'.
When done, you must hClose the handle, and then use either 'forceSuccess' or
getProcessStatus on the 'PipeHandle'. Zombies will result otherwise.
This function logs as pipeFrom.
Not available on Windows or with Hugs.
-}hPipeFrom::FilePath->[String]->IO(PipeHandle,Handle)hPipeFromfpargs=dopipepair<-createPipelogRunning"pipeFrom"fpargsletchildstuff=dodupTo(sndpipepair)stdOutputcloseFd(fstpipepair)executeFilefpTrueargsNothingp<-try(forkProcesschildstuff)-- parentpid<-casepofRightx->returnxLefte->warnFail"pipeFrom"fpargs$"Error in fork: "++showecloseFd(sndpipepair)h<-fdToHandle(fstpipepair)return(PipeHandlepidfpargs"pipeFrom",h)#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Read data from a pipe. Returns a lazy string and a 'PipeHandle'.
ONLY AFTER the string has been read completely, You must call either
'System.Posix.Process.getProcessStatus' or 'forceSuccess' on the 'PipeHandle'.
Zombies will result otherwise.
Not available on Windows.
-}pipeFrom::FilePath->[String]->IO(PipeHandle,String)pipeFromfpargs=do(pid,h)<-hPipeFromfpargsc<-hGetContentshreturn(pid,c)#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Write data to a pipe. Returns a 'PipeHandle' and a new Handle to write
to.
When done, you must hClose the handle, and then use either 'forceSuccess' or
getProcessStatus on the 'PipeHandle'. Zombies will result otherwise.
This function logs as pipeTo.
Not available on Windows.
-}hPipeTo::FilePath->[String]->IO(PipeHandle,Handle)hPipeTofpargs=dopipepair<-createPipelogRunning"pipeTo"fpargsletchildstuff=dodupTo(fstpipepair)stdInputcloseFd(sndpipepair)executeFilefpTrueargsNothingp<-try(forkProcesschildstuff)-- parentpid<-casepofRightx->returnxLefte->warnFail"pipeTo"fpargs$"Error in fork: "++showecloseFd(fstpipepair)h<-fdToHandle(sndpipepair)return(PipeHandlepidfpargs"pipeTo",h)#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Write data to a pipe. Returns a ProcessID.
You must call either
'System.Posix.Process.getProcessStatus' or 'forceSuccess' on the ProcessID.
Zombies will result otherwise.
Not available on Windows.
-}pipeTo::FilePath->[String]->String->IOPipeHandlepipeTofpargsmessage=do(pid,h)<-hPipeTofpargsfinally(hPutStrhmessage)(hCloseh)returnpid#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Like a combination of 'hPipeTo' and 'hPipeFrom'; returns
a 3-tuple of ('PipeHandle', Data From Pipe, Data To Pipe).
When done, you must hClose both handles, and then use either 'forceSuccess' or
getProcessStatus on the 'PipeHandle'. Zombies will result otherwise.
Hint: you will usually need to ForkIO a thread to handle one of the Handles;
otherwise, deadlock can result.
This function logs as pipeBoth.
Not available on Windows.
-}hPipeBoth::FilePath->[String]->IO(PipeHandle,Handle,Handle)hPipeBothfpargs=dofrompair<-createPipetopair<-createPipelogRunning"pipeBoth"fpargsletchildstuff=dodupTo(sndfrompair)stdOutputcloseFd(fstfrompair)dupTo(fsttopair)stdInputcloseFd(sndtopair)executeFilefpTrueargsNothingp<-try(forkProcesschildstuff)-- parentpid<-casepofRightx->returnxLefte->warnFail"pipeBoth"fpargs$"Error in fork: "++showecloseFd(sndfrompair)closeFd(fsttopair)fromh<-fdToHandle(fstfrompair)toh<-fdToHandle(sndtopair)return(PipeHandlepidfpargs"pipeBoth",fromh,toh)#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Like a combination of 'pipeTo' and 'pipeFrom'; forks an IO thread
to send data to the piped program, and simultaneously returns its output
stream.
The same note about checking the return status applies here as with 'pipeFrom'.
Not available on Windows. -}pipeBoth::FilePath->[String]->String->IO(PipeHandle,String)pipeBothfpargsmessage=do(pid,fromh,toh)<-hPipeBothfpargsforkIO$finally(hPutStrtohmessage)(hClosetoh)c<-hGetContentsfromhreturn(pid,c)#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__)){- | Uses 'System.Posix.Process.getProcessStatus' to obtain the exit status
of the given process ID. If the process terminated normally, does nothing.
Otherwise, raises an exception with an appropriate error message.
This call will block waiting for the given pid to terminate.
Not available on Windows. -}forceSuccess::PipeHandle->IO()forceSuccess(PipeHandlepidfpargsfuncname)=letwarnfail=warnFailfuncnameindostatus<-getProcessStatusTrueFalsepidcasestatusofNothing->warnfailfpargs$"Got no process status"Just(Exited(ExitSuccess))->return()Just(Exited(ExitFailurefc))->cmdfailedfuncnamefpargsfcJust(Terminatedsig)->warnfailfpargs$"Terminated by signal "++showsigJust(Stoppedsig)->warnfailfpargs$"Stopped by signal "++showsig#endif{- | Invokes the specified command in a subprocess, waiting for the result.
If the command terminated successfully, return normally. Otherwise,
raises a userError with the problem.
Implemented in terms of 'posixRawSystem' where supported, and System.Posix.rawSystem otherwise.
-}safeSystem::FilePath->[String]->IO()safeSystemcommandargs=dodebugM(logbase++".safeSystem")("Running: "++command++" "++(showargs))#if defined(__HUGS__) || defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__)ec<-rawSystemcommandargscaseecofExitSuccess->return()ExitFailurefc->cmdfailed"safeSystem"commandargsfc#elseec<-posixRawSystemcommandargscaseecofExitedExitSuccess->return()Exited(ExitFailurefc)->cmdfailed"safeSystem"commandargsfcTerminateds->cmdsignalled"safeSystem"commandargssStoppeds->cmdsignalled"safeSystem"commandargss#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Invokes the specified command in a subprocess, waiting for the result.
Return the result status. Never raises an exception. Only available
on POSIX platforms.
Like system(3), this command ignores SIGINT and SIGQUIT and blocks SIGCHLD
during its execution.
Logs as System.Cmd.Utils.posixRawSystem -}posixRawSystem::FilePath->[String]->IOProcessStatusposixRawSystemprogramargs=dodebugM(logbase++".posixRawSystem")("Running: "++program++" "++(showargs))oldint<-installHandlersigINTIgnoreNothingoldquit<-installHandlersigQUITIgnoreNothingletsigset=addSignalsigCHLDemptySignalSetoldset<-getSignalMaskblockSignalssigsetchildpid<-forkProcess(childactionoldintoldquitoldset)mps<-getProcessStatusTrueFalsechildpidrestoresignalsoldintoldquitoldsetletretval=casempsofJustx->xNothing->error"Nothing returned from getProcessStatus"debugM(logbase++".posixRawSystem")(program++": exited with "++showretval)returnretvalwherechildactionoldintoldquitoldset=dorestoresignalsoldintoldquitoldsetexecuteFileprogramTrueargsNothingrestoresignalsoldintoldquitoldset=doinstallHandlersigINToldintNothinginstallHandlersigQUIToldquitNothingsetSignalMaskoldset#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Invokes the specified command in a subprocess, without waiting for
the result. Returns the PID of the subprocess -- it is YOUR responsibility
to use getProcessStatus or getAnyProcessStatus on that at some point. Failure
to do so will lead to resource leakage (zombie processes).
This function does nothing with signals. That too is up to you.
Logs as System.Cmd.Utils.forkRawSystem -}forkRawSystem::FilePath->[String]->IOProcessIDforkRawSystemprogramargs=dodebugM(logbase++".forkRawSystem")("Running: "++program++" "++(showargs))forkProcesschildactionwherechildaction=executeFileprogramTrueargsNothing#endif#endifcmdfailed::String->FilePath->[String]->Int->IOacmdfailedfuncnamecommandargsfailcode=doleterrormsg="Command "++command++" "++(showargs)++" failed; exit code "++(showfailcode)lete=userError(errormsg)warningM(logbase++"."++funcname)errormsgioErrore#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__cmdsignalled::String->FilePath->[String]->Signal->IOacmdsignalledfuncnamecommandargsfailcode=doleterrormsg="Command "++command++" "++(showargs)++" failed due to signal "++(showfailcode)lete=userError(errormsg)warningM(logbase++"."++funcname)errormsgioErrore#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Open a pipe to the specified command.
Passes the handle on to the specified function.
The 'PipeMode' specifies what you will be doing. That is, specifing 'ReadFromPipe'
sets up a pipe from stdin, and 'WriteToPipe' sets up a pipe from stdout.
Not available on Windows.
-}pOpen::PipeMode->FilePath->[String]->(Handle->IOa)->IOapOpenpmfpargsfunc=dopipepair<-createPipedebugM(logbase++".pOpen")("Running: "++fp++" "++(showargs))casepmofReadFromPipe->doletcallfunc_=docloseFd(sndpipepair)h<-fdToHandle(fstpipepair)x<-funchhClosehreturn$!xpOpen3Nothing(Just(sndpipepair))Nothingfpargscallfunc(closeFd(fstpipepair))WriteToPipe->doletcallfunc_=docloseFd(fstpipepair)h<-fdToHandle(sndpipepair)x<-funchhClosehreturn$!xpOpen3(Just(fstpipepair))NothingNothingfpargscallfunc(closeFd(sndpipepair))#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Runs a command, redirecting things to pipes.
Not available on Windows.
Note that you may not use the same fd on more than one item. If you
want to redirect stdout and stderr, dup it first.
-}pOpen3::MaybeFd-- ^ Send stdin to this fd->MaybeFd-- ^ Get stdout from this fd->MaybeFd-- ^ Get stderr from this fd->FilePath-- ^ Command to run->[String]-- ^ Command args->(ProcessID->IOa)-- ^ Action to run in parent->IO()-- ^ Action to run in child before execing (if you don't need something, set this to @return ()@) -- IGNORED IN HUGS->IOapOpen3pinpoutperrfpargsfuncchildfunc=dopid<-pOpen3Rawpinpoutperrfpargschildfuncretval<-func$!pidletrv=seqretvalretvalforceSuccess(PipeHandle(seqretvalpid)fpargs"pOpen3")returnrv#endif#endif#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))#ifndef __HUGS__{- | Runs a command, redirecting things to pipes.
Not available on Windows.
Returns immediately with the PID of the child. Using 'waitProcess' on it
is YOUR responsibility!
Note that you may not use the same fd on more than one item. If you
want to redirect stdout and stderr, dup it first.
-}pOpen3Raw::MaybeFd-- ^ Send stdin to this fd->MaybeFd-- ^ Get stdout from this fd->MaybeFd-- ^ Get stderr from this fd->FilePath-- ^ Command to run->[String]-- ^ Command args->IO()-- ^ Action to run in child before execing (if you don't need something, set this to @return ()@) -- IGNORED IN HUGS->IOProcessIDpOpen3Rawpinpoutperrfpargschildfunc=letmayberedirNothing_=return()mayberedir(Justfromfd)tofd=dodupTofromfdtofdcloseFdfromfdreturn()childstuff=domayberedirpinstdInputmayberedirpoutstdOutputmayberedirperrstdErrorchildfuncdebugM(logbase++".pOpen3")("Running: "++fp++" "++(showargs))executeFilefpTrueargsNothing{-
realfunc p = do
System.Posix.Signals.installHandler
System.Posix.Signals.sigPIPE
System.Posix.Signals.Ignore
Nothing
func p
-}indop<-try(forkProcesschildstuff)pid<-casepofRightx->returnxLefte->fail("Error in fork: "++(showe))returnpid#endif#endifshowCmd::FilePath->[String]->StringshowCmdfpargs=fp++" "++showargs