views:

135

answers:

2

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?)

+5  A: 

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

Don Stewart
This returns the directory where new temporary files will be created (i.e. usually "/tmp"). It doesn't actually create a temporary directory.
Travis Brown
@Travis ACK! withTemporaryDirectory was what I was looking for.
Don Stewart
This fits nicely with the usage I had in mind, since it automates cleanup of the directory when I'm done with it.
Paul Kuliniewicz
+2  A: 

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.

Travis Brown