What is the haskell way to copy a directory
It's possible to use the Shelly
library in order to do this, see cp_r
:
cp_r "sourcedir" "targetdir"
Shelly first tries to use native cp -r
if available. If not, it falls back to a native Haskell IO
implementation.
For further details on type semantics of cp_r
, see this post written by me to described how to use cp_r
with String
and or Text
.
Shelly is not platform independent, since it relies on the Unix package, which is not supported under Windows.
The filesystem-trees
package provides the means for a very simple implementation:
import System.File.Tree (getDirectory, copyTo_)
copyDirectory :: FilePath -> FilePath -> IO ()
copyDirectory source target = getDirectory source >>= copyTo_ target
I couldn't find anything that does this on Hackage.
Your code looks pretty good to me. Some comments:
-
dstExists <- doesDirectoryExist dst
This does not take into account that a file with the destination name might exist.
-
if or [not srcExists, dstExists] then print "cannot copy"
You might want to throw an exception or return a status instead of printing directly from this function.
-
paths <- forM xs $ \name -> do [...] return ()
Since you're not using
paths
for anything, you can change this toforM_ xs $ \name -> do [...]
The MissingH
package provides recursive directory traversals, which you might be able to use to simplify your code.