module Test.Syd.Path where

import Data.ByteString (ByteString)
import qualified Data.ByteString as SB
import Path
import Path.IO
import System.IO
import Test.Syd.Def.SetupFunc
import Test.Syd.Def.TestDefM

-- | A test suite that has access to a temporary directory
tempDirSpec ::
  -- | Temporary directory name template
  String ->
  TestDefM outers (Path Abs Dir) result ->
  TestDefM outers () result
tempDirSpec :: forall (outers :: [*]) result.
String
-> TestDefM outers (Path Abs Dir) result
-> TestDefM outers () result
tempDirSpec String
template = forall inner (outers :: [*]) result any.
SetupFunc inner
-> TestDefM outers inner result -> TestDefM outers any result
setupAround forall a b. (a -> b) -> a -> b
$ String -> SetupFunc (Path Abs Dir)
tempDirSetupFunc String
template

-- | Setup function for a temporary directory
tempDirSetupFunc ::
  -- | Temporary directory name template
  String ->
  SetupFunc (Path Abs Dir)
tempDirSetupFunc :: String -> SetupFunc (Path Abs Dir)
tempDirSetupFunc String
template = forall resource.
(forall r. (resource -> IO r) -> IO r) -> SetupFunc resource
SetupFunc forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
String -> (Path Abs Dir -> m a) -> m a
withSystemTempDir String
template

tempBinaryFileWithContentsSetupFunc ::
  -- | Temporary directory name template
  String ->
  ByteString ->
  SetupFunc (Path Abs File)
tempBinaryFileWithContentsSetupFunc :: String -> ByteString -> SetupFunc (Path Abs File)
tempBinaryFileWithContentsSetupFunc String
template ByteString
contents = forall resource.
(forall r. (resource -> IO r) -> IO r) -> SetupFunc resource
SetupFunc forall a b. (a -> b) -> a -> b
$ \Path Abs File -> IO r
func ->
  forall (m :: * -> *) a.
(MonadIO m, MonadMask m) =>
String -> (Path Abs File -> Handle -> m a) -> m a
withSystemTempFile
    String
template
    ( \Path Abs File
af Handle
h -> do
        Handle -> ByteString -> IO ()
SB.hPut Handle
h ByteString
contents
        Handle -> IO ()
hFlush Handle
h
        Handle -> IO ()
hClose Handle
h
        Path Abs File -> IO r
func Path Abs File
af
    )