module Omnifmt.Process (
runProcess, runProcess_, runTimedProcess, runCommand, runCommand_, runTimedCommand,
runCreateProcess, runCreateProcess_,
) where
import Control.Monad.Except
import Control.Monad.Logger
import Data.Text hiding (unwords)
import Omnifmt.Exit
import System.Exit
import System.Process.Extra (CmdSpec (..), CreateProcess)
import qualified System.Process.Extra as System
runProcess :: (MonadIO m, MonadLogger m) => FilePath -> [String] -> m (ExitCode, String, String)
runProcess cmd args = runCreateProcess (System.proc cmd args) ""
runProcess_ :: (MonadError ExitCode m, MonadIO m, MonadLogger m) => FilePath -> [String] -> m String
runProcess_ cmd args = runCreateProcess_ (System.proc cmd args) ""
runTimedProcess :: (MonadIO m, MonadLogger m) => Int -> FilePath -> [String] -> m (ExitCode, String, String)
runTimedProcess n cmd args = runCreateProcess (System.proc "timeout" $ "-k":show (n * 2):show n:cmd:args) ""
runCommand :: (MonadIO m, MonadLogger m) => String -> m (ExitCode, String, String)
runCommand cmd = runCreateProcess (System.shell cmd) ""
runCommand_ :: (MonadError ExitCode m, MonadIO m, MonadLogger m) => String -> m String
runCommand_ cmd = runCreateProcess_ (System.shell cmd) ""
runTimedCommand :: (MonadIO m, MonadLogger m) => Int -> String -> m (ExitCode, String, String)
runTimedCommand n cmd = runCreateProcess (System.shell $ unwords ["timeout -k", show $ n * 2, show n, cmd]) ""
runCreateProcess :: (MonadIO m, MonadLogger m) => CreateProcess -> String -> m (ExitCode, String, String)
runCreateProcess process stdin = do
logDebugN $ pack (case System.cmdspec process of
ShellCommand cmd -> cmd
RawCommand cmd args -> unwords (cmd:args)
)
liftIO $ System.readCreateProcessWithExitCode process stdin
runCreateProcess_ :: (MonadError ExitCode m, MonadIO m, MonadLogger m) => CreateProcess -> String -> m String
runCreateProcess_ process stdin = do
(exitCode, stdout, stderr) <- runCreateProcess process stdin
if exitCode == ExitSuccess
then return stdout
else panic stderr