module Test.Mockery.Directory (
inTempDirectory
, inTempDirectoryNamed
, withFile
, touch
) where
import Control.Exception
import Control.Monad
import System.Directory
import System.FilePath
import System.IO.Error
import System.IO hiding (withFile)
import System.IO.Temp (withSystemTempDirectory, withSystemTempFile)
import qualified Data.ByteString as B
inTempDirectory :: IO a -> IO a
inTempDirectory :: forall a. IO a -> IO a
inTempDirectory IO a
action = forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
String -> (String -> m a) -> m a
withSystemTempDirectory String
"mockery" forall a b. (a -> b) -> a -> b
$ \String
path -> do
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket IO String
getCurrentDirectory String -> IO ()
setCurrentDirectory forall a b. (a -> b) -> a -> b
$ \String
_ -> do
String -> IO ()
setCurrentDirectory String
path
IO a
action
inTempDirectoryNamed :: FilePath -> IO a -> IO a
inTempDirectoryNamed :: forall a. String -> IO a -> IO a
inTempDirectoryNamed String
name IO a
action = forall a. IO a -> IO a
inTempDirectory forall a b. (a -> b) -> a -> b
$ do
String -> IO ()
createDirectory String
name
String -> IO ()
setCurrentDirectory String
name
IO a
action
withFile :: String -> (FilePath -> IO a) -> IO a
withFile :: forall a. String -> (String -> IO a) -> IO a
withFile String
input String -> IO a
action = forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
String -> (String -> Handle -> m a) -> m a
withSystemTempFile String
"mockery" forall a b. (a -> b) -> a -> b
$ \String
file Handle
h -> do
Handle -> String -> IO ()
hPutStr Handle
h String
input
Handle -> IO ()
hClose Handle
h
String -> IO a
action String
file
touch :: FilePath -> IO ()
touch :: String -> IO ()
touch String
file = do
Bool -> String -> IO ()
createDirectoryIfMissing Bool
True (String -> String
takeDirectory String
file)
ByteString
c <- forall e b a.
Exception e =>
(e -> Maybe b) -> IO a -> (b -> IO a) -> IO a
catchJust (forall (f :: * -> *). Alternative f => Bool -> f ()
guard forall b c a. (b -> c) -> (a -> b) -> a -> c
. IOError -> Bool
isDoesNotExistError) (String -> IO ByteString
B.readFile String
file) (forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
B.empty)
String -> ByteString -> IO ()
B.writeFile String
file ByteString
c