-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadDir.hs
53 lines (46 loc) · 1.94 KB
/
ReadDir.hs
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
51
52
53
module ReadDir (
DirEntry(..),
readDir,
) where
import System.FilePath hiding (makeRelative)
import System.Directory
import System.IO.Unsafe
import Data.Time.Clock
import Control.Monad
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
data DirEntry = DirEntry {
deFileName :: FilePath,
deModTime :: UTCTime,
deFileContent :: LB.ByteString
} deriving (Show)
readDir :: FilePath -> IO [DirEntry]
readDir dir = mapM (mkDirEntry . makeRelative dir) =<< recursive dir
where mkDirEntry file = do
modTime <- {- unsafeInterleaveIO $ -} getModificationTime (dir </> file)
content <- unsafeInterleaveIO $ (LB.fromChunks . (:[])) `liftM` B.readFile (dir </> file)
return $ DirEntry {
deFileName = file,
deModTime = modTime,
deFileContent = content }
recursive dir = do
all_entries <- if dir == ""
then getDirectoryContents "."
else getDirectoryContents dir
let entries = filter ((/='.') . head) all_entries
files <- filterM (doesFileExist . combine dir) entries
dirs <- filterM (doesDirectoryExist . combine dir) entries
deeper <- concat `liftM` mapM (recursive . combine dir) dirs
return $ (map (combine dir) files) ++ deeper
makeRelative :: FilePath -> FilePath -> FilePath
makeRelative cur x = joinPath $
replicate (length curdir - common) ".." ++
drop common orgpth
where
common = length $ takeWhile id $ zipWith (==) orgdir curdir
orgpth = splitPath pth
orgdir = splitDirectories pth
curdir = case splitDirectories $ normalise $ cur of
(".":rest ) -> rest
dir -> dir
pth = normalise x