module Utility.Tmp where
import Control.Exception (bracket)
import System.IO
import System.Directory
import Control.Monad.IfElse
import System.FilePath
import Utility.Exception
import Utility.FileSystemEncoding
import Utility.PosixFiles
type Template = String
viaTmp :: (FilePath -> String -> IO ()) -> FilePath -> String -> IO ()
viaTmp a file content = do
let (dir, base) = splitFileName file
createDirectoryIfMissing True dir
(tmpfile, handle) <- openTempFile dir (base ++ ".tmp")
hClose handle
a tmpfile content
rename tmpfile file
withTmpFile :: Template -> (FilePath -> Handle -> IO a) -> IO a
withTmpFile template a = do
tmpdir <- catchDefaultIO "." getTemporaryDirectory
withTmpFileIn tmpdir template a
withTmpFileIn :: FilePath -> Template -> (FilePath -> Handle -> IO a) -> IO a
withTmpFileIn tmpdir template a = bracket create remove use
where
create = openTempFile tmpdir template
remove (name, handle) = do
hClose handle
catchBoolIO (removeFile name >> return True)
use (name, handle) = a name handle
withTmpDir :: Template -> (FilePath -> IO a) -> IO a
withTmpDir template a = do
tmpdir <- catchDefaultIO "." getTemporaryDirectory
withTmpDirIn tmpdir template a
withTmpDirIn :: FilePath -> Template -> (FilePath -> IO a) -> IO a
withTmpDirIn tmpdir template = bracket create remove
where
remove d = whenM (doesDirectoryExist d) $ do
#if mingw32_HOST_OS
_ <- tryIO $ removeDirectoryRecursive d
return ()
#else
removeDirectoryRecursive d
#endif
create = do
createDirectoryIfMissing True tmpdir
makenewdir (tmpdir </> template) (0 :: Int)
makenewdir t n = do
let dir = t ++ "." ++ show n
either (const $ makenewdir t $ n + 1) (const $ return dir)
=<< tryIO (createDirectory dir)
relatedTemplate :: FilePath -> FilePath
relatedTemplate f
| len > 20 = truncateFilePath (len 20) f
| otherwise = f
where
len = length f