Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some directory walker in Haskell?

Is there some recursive directory walker in Haskell so I could write something like

listing <- walkDir "/tmp"

I would not like to write my own. I can install some dependency from cabal but I want it to be cross platform (at least Linux and Windows).

like image 917
Trismegistos Avatar asked Nov 08 '12 21:11

Trismegistos


4 Answers

Here is one way to list all Haskell files in a directory tree, using directory-tree that is not in a hidden directory (whose name starts with '.'):

import Data.Traversable (traverse)
import System.Directory.Tree (
    AnchoredDirTree(..), DirTree(..),
    filterDir, readDirectoryWith
    )
import System.FilePath (takeExtension)

listFilesDirFiltered = do
    _:/tree <- readDirectoryWith return "C:\\devmy\\code"
    traverse print $ filterDir myPred tree
    return ()
  where myPred (Dir ('.':_) _) = False
        myPred (File n _) = takeExtension n == ".hs"
        myPred _ = True

main = listFilesDirFiltered

Works on both Windows and Linux.

like image 84
Björn Lindqvist Avatar answered Oct 27 '22 01:10

Björn Lindqvist


I have a recursive definition for traversing a directory using filepath package:

import Control.Monad
import System.Directory
import System.FilePath
import System.Posix.Files

-- | Traverse from 'top' directory and return all the files by
-- filtering out the 'exclude' predicate.
traverseDir :: FilePath -> (FilePath -> Bool) -> IO [FilePath]
traverseDir top exclude = do
  ds <- getDirectoryContents top
  paths <- forM (filter (not.exclude) ds) $ \d -> do
    let path = top </> d
    s <- getFileStatus path
    if isDirectory s
      then traverseDir path exclude
      else return [path]
  return (concat paths)
like image 38
aycanirican Avatar answered Oct 26 '22 23:10

aycanirican


The filemanip package provides powerful and elegant functions for that. For example it provides a fold function that will recursively call your function down a directory tree. As an example i used it here to recursively list files in a directory starting from the oldest

like image 35
danza Avatar answered Oct 27 '22 01:10

danza


http://hackage.haskell.org/package/FilePather has that sort of recursive directory walking functionality.

like image 22
singpolyma Avatar answered Oct 26 '22 23:10

singpolyma