Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a temporary directory in Haskell

What is the proper way to safely create a temporary directory in Haskell? System.IO offers ways to create temporary files, but I can't find anything that does the same for directories, neither there nor in System.Directory, System.Posix.Directory, nor System.Posix.Temp. Is there a function I'm overlooking, or do I need to write one myself? (And if so, are there any dangers to avoid, like there are with creating temporary files?)

like image 805
Paul Kuliniewicz Avatar asked Jun 04 '10 22:06

Paul Kuliniewicz


3 Answers

As suggested by @Nikita Volkov, I am posting the comment of @Thomas M. DuBuisson as a separate answer:

Use the temporary package. It provides a convenient platform-independent API for using temporary files and directories. The temporary files and directories are automatically deleted after use.

like image 55
Yitz Avatar answered Oct 22 '22 15:10

Yitz


For working specifically with Unix systems, the Unixutils package contains such a function:

withTemporaryDirectory :: FilePath -> (FilePath -> IO a) -> IO a

If you need it to work on both Windows and Unix systems, you'll want to use the temporary package instead. It has the same function with a slightly different type signature:

withTemporaryDirectory :: FilePath -> String -> (FilePath -> IO a) -> IO a

like image 29
Don Stewart Avatar answered Oct 22 '22 17:10

Don Stewart


You could look at the Distribution.Compat.TempFile module of the Cabal source for an example. It defines createTempDirectory as follows (where c_getpid and mkPrivateDir are platform-specific):

createTempDirectory :: FilePath -> String -> IO FilePath
createTempDirectory dir template = do
  pid <- c_getpid
  findTempName pid
  where
    findTempName x = do
      let dirpath = dir </> template ++ show x
      r <- try $ mkPrivateDir dirpath
      case r of
        Right _ -> return dirpath
        Left  e | isAlreadyExistsError e -> findTempName (x+1)
                | otherwise              -> ioError e

The fact that Cabal defines this function suggests that there's not a standard way to do it.

like image 2
Travis Brown Avatar answered Oct 22 '22 15:10

Travis Brown