Last active
August 27, 2020 21:53
-
-
Save steshaw/4e0367031f278c8bab58e16d25803faa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE QuasiQuotes #-} | |
{-# LANGUAGE TemplateHaskell #-} | |
module Foo.EmbedFile | |
( ourEmbedFile, | |
ourEmbedFileUtf8, | |
traceSplices, | |
relativeToProjectHome, | |
) | |
where | |
import ClassyPrelude | |
import qualified Data.FileEmbed as FE | |
import qualified Data.Text as T | |
import qualified Data.Text.IO as T | |
import Debug.Trace | |
import Instances.TH.Lift () | |
import Language.Haskell.TH (Exp, Q, runIO) | |
import qualified Language.Haskell.TH as TH | |
import System.Environment | |
-- | | |
-- NOTE: This method of locating the file to embed does not work in HIE since | |
-- the file being edited is copyied to $TMP. | |
_embedFileBySourceLocationToCabal :: FilePath -> Q Exp | |
_embedFileBySourceLocationToCabal filePath = do | |
p <- FE.makeRelativeToProject filePath | |
let debug = False | |
when debug $ do | |
runIO $ putStrLn $ sep <> fromString p <> sep | |
FE.embedFile p | |
sep :: Text | |
sep = "\n" <> replicate 80 '-' <> "\n" | |
relativeToProjectHome :: MonadIO m => FilePath -> m FilePath | |
relativeToProjectHome filePath = do | |
projectHome <- liftIO $ getEnv "PROJECT_HOME" | |
pure $ projectHome </> filePath | |
embedFileRelativeToProjectHome :: FilePath -> Q Exp | |
embedFileRelativeToProjectHome filePath = do | |
f <- relativeToProjectHome filePath | |
let debug = False | |
when debug $ do | |
runIO $ T.hPutStrLn stderr $ sep <> fromString f <> sep | |
traceSplices $ FE.embedFile f | |
traceSplices :: Q Exp -> Q Exp | |
traceSplices qExp = do | |
let debug = False | |
if debug | |
then do | |
e <- qExp | |
let msg = sep <> fromString (TH.pprint e) <> sep | |
pure $ Debug.Trace.trace (T.unpack msg) e | |
else qExp | |
ourEmbedFile :: FilePath -> Q Exp | |
ourEmbedFile = embedFileRelativeToProjectHome | |
ourEmbedFileUtf8 :: FilePath -> Q Exp | |
ourEmbedFileUtf8 filePath = [|decodeUtf8 $(ourEmbedFile filePath)|] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment