Search code examples
haskellhaskell-turtle

Using Haskell Turtle's FilePath with readFile


I am trying to use Haskell Turtle to do some CSV file processing, but I'm having trouble working with the Turtle.FilePath from the option parser. Here's an exampple:

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Lib

import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Turtle

data Args = Args Turtle.FilePath
  deriving Show

tfpToStr :: Turtle.FilePath -> String
tfpToStr fpath = show fpath

tfpToPfp :: Turtle.FilePath -> Prelude.FilePath
tfpToPfp fpath = show fpath

parser :: Parser Args
parser = Args <$> (argPath "fname" "The file containing the data")

sname :: String
sname = "salaries.csv"

main :: IO ()
main = do
    Args fname <- options "Salary Printer" parser
    csvData <- BL.readFile (tfpToStr fname)
    -- csvData <- BL.readFile sname
    putStrLn $ show csvData

I have a file salaries.csv in the same directory. If I run this, I get back FilePath "salaries.csv": openBinaryFile: does not exist (No such file or directory). Using tfpToPfp yields the same result. If I comment out the first readFile and uncomment the other one that calls BL.readFile sname then it works perfectly. I've also tried csvData <- BL.readFile $ fromString (tfpToStr fname), that also throws an error.

Unfortunately, BL.readFile does not take a Turtle.FilePath directly; it complains that it didn't get a Prelude.FilePath.

So how is one supposed to get a Turtle.FilePath into BL.readFile?

I'm using stack resolver LTS-9.9 if that makes a difference.


Solution

  • The conversion can also be performed without directly using system-filepath:

    import qualified Data.Text as T
    
    filePathToString :: FilePath -> String
    filePathToString = T.unpack . format fp