module Rerun where
import Test.Hspec.Runner
import Control.Exception
import Prelude
import System.Environment
import System.IO.Strict
import System.IO(withFile,IOMode(ReadMode))
import System.Directory(removeFile)
import Safe (lastMay)
import Control.Monad(when)
main clientSpec = do
stashFile <- lookupEnv "HSPEC_FAILURES_FILE"
alreadySet <- lookupEnv "HSPEC_FAILURES"
print ("startup", stashFile, alreadySet)
case (stashFile,alreadySet) of
(Just stash,Just failures) -> do
print ("writing stash optimistically", failures)
writeFile stash failures
(Just stash,Nothing) -> do
print ("reading", stash)
f <- safeReadFile stash
print ("read", stash)
case f of
Nothing -> print ("couldn't read stash", stash)
Just contents -> do
when (contents /= "") $ do
print ("read stash, setting env", contents)
setEnv "HSPEC_FAILURES" contents
_ -> return ()
clientSpec `finally` do
print "done with tests!"
case stashFile of
Just stash -> logAndIgnore () $ removeFile stash
Nothing -> return ()
newSet <- lookupEnv "HSPEC_FAILURES"
print ("spec failures", newSet,stashFile,alreadySet)
case (stashFile,alreadySet,newSet) of
(Just stash,Nothing,Just newset) ->
writeFile stash newset
_ -> return ()
safeReadFile :: FilePath -> IO (Maybe String)
safeReadFile fs = logAndIgnore Nothing $ do
f <- withFile fs ReadMode (\h -> hGetContents h >>= \x -> seq (lastMay x) (return x))
print ("saferead got", f)
return (Just f)
logAndIgnore def f = handle (\(e::IOException) -> print ("saferead failed", e) >> return def) f