module Utils
    (list
    ,run
    ,trim)
    where

import System.Process
import System.IO
import System.Exit
import qualified System.IO.Strict as StrictIO

list :: Eq a => b -> ([a] -> b) -> [a] -> b
list nil cons v = if v == [] then nil else cons v

run :: String -> String -> IO (Either String (String,String))
run cmd input = do
  Right (inp,out,err,pid) <- catch (Right `fmap` runInteractiveCommand cmd)
                                   (const $ return $ Left "Broken pipe")
  catch (do hPutStr inp input; hClose inp
            output <- StrictIO.hGetContents out
            errput <- StrictIO.hGetContents err
            e <- catch (waitForProcess pid)
                       (const $ return ExitSuccess)
            return $ Right (errput,output))
        (const $ return $ Left "Broken pipe")

trim :: String -> String
trim = unwords . words