{-# LANGUAGE OverloadedStrings #-}

module Test.Tasty.AutoCollect (
  processFile,
) where

import Data.Text (Text)
import qualified Data.Text as Text

import Test.Tasty.AutoCollect.GenerateMain
import Test.Tasty.AutoCollect.ModuleType
import Test.Tasty.AutoCollect.Utils.Text

-- | Preprocess the given Haskell file. See Preprocessor.hs
processFile :: FilePath -> Text -> IO Text
processFile :: FilePath -> Text -> IO Text
processFile FilePath
path Text
file =
  case Text -> Maybe ModuleType
parseModuleType Text
file of
    Just (ModuleMain AutoCollectConfig
cfg) -> Text -> Text
addLinePragma (Text -> Text) -> IO Text -> IO Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AutoCollectConfig -> FilePath -> IO Text
generateMainModule AutoCollectConfig
cfg FilePath
path
    Just ModuleType
ModuleTest ->
      Text -> IO Text
forall (f :: * -> *) a. Applicative f => a -> f a
pure
        (Text -> IO Text) -> (Text -> Text) -> Text -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text -> Text
forall a. (Semigroup a, IsString a) => a -> a -> a
addLine Text
"{-# OPTIONS_GHC -fplugin=Test.Tasty.AutoCollect.ConvertTest #-}"
        (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
addLinePragma
        (Text -> IO Text) -> Text -> IO Text
forall a b. (a -> b) -> a -> b
$ Text
file
    Maybe ModuleType
Nothing -> Text -> IO Text
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> IO Text) -> Text -> IO Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
addLinePragma Text
file
  where
    addLine :: a -> a -> a
addLine a
line a
f = a
line a -> a -> a
forall a. Semigroup a => a -> a -> a
<> a
"\n" a -> a -> a
forall a. Semigroup a => a -> a -> a
<> a
f
    -- this is needed to tell GHC to use original path in error messages
    addLinePragma :: Text -> Text
addLinePragma = Text -> Text -> Text
forall a. (Semigroup a, IsString a) => a -> a -> a
addLine (Text -> Text -> Text) -> Text -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Text
"{-# LINE 1 " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
quoted (FilePath -> Text
Text.pack FilePath
path) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" #-}"