--- * -*- outline-regexp:"--- \\*"; -*-
--- ** doc
-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.
{-|

A reader for CSV (character-separated) data.
This also reads a rules file to help interpret the CSV data.

-}

--- ** language
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverloadedStrings    #-}
{-# LANGUAGE ScopedTypeVariables  #-}
{-# LANGUAGE TypeFamilies         #-}

--- ** exports
module Hledger.Read.CsvReader (
  -- * Reader
  reader,
  -- * Tests
  tests_CsvReader,
)
where

--- ** imports
import Prelude hiding (Applicative(..))
import Control.Monad.Except       (ExceptT(..), liftEither, withExceptT)
import Control.Monad.IO.Class     (MonadIO)
import Data.Encoding              (DynEncoding)
import Data.Text                  (Text)
import System.IO                  (Handle, IOMode(..), openFile)

import Hledger.Data
import Hledger.Utils
import Hledger.Read.Common (aliasesFromOpts, Reader(..), InputOpts(..), includeFileParser, journalFinalise)
import Hledger.Read.RulesReader (readParsedJournalFromCsv, getRulesFile, rulesEncoding, readRules)
import Control.Monad.Trans (lift)

--- ** doctest setup
-- $setup
-- >>> :set -XOverloadedStrings

--- ** reader

reader :: MonadIO m => SepFormat -> Reader m
reader :: forall (m :: * -> *). MonadIO m => SepFormat -> Reader m
reader SepFormat
sep = Reader
  {rFormat :: StorageFormat
rFormat     = SepFormat -> StorageFormat
Sep SepFormat
sep
  ,rExtensions :: [String]
rExtensions = [SepFormat -> String
forall a. Show a => a -> String
show SepFormat
sep]
  ,rReadFn :: InputOpts -> String -> Handle -> ExceptT String IO Journal
rReadFn     = SepFormat
-> InputOpts -> String -> Handle -> ExceptT String IO Journal
parse SepFormat
sep
  -- When included by a journal file: the --rules option is ignored, the rules file is always FILE.rules,
  -- and the data is not finalised here; the including journal's finalisation handles that.
  -- (So if finalisation then fails on a CSV-generated entry, the "converted from this record"
  -- context is not shown, but the error still cites the CSV file and line.)
  ,rParser :: MonadIO m => InputOpts -> ErroringJournalParser m Journal
rParser     = \InputOpts
iopts -> (String -> ExceptT String IO Journal)
-> ErroringJournalParser m Journal
forall (m :: * -> *).
MonadIO m =>
(String -> ExceptT String IO Journal)
-> ErroringJournalParser m Journal
includeFileParser ((String -> ExceptT String IO Journal)
 -> ErroringJournalParser m Journal)
-> (String -> ExceptT String IO Journal)
-> ErroringJournalParser m Journal
forall a b. (a -> b) -> a -> b
$ \String
f ->
                   (Journal, String -> String) -> Journal
forall a b. (a, b) -> a
fst ((Journal, String -> String) -> Journal)
-> ExceptT String IO (Journal, String -> String)
-> ExceptT String IO Journal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SepFormat
-> Bool
-> Maybe String
-> String
-> (Maybe DynEncoding -> IO Text)
-> ExceptT String IO (Journal, String -> String)
readCsvWith SepFormat
sep (InputOpts -> Bool
_scanfiles InputOpts
iopts) Maybe String
forall a. Maybe a
Nothing String
f (\Maybe DynEncoding
enc -> String -> IOMode -> IO Handle
openFile String
f IOMode
ReadMode IO Handle -> (Handle -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe DynEncoding -> Handle -> IO Text
hGetContentsPortably Maybe DynEncoding
enc)
  }

-- | Parse and post-process a "Journal" from a CSV(/SSV/TSV/*SV) data file, or give an error.
-- This reads the data from the provided input file handle, and reads the corresponding
-- rules file (or the one specified by --rules) to help convert it.
-- This does not check balance assertions.
parse :: SepFormat -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
parse :: SepFormat
-> InputOpts -> String -> Handle -> ExceptT String IO Journal
parse SepFormat
sep InputOpts
iopts String
f Handle
h = do
  (j1, adderrorcontext) <- SepFormat
-> Bool
-> Maybe String
-> String
-> (Maybe DynEncoding -> IO Text)
-> ExceptT String IO (Journal, String -> String)
readCsvWith SepFormat
sep (InputOpts -> Bool
_scanfiles InputOpts
iopts) (InputOpts -> Maybe String
mrules_file_ InputOpts
iopts) String
f (Maybe DynEncoding -> Handle -> IO Text
`hGetContentsPortably` Handle
h)
  -- apply any command line account aliases. Can fail with a bad replacement pattern.
  j2 <- liftEither $ journalApplyAliases (aliasesFromOpts iopts) j1
  -- if finalisation fails, show also the CSV record which generated the failing entry
  withExceptT adderrorcontext $
    journalFinalise iopts{balancingopts_=(balancingopts_ iopts){ignore_assertions_=True}} f "" j2

-- | Read the rules file for a CSV data file (the one specified, or the one named after the data file),
-- read the data with the given action (which is told the rules' encoding, if any),
-- and convert it to an unfinalised journal (see 'readParsedJournalFromCsv').
-- If the first argument is true (we are just finding the files read), the data is not read.
readCsvWith :: SepFormat -> Bool -> Maybe FilePath -> FilePath -> (Maybe DynEncoding -> IO Text)
            -> ExceptT String IO (ParsedJournal, String -> String)
readCsvWith :: SepFormat
-> Bool
-> Maybe String
-> String
-> (Maybe DynEncoding -> IO Text)
-> ExceptT String IO (Journal, String -> String)
readCsvWith SepFormat
sep Bool
scanning Maybe String
mrulesfile String
f Maybe DynEncoding -> IO Text
readdata = do
  let rulesfile :: String
rulesfile = String -> Maybe String -> String
getRulesFile String
f Maybe String
mrulesfile
  (rules, rulesfiles) <- String -> ExceptT String IO (CsvRules, [String])
readRules String
rulesfile
  mencoding <- rulesEncoding rulesfile rules
  csvtext <- if scanning then return "" else lift $ readdata mencoding
  readParsedJournalFromCsv rulesfile rules (f, rulesfiles) f csvtext (Just sep)

--- ** tests

tests_CsvReader :: TestTree
tests_CsvReader = String -> [TestTree] -> TestTree
testGroup String
"CsvReader" [
  ]