aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/markdown2pdf.hs25
1 files changed, 16 insertions, 9 deletions
diff --git a/src/markdown2pdf.hs b/src/markdown2pdf.hs
index d6ee39dab..1a2ee8ccb 100644
--- a/src/markdown2pdf.hs
+++ b/src/markdown2pdf.hs
@@ -8,6 +8,8 @@ import Data.ByteString.UTF8 (toString)
import Control.Monad (unless, guard, liftM, when)
import Control.Concurrent (putMVar, takeMVar, newEmptyMVar, forkIO)
import Control.Exception (tryJust, bracket, evaluate)
+import Control.Monad.Trans (liftIO)
+import System.IO.Error (isAlreadyExistsError)
import System.IO
import System.IO.Error (isDoesNotExistError)
@@ -176,17 +178,22 @@ saveOutput input output = do
copyFile (encodeString input) (encodeString output)
UTF8.hPutStrLn stderr $! "Created " ++ output
-main :: IO ()
-main = bracket
- -- acquire resource
- (do dir <- getTemporaryDirectory
- let tmp = dir </> "pandoc"
- createDirectoryIfMissing True tmp
- return tmp)
+-- | Perform a function in a temporary directory and clean up.
+withTempDir :: FilePath -> (FilePath -> IO a) -> IO a
+withTempDir baseName = bracket (createTempDir 0 baseName) removeDirectoryRecursive
- -- release resource
- ( \tmp -> removeDirectoryRecursive tmp)
+-- | Create a temporary directory with a unique name.
+createTempDir :: Integer -> FilePath -> IO FilePath
+createTempDir num baseName = do
+ sysTempDir <- getTemporaryDirectory
+ let dirName = sysTempDir </> baseName <.> show num
+ liftIO $ catch (createDirectory dirName >> return dirName) $
+ \e -> if isAlreadyExistsError e
+ then createTempDir (num + 1) baseName
+ else ioError e
+main :: IO ()
+main = withTempDir "pandoc"
-- run computation
$ \tmp -> do
args <- liftM (map decodeString) getArgs