diff options
Diffstat (limited to 'tests/Language/Haskell/Stylish/Tests/Util.hs')
-rw-r--r-- | tests/Language/Haskell/Stylish/Tests/Util.hs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/tests/Language/Haskell/Stylish/Tests/Util.hs b/tests/Language/Haskell/Stylish/Tests/Util.hs index 40b5629..f43b6b5 100644 --- a/tests/Language/Haskell/Stylish/Tests/Util.hs +++ b/tests/Language/Haskell/Stylish/Tests/Util.hs @@ -1,9 +1,22 @@ module Language.Haskell.Stylish.Tests.Util ( testStep + , withTestDirTree ) where -------------------------------------------------------------------------------- +import Control.Exception (bracket, try) +import System.Directory (createDirectory, + getCurrentDirectory, + getTemporaryDirectory, + removeDirectoryRecursive, + setCurrentDirectory) +import System.FilePath ((</>)) +import System.IO.Error (isAlreadyExistsError) +import System.Random (randomIO) + + +-------------------------------------------------------------------------------- import Language.Haskell.Stylish.Parse import Language.Haskell.Stylish.Step @@ -15,3 +28,34 @@ testStep step str = case parseModule [] Nothing str of Right module' -> unlines $ stepFilter step ls module' where ls = lines str + + +-------------------------------------------------------------------------------- +-- | Create a temporary directory with a randomised name built from the template +-- provided +createTempDirectory :: String -> IO FilePath +createTempDirectory template = do + tmpRootDir <- getTemporaryDirectory + dirId <- randomIO :: IO Word + findTempName tmpRootDir dirId + where + findTempName :: FilePath -> Word -> IO FilePath + findTempName tmpRootDir x = do + let dirpath = tmpRootDir </> template ++ show x + r <- try $ createDirectory dirpath + case r of + Right _ -> return dirpath + Left e | isAlreadyExistsError e -> findTempName tmpRootDir (x+1) + | otherwise -> ioError e + + +-------------------------------------------------------------------------------- +-- | Perform an action inside a temporary directory tree and purge the tree +-- afterwards +withTestDirTree :: IO a -> IO a +withTestDirTree action = bracket + ((,) <$> getCurrentDirectory <*> createTempDirectory "stylish_haskell") + (\(current, temp) -> + setCurrentDirectory current *> + removeDirectoryRecursive temp) + (\(_, temp) -> setCurrentDirectory temp *> action) |