-- | Functions and types for safely working with tempfiles  in 'Scoped' blocks
module Control.Monad.Scoped.Temp
  ( -- * Allocating a temporary files in a 'Scoped' block
    tempFile
  , systemTempFile
  )
where

import Control.Monad.Scoped.Handle (ScopedHandle)
import Control.Monad.Scoped.Internal (Scoped (UnsafeMkScoped), ScopedResource (UnsafeMkScopedResource))
import UnliftIO (MonadUnliftIO, withSystemTempFile, withTempFile)

-- | Like 'System.IO.withTempFile' but for 'Scoped'
tempFile :: MonadUnliftIO m => FilePath -> String -> Scoped (s : ss) m (FilePath, ScopedHandle s)
tempFile :: forall (m :: Type -> Type) s (ss :: [Type]).
MonadUnliftIO m =>
FilePath
-> FilePath -> Scoped (s : ss) m (FilePath, ScopedHandle s)
tempFile FilePath
fp FilePath
template = (forall b. ((FilePath, ScopedHandle s) -> m b) -> m b)
-> Scoped (s : ss) m (FilePath, ScopedHandle s)
forall {k} (s :: [Type]) (m :: k -> Type) a.
(forall (b :: k). (a -> m b) -> m b) -> Scoped s m a
UnsafeMkScoped \(FilePath, ScopedHandle s) -> m b
k -> FilePath -> FilePath -> (FilePath -> Handle -> m b) -> m b
forall (m :: Type -> Type) a.
MonadUnliftIO m =>
FilePath -> FilePath -> (FilePath -> Handle -> m a) -> m a
withTempFile FilePath
fp FilePath
template \FilePath
path Handle
h -> (FilePath, ScopedHandle s) -> m b
k (FilePath
path, Handle -> ScopedHandle s
forall s a. a -> ScopedResource s a
UnsafeMkScopedResource Handle
h)

-- | Like 'System.IO.withSystemTempFile' but for 'Scoped'
systemTempFile :: MonadUnliftIO m => String -> Scoped (s : ss) m (FilePath, ScopedHandle s)
systemTempFile :: forall (m :: Type -> Type) s (ss :: [Type]).
MonadUnliftIO m =>
FilePath -> Scoped (s : ss) m (FilePath, ScopedHandle s)
systemTempFile FilePath
template = (forall b. ((FilePath, ScopedHandle s) -> m b) -> m b)
-> Scoped (s : ss) m (FilePath, ScopedHandle s)
forall {k} (s :: [Type]) (m :: k -> Type) a.
(forall (b :: k). (a -> m b) -> m b) -> Scoped s m a
UnsafeMkScoped \(FilePath, ScopedHandle s) -> m b
k -> FilePath -> (FilePath -> Handle -> m b) -> m b
forall (m :: Type -> Type) a.
MonadUnliftIO m =>
FilePath -> (FilePath -> Handle -> m a) -> m a
withSystemTempFile FilePath
template \FilePath
path Handle
h -> (FilePath, ScopedHandle s) -> m b
k (FilePath
path, Handle -> ScopedHandle s
forall s a. a -> ScopedResource s a
UnsafeMkScopedResource Handle
h)