aboutsummaryrefslogtreecommitdiff
path: root/haddock-test/src/Test/Haddock/Utils.hs
blob: a947fea101cb0308514199f816ba26ab10506c35 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module Test.Haddock.Utils where


import Control.Monad

import Data.Maybe

import System.Directory
import System.FilePath


mlast :: [a] -> Maybe a
mlast = listToMaybe . reverse


partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM _ [] = pure ([], [])
partitionM p (x:xs) = do
    (ss, fs) <- partitionM p xs
    b <- p x
    pure $ if b then (x:ss, fs) else (ss, x:fs)


whenM :: Monad m => m Bool -> m () -> m ()
whenM mb action = mb >>= \b -> when b action


getDirectoryTree :: FilePath -> IO [FilePath]
getDirectoryTree path = do
    (dirs, files) <- partitionM isDirectory =<< contents
    subfiles <- fmap concat . forM dirs $ \dir ->
        map (dir </>) <$> getDirectoryTree (path </> dir)
    pure $ files ++ subfiles
  where
    contents = filter realEntry <$> getDirectoryContents path
    isDirectory entry = doesDirectoryExist $ path </> entry
    realEntry entry = not $ entry == "." || entry == ".."


createEmptyDirectory :: FilePath -> IO ()
createEmptyDirectory path = do
    whenM (doesDirectoryExist path) $ removeDirectoryRecursive path
    createDirectory path


-- | Just like 'copyFile' but output directory path is not required to exist.
copyFile' :: FilePath -> FilePath -> IO ()
copyFile' old new = do
    createDirectoryIfMissing True $ takeDirectory new
    copyFile old new