-- | 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 m (FilePath, ScopedHandle s)
tempFile :: forall {k} (m :: Type -> Type) (s :: k).
MonadUnliftIO m =>
FilePath -> FilePath -> Scoped s m (FilePath, ScopedHandle s)
tempFile FilePath
fp FilePath
template = (forall b. ((FilePath, ScopedHandle s) -> m b) -> m b)
-> Scoped s m (FilePath, ScopedHandle s)
forall {l} {k} (s :: l) (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 {k} (s :: k) a. a -> ScopedResource s a
UnsafeMkScopedResource Handle
h)

-- | Like 'System.IO.withSystemTempFile' but for 'Scoped'
systemTempFile :: MonadUnliftIO m => String -> Scoped s m (FilePath, ScopedHandle s)
systemTempFile :: forall {k} (m :: Type -> Type) (s :: k).
MonadUnliftIO m =>
FilePath -> Scoped s m (FilePath, ScopedHandle s)
systemTempFile FilePath
template = (forall b. ((FilePath, ScopedHandle s) -> m b) -> m b)
-> Scoped s m (FilePath, ScopedHandle s)
forall {l} {k} (s :: l) (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 {k} (s :: k) a. a -> ScopedResource s a
UnsafeMkScopedResource Handle
h)