{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This module uses template Haskell. Following is a simplified explanation of usage for those unfamiliar with calling Template Haskell functions.
--
-- The function @embedFile@ in this modules embeds a file into the executable
-- that you can use it at runtime. A file is represented as a @ByteString@.
-- However, as you can see below, the type signature indicates a value of type
-- @Q Exp@ will be returned. In order to convert this into a @ByteString@, you
-- must use Template Haskell syntax, e.g.:
--
-- > $(embedFile "myfile.txt")
--
-- This expression will have type @ByteString@. Be certain to enable the
-- TemplateHaskell language extension, usually by adding the following to the
-- top of your module:
--
-- > {-# LANGUAGE TemplateHaskell #-}
module Data.FileEmbed
    ( -- * Embed at compile time
      embedFile
    , embedFileIfExists
    , embedOneFileOf
    , embedDir
    , embedDirListing
    , getDir
      -- * Embed as a IsString
    , embedStringFile
    , embedOneStringFileOf
      -- * Inject into an executable
      -- $inject
#if MIN_VERSION_template_haskell(2,5,0)
    , dummySpace
    , dummySpaceWith
#endif
    , inject
    , injectFile
    , injectWith
    , injectFileWith
      -- * Relative path manipulation
    , makeRelativeToProject
    , makeRelativeToLocationPredicate
      -- * Internal
    , stringToBs
    , bsToExp
    , strToExp
    ) where

import Language.Haskell.TH.Syntax
    ( Exp (AppE, ListE, LitE, TupE, SigE, VarE)
    , Lit (..)
    , Q
    , runIO
    , qLocation, loc_filename
#if MIN_VERSION_template_haskell(2,7,0)
    , Quasi(qAddDependentFile)
#endif
    )
#if MIN_VERSION_template_haskell(2,16,0)
import Language.Haskell.TH ( mkBytes, bytesPrimL )
import qualified Data.ByteString.Internal as B
#endif
import System.Directory (doesDirectoryExist, doesFileExist,
                         getDirectoryContents, canonicalizePath)
import Control.Exception (throw, tryJust, ErrorCall(..))
import Control.Monad (filterM, guard)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Control.Arrow ((&&&), second)
import Control.Applicative ((<$>))
import Data.ByteString.Unsafe (unsafePackAddressLen)
import System.IO.Error (isDoesNotExistError)
import System.IO.Unsafe (unsafePerformIO)
import System.FilePath ((</>), takeDirectory, takeExtension)
import Data.String (fromString)
import Prelude as P
import Data.List (sortBy)
import Data.Ord (comparing)

-- | Embed a single file in your source code.
--
-- > import qualified Data.ByteString
-- >
-- > myFile :: Data.ByteString.ByteString
-- > myFile = $(embedFile "dirName/fileName")
embedFile :: FilePath -> Q Exp
embedFile :: FilePath -> Q Exp
embedFile FilePath
fp =
#if MIN_VERSION_template_haskell(2,7,0)
    FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile FilePath
fp Q () -> Q ByteString -> Q ByteString
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
#endif
  (IO ByteString -> Q ByteString
forall a. IO a -> Q a
runIO (IO ByteString -> Q ByteString) -> IO ByteString -> Q ByteString
forall a b. (a -> b) -> a -> b
$ FilePath -> IO ByteString
B.readFile FilePath
fp) Q ByteString -> (ByteString -> Q Exp) -> Q Exp
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ByteString -> Q Exp
bsToExp

-- | Maybe embed a single file in your source code depending on whether or not file exists.
--
-- Warning: When a build is compiled with the file missing, a recompile when the file exists might not trigger an embed of the file.
-- You might try to fix this by doing a clean build.
--
-- > import qualified Data.ByteString
-- >
-- > maybeMyFile :: Maybe Data.ByteString.ByteString
-- > maybeMyFile = $(embedFileIfExists "dirName/fileName")
--
-- @since 0.0.14.0
embedFileIfExists :: FilePath -> Q Exp
embedFileIfExists :: FilePath -> Q Exp
embedFileIfExists FilePath
fp = do
  Maybe ByteString
mbs <- IO (Maybe ByteString) -> Q (Maybe ByteString)
forall a. IO a -> Q a
runIO IO (Maybe ByteString)
maybeFile
  case Maybe ByteString
mbs of
    Maybe ByteString
Nothing -> [| Nothing |]
    Just ByteString
bs -> do
#if MIN_VERSION_template_haskell(2,7,0)
      FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile FilePath
fp
#endif
      [| Just $(bsToExp bs) |]
  where
    maybeFile :: IO (Maybe B.ByteString)
    maybeFile :: IO (Maybe ByteString)
maybeFile = 
      (() -> Maybe ByteString)
-> (ByteString -> Maybe ByteString)
-> Either () ByteString
-> Maybe ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe ByteString -> () -> Maybe ByteString
forall a b. a -> b -> a
const Maybe ByteString
forall a. Maybe a
Nothing) ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (Either () ByteString -> Maybe ByteString)
-> IO (Either () ByteString) -> IO (Maybe ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> 
      (IOError -> Maybe ()) -> IO ByteString -> IO (Either () ByteString)
forall e b a.
Exception e =>
(e -> Maybe b) -> IO a -> IO (Either b a)
tryJust (Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> (IOError -> Bool) -> IOError -> Maybe ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IOError -> Bool
isDoesNotExistError) (FilePath -> IO ByteString
B.readFile FilePath
fp)

-- | Embed a single existing file in your source code
-- out of list a list of paths supplied.
--
-- > import qualified Data.ByteString
-- >
-- > myFile :: Data.ByteString.ByteString
-- > myFile = $(embedOneFileOf [ "dirName/fileName", "src/dirName/fileName" ])
embedOneFileOf :: [FilePath] -> Q Exp
embedOneFileOf :: [FilePath] -> Q Exp
embedOneFileOf [FilePath]
ps =
  (IO (FilePath, ByteString) -> Q (FilePath, ByteString)
forall a. IO a -> Q a
runIO (IO (FilePath, ByteString) -> Q (FilePath, ByteString))
-> IO (FilePath, ByteString) -> Q (FilePath, ByteString)
forall a b. (a -> b) -> a -> b
$ [FilePath] -> IO (FilePath, ByteString)
readExistingFile [FilePath]
ps) Q (FilePath, ByteString)
-> ((FilePath, ByteString) -> Q Exp) -> Q Exp
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \ ( FilePath
path, ByteString
content ) -> do
#if MIN_VERSION_template_haskell(2,7,0)
    FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile FilePath
path
#endif
    ByteString -> Q Exp
bsToExp ByteString
content
  where
    readExistingFile :: [FilePath] -> IO ( FilePath, B.ByteString )
    readExistingFile :: [FilePath] -> IO (FilePath, ByteString)
readExistingFile [FilePath]
xs = do
      [FilePath]
ys <- (FilePath -> IO Bool) -> [FilePath] -> IO [FilePath]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM FilePath -> IO Bool
doesFileExist [FilePath]
xs
      case [FilePath]
ys of
        (FilePath
p:[FilePath]
_) -> FilePath -> IO ByteString
B.readFile FilePath
p IO ByteString
-> (ByteString -> IO (FilePath, ByteString))
-> IO (FilePath, ByteString)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \ ByteString
c -> (FilePath, ByteString) -> IO (FilePath, ByteString)
forall (m :: * -> *) a. Monad m => a -> m a
return ( FilePath
p, ByteString
c )
        [FilePath]
_ -> ErrorCall -> IO (FilePath, ByteString)
forall a e. Exception e => e -> a
throw (ErrorCall -> IO (FilePath, ByteString))
-> ErrorCall -> IO (FilePath, ByteString)
forall a b. (a -> b) -> a -> b
$ FilePath -> ErrorCall
ErrorCall FilePath
"Cannot find file to embed as resource"

-- | Embed a directory recursively in your source code.
--
-- > import qualified Data.ByteString
-- >
-- > myDir :: [(FilePath, Data.ByteString.ByteString)]
-- > myDir = $(embedDir "dirName")
embedDir :: FilePath -> Q Exp
embedDir :: FilePath -> Q Exp
embedDir FilePath
fp = do
    Type
typ <- [t| [(FilePath, B.ByteString)] |]
    Exp
e <- [Exp] -> Exp
ListE ([Exp] -> Exp) -> Q [Exp] -> Q Exp
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ((IO [(FilePath, ByteString)] -> Q [(FilePath, ByteString)]
forall a. IO a -> Q a
runIO (IO [(FilePath, ByteString)] -> Q [(FilePath, ByteString)])
-> IO [(FilePath, ByteString)] -> Q [(FilePath, ByteString)]
forall a b. (a -> b) -> a -> b
$ FilePath -> IO [(FilePath, ByteString)]
fileList FilePath
fp) Q [(FilePath, ByteString)]
-> ([(FilePath, ByteString)] -> Q [Exp]) -> Q [Exp]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ((FilePath, ByteString) -> Q Exp)
-> [(FilePath, ByteString)] -> Q [Exp]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (FilePath -> (FilePath, ByteString) -> Q Exp
pairToExp FilePath
fp))
    Exp -> Q Exp
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Exp -> Type -> Exp
SigE Exp
e Type
typ

-- | Embed a directory listing recursively in your source code.
--
-- > myFiles :: [FilePath]
-- > myFiles = $(embedDirListing "dirName")
--
-- @since 0.0.11
embedDirListing :: FilePath -> Q Exp
embedDirListing :: FilePath -> Q Exp
embedDirListing FilePath
fp = do
    Type
typ <- [t| [FilePath] |]
    Exp
e <- [Exp] -> Exp
ListE ([Exp] -> Exp) -> Q [Exp] -> Q Exp
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ((IO [FilePath] -> Q [FilePath]
forall a. IO a -> Q a
runIO (IO [FilePath] -> Q [FilePath]) -> IO [FilePath] -> Q [FilePath]
forall a b. (a -> b) -> a -> b
$ ((FilePath, ByteString) -> FilePath)
-> [(FilePath, ByteString)] -> [FilePath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (FilePath, ByteString) -> FilePath
forall a b. (a, b) -> a
fst ([(FilePath, ByteString)] -> [FilePath])
-> IO [(FilePath, ByteString)] -> IO [FilePath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO [(FilePath, ByteString)]
fileList FilePath
fp) Q [FilePath] -> ([FilePath] -> Q [Exp]) -> Q [Exp]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (FilePath -> Q Exp) -> [FilePath] -> Q [Exp]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM FilePath -> Q Exp
strToExp)
    Exp -> Q Exp
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Exp -> Type -> Exp
SigE Exp
e Type
typ

-- | Get a directory tree in the IO monad.
--
-- This is the workhorse of 'embedDir'
getDir :: FilePath -> IO [(FilePath, B.ByteString)]
getDir :: FilePath -> IO [(FilePath, ByteString)]
getDir = FilePath -> IO [(FilePath, ByteString)]
fileList

pairToExp :: FilePath -> (FilePath, B.ByteString) -> Q Exp
pairToExp :: FilePath -> (FilePath, ByteString) -> Q Exp
pairToExp FilePath
_root (FilePath
path, ByteString
bs) = do
#if MIN_VERSION_template_haskell(2,7,0)
    FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile (FilePath -> Q ()) -> FilePath -> Q ()
forall a b. (a -> b) -> a -> b
$ FilePath
_root FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ Char
'/' Char -> FilePath -> FilePath
forall a. a -> [a] -> [a]
: FilePath
path
#endif
    Exp
exp' <- ByteString -> Q Exp
bsToExp ByteString
bs
    Exp -> Q Exp
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$! [Maybe Exp] -> Exp
TupE
#if MIN_VERSION_template_haskell(2,16,0)
      ([Maybe Exp] -> Exp) -> [Maybe Exp] -> Exp
forall a b. (a -> b) -> a -> b
$ (Exp -> Maybe Exp) -> [Exp] -> [Maybe Exp]
forall a b. (a -> b) -> [a] -> [b]
map Exp -> Maybe Exp
forall a. a -> Maybe a
Just
#endif
      [Lit -> Exp
LitE (Lit -> Exp) -> Lit -> Exp
forall a b. (a -> b) -> a -> b
$ FilePath -> Lit
StringL FilePath
path, Exp
exp']

bsToExp :: B.ByteString -> Q Exp
#if MIN_VERSION_template_haskell(2, 5, 0)
bsToExp :: ByteString -> Q Exp
bsToExp ByteString
bs =
    Exp -> Q Exp
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE 'unsafePerformIO
      Exp -> Exp -> Exp
`AppE` (Name -> Exp
VarE 'unsafePackAddressLen
      Exp -> Exp -> Exp
`AppE` Lit -> Exp
LitE (Integer -> Lit
IntegerL (Integer -> Lit) -> Integer -> Lit
forall a b. (a -> b) -> a -> b
$ Int -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Integer) -> Int -> Integer
forall a b. (a -> b) -> a -> b
$ ByteString -> Int
B8.length ByteString
bs)
#if MIN_VERSION_template_haskell(2, 16, 0)
      Exp -> Exp -> Exp
`AppE` Lit -> Exp
LitE (Bytes -> Lit
bytesPrimL (
                let B.PS ForeignPtr Word8
ptr Int
off Int
sz = ByteString
bs
                in  ForeignPtr Word8 -> Word -> Word -> Bytes
mkBytes ForeignPtr Word8
ptr (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
off) (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
sz))))
#elif MIN_VERSION_template_haskell(2, 8, 0)
      `AppE` LitE (StringPrimL $ B.unpack bs))
#else
      `AppE` LitE (StringPrimL $ B8.unpack bs))
#endif
#else
bsToExp bs = do
    helper <- [| stringToBs |]
    let chars = B8.unpack bs
    return $! AppE helper $! LitE $! StringL chars
#endif

stringToBs :: String -> B.ByteString
stringToBs :: FilePath -> ByteString
stringToBs = FilePath -> ByteString
B8.pack

-- | Embed a single file in your source code.
--
-- > import Data.String
-- >
-- > myFile :: IsString a => a
-- > myFile = $(embedStringFile "dirName/fileName")
--
-- Since 0.0.9
embedStringFile :: FilePath -> Q Exp
embedStringFile :: FilePath -> Q Exp
embedStringFile FilePath
fp =
#if MIN_VERSION_template_haskell(2,7,0)
    FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile FilePath
fp Q () -> Q FilePath -> Q FilePath
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
#endif
  (IO FilePath -> Q FilePath
forall a. IO a -> Q a
runIO (IO FilePath -> Q FilePath) -> IO FilePath -> Q FilePath
forall a b. (a -> b) -> a -> b
$ FilePath -> IO FilePath
P.readFile FilePath
fp) Q FilePath -> (FilePath -> Q Exp) -> Q Exp
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= FilePath -> Q Exp
strToExp

-- | Embed a single existing string file in your source code
-- out of list a list of paths supplied.
--
-- Since 0.0.9
embedOneStringFileOf :: [FilePath] -> Q Exp
embedOneStringFileOf :: [FilePath] -> Q Exp
embedOneStringFileOf [FilePath]
ps =
  (IO (FilePath, FilePath) -> Q (FilePath, FilePath)
forall a. IO a -> Q a
runIO (IO (FilePath, FilePath) -> Q (FilePath, FilePath))
-> IO (FilePath, FilePath) -> Q (FilePath, FilePath)
forall a b. (a -> b) -> a -> b
$ [FilePath] -> IO (FilePath, FilePath)
readExistingFile [FilePath]
ps) Q (FilePath, FilePath) -> ((FilePath, FilePath) -> Q Exp) -> Q Exp
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \ ( FilePath
path, FilePath
content ) -> do
#if MIN_VERSION_template_haskell(2,7,0)
    FilePath -> Q ()
forall (m :: * -> *). Quasi m => FilePath -> m ()
qAddDependentFile FilePath
path
#endif
    FilePath -> Q Exp
strToExp FilePath
content
  where
    readExistingFile :: [FilePath] -> IO ( FilePath, String )
    readExistingFile :: [FilePath] -> IO (FilePath, FilePath)
readExistingFile [FilePath]
xs = do
      [FilePath]
ys <- (FilePath -> IO Bool) -> [FilePath] -> IO [FilePath]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM FilePath -> IO Bool
doesFileExist [FilePath]
xs
      case [FilePath]
ys of
        (FilePath
p:[FilePath]
_) -> FilePath -> IO FilePath
P.readFile FilePath
p IO FilePath
-> (FilePath -> IO (FilePath, FilePath)) -> IO (FilePath, FilePath)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \ FilePath
c -> (FilePath, FilePath) -> IO (FilePath, FilePath)
forall (m :: * -> *) a. Monad m => a -> m a
return ( FilePath
p, FilePath
c )
        [FilePath]
_ -> ErrorCall -> IO (FilePath, FilePath)
forall a e. Exception e => e -> a
throw (ErrorCall -> IO (FilePath, FilePath))
-> ErrorCall -> IO (FilePath, FilePath)
forall a b. (a -> b) -> a -> b
$ FilePath -> ErrorCall
ErrorCall FilePath
"Cannot find file to embed as resource"

strToExp :: String -> Q Exp
#if MIN_VERSION_template_haskell(2, 5, 0)
strToExp :: FilePath -> Q Exp
strToExp FilePath
s =
    Exp -> Q Exp
forall (m :: * -> *) a. Monad m => a -> m a
return (Exp -> Q Exp) -> Exp -> Q Exp
forall a b. (a -> b) -> a -> b
$ Name -> Exp
VarE 'fromString
      Exp -> Exp -> Exp
`AppE` Lit -> Exp
LitE (FilePath -> Lit
StringL FilePath
s)
#else
strToExp s = do
    helper <- [| fromString |]
    return $! AppE helper $! LitE $! StringL s
#endif

notHidden :: FilePath -> Bool
notHidden :: FilePath -> Bool
notHidden (Char
'.':FilePath
_) = Bool
False
notHidden FilePath
_ = Bool
True

fileList :: FilePath -> IO [(FilePath, B.ByteString)]
fileList :: FilePath -> IO [(FilePath, ByteString)]
fileList FilePath
top = FilePath -> FilePath -> IO [(FilePath, ByteString)]
fileList' FilePath
top FilePath
""

fileList' :: FilePath -> FilePath -> IO [(FilePath, B.ByteString)]
fileList' :: FilePath -> FilePath -> IO [(FilePath, ByteString)]
fileList' FilePath
realTop FilePath
top = do
    [FilePath]
allContents <- (FilePath -> Bool) -> [FilePath] -> [FilePath]
forall a. (a -> Bool) -> [a] -> [a]
filter FilePath -> Bool
notHidden ([FilePath] -> [FilePath]) -> IO [FilePath] -> IO [FilePath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO [FilePath]
getDirectoryContents (FilePath
realTop FilePath -> FilePath -> FilePath
</> FilePath
top)
    let all' :: [(FilePath, FilePath)]
all' = (FilePath -> (FilePath, FilePath))
-> [FilePath] -> [(FilePath, FilePath)]
forall a b. (a -> b) -> [a] -> [b]
map ((FilePath
top FilePath -> FilePath -> FilePath
</>) (FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> (FilePath, FilePath)
forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& (\FilePath
x -> FilePath
realTop FilePath -> FilePath -> FilePath
</> FilePath
top FilePath -> FilePath -> FilePath
</> FilePath
x)) [FilePath]
allContents
    [(FilePath, ByteString)]
files <- ((FilePath, FilePath) -> IO Bool)
-> [(FilePath, FilePath)] -> IO [(FilePath, FilePath)]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (FilePath -> IO Bool
doesFileExist (FilePath -> IO Bool)
-> ((FilePath, FilePath) -> FilePath)
-> (FilePath, FilePath)
-> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath, FilePath) -> FilePath
forall a b. (a, b) -> b
snd) [(FilePath, FilePath)]
all' IO [(FilePath, FilePath)]
-> ([(FilePath, FilePath)] -> IO [(FilePath, ByteString)])
-> IO [(FilePath, ByteString)]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
             ((FilePath, FilePath) -> IO (FilePath, ByteString))
-> [(FilePath, FilePath)] -> IO [(FilePath, ByteString)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ((FilePath, IO ByteString) -> IO (FilePath, ByteString)
forall (m :: * -> *) a b. Monad m => (a, m b) -> m (a, b)
liftPair2 ((FilePath, IO ByteString) -> IO (FilePath, ByteString))
-> ((FilePath, FilePath) -> (FilePath, IO ByteString))
-> (FilePath, FilePath)
-> IO (FilePath, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath -> IO ByteString)
-> (FilePath, FilePath) -> (FilePath, IO ByteString)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (d, b) (d, c)
second FilePath -> IO ByteString
B.readFile)
    [[(FilePath, ByteString)]]
dirs <- ((FilePath, FilePath) -> IO Bool)
-> [(FilePath, FilePath)] -> IO [(FilePath, FilePath)]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (FilePath -> IO Bool
doesDirectoryExist (FilePath -> IO Bool)
-> ((FilePath, FilePath) -> FilePath)
-> (FilePath, FilePath)
-> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath, FilePath) -> FilePath
forall a b. (a, b) -> b
snd) [(FilePath, FilePath)]
all' IO [(FilePath, FilePath)]
-> ([(FilePath, FilePath)] -> IO [[(FilePath, ByteString)]])
-> IO [[(FilePath, ByteString)]]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
            ((FilePath, FilePath) -> IO [(FilePath, ByteString)])
-> [(FilePath, FilePath)] -> IO [[(FilePath, ByteString)]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (FilePath -> FilePath -> IO [(FilePath, ByteString)]
fileList' FilePath
realTop (FilePath -> IO [(FilePath, ByteString)])
-> ((FilePath, FilePath) -> FilePath)
-> (FilePath, FilePath)
-> IO [(FilePath, ByteString)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath, FilePath) -> FilePath
forall a b. (a, b) -> a
fst)
    [(FilePath, ByteString)] -> IO [(FilePath, ByteString)]
forall (m :: * -> *) a. Monad m => a -> m a
return ([(FilePath, ByteString)] -> IO [(FilePath, ByteString)])
-> [(FilePath, ByteString)] -> IO [(FilePath, ByteString)]
forall a b. (a -> b) -> a -> b
$ ((FilePath, ByteString) -> (FilePath, ByteString) -> Ordering)
-> [(FilePath, ByteString)] -> [(FilePath, ByteString)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (((FilePath, ByteString) -> FilePath)
-> (FilePath, ByteString) -> (FilePath, ByteString) -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (FilePath, ByteString) -> FilePath
forall a b. (a, b) -> a
fst) ([(FilePath, ByteString)] -> [(FilePath, ByteString)])
-> [(FilePath, ByteString)] -> [(FilePath, ByteString)]
forall a b. (a -> b) -> a -> b
$ [[(FilePath, ByteString)]] -> [(FilePath, ByteString)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[(FilePath, ByteString)]] -> [(FilePath, ByteString)])
-> [[(FilePath, ByteString)]] -> [(FilePath, ByteString)]
forall a b. (a -> b) -> a -> b
$ [(FilePath, ByteString)]
files [(FilePath, ByteString)]
-> [[(FilePath, ByteString)]] -> [[(FilePath, ByteString)]]
forall a. a -> [a] -> [a]
: [[(FilePath, ByteString)]]
dirs

liftPair2 :: Monad m => (a, m b) -> m (a, b)
liftPair2 :: (a, m b) -> m (a, b)
liftPair2 (a
a, m b
b) = m b
b m b -> (b -> m (a, b)) -> m (a, b)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \b
b' -> (a, b) -> m (a, b)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
a, b
b')

magic :: B.ByteString -> B.ByteString
magic :: ByteString -> ByteString
magic ByteString
x = [ByteString] -> ByteString
B8.concat [ByteString
"fe", ByteString
x]

sizeLen :: Int
sizeLen :: Int
sizeLen = Int
20

getInner :: B.ByteString -> B.ByteString
getInner :: ByteString -> ByteString
getInner ByteString
b =
    let (ByteString
sizeBS, ByteString
rest) = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
sizeLen ByteString
b
     in case ReadS Int
forall a. Read a => ReadS a
reads ReadS Int -> ReadS Int
forall a b. (a -> b) -> a -> b
$ ByteString -> FilePath
B8.unpack ByteString
sizeBS of
            (Int
i, FilePath
_):[(Int, FilePath)]
_ -> Int -> ByteString -> ByteString
B.take Int
i ByteString
rest
            [] -> FilePath -> ByteString
forall a. HasCallStack => FilePath -> a
error FilePath
"Data.FileEmbed (getInner): Your dummy space has been corrupted."

padSize :: Int -> String
padSize :: Int -> FilePath
padSize Int
i =
    let s :: FilePath
s = Int -> FilePath
forall a. Show a => a -> FilePath
show Int
i
     in Int -> Char -> FilePath
forall a. Int -> a -> [a]
replicate (Int
sizeLen Int -> Int -> Int
forall a. Num a => a -> a -> a
- FilePath -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length FilePath
s) Char
'0' FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
s

#if MIN_VERSION_template_haskell(2,5,0)
-- | Allocate the given number of bytes in the generate executable. That space
-- can be filled up with the 'inject' and 'injectFile' functions.
dummySpace :: Int -> Q Exp
dummySpace :: Int -> Q Exp
dummySpace = ByteString -> Int -> Q Exp
dummySpaceWith ByteString
"MS"

-- | Like 'dummySpace', but takes a postfix for the magic string.  In
-- order for this to work, the same postfix must be used by 'inject' /
-- 'injectFile'.  This allows an executable to have multiple
-- 'ByteString's injected into it, without encountering collisions.
--
-- Since 0.0.8
dummySpaceWith :: B.ByteString -> Int -> Q Exp
dummySpaceWith :: ByteString -> Int -> Q Exp
dummySpaceWith ByteString
postfix Int
space = do
    let size :: FilePath
size = Int -> FilePath
padSize Int
space
        magic' :: ByteString
magic' = ByteString -> ByteString
magic ByteString
postfix
        start :: FilePath
start = ByteString -> FilePath
B8.unpack ByteString
magic' FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
size
        magicLen :: Int
magicLen = ByteString -> Int
B8.length ByteString
magic'
        len :: Int
len = Int
magicLen Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sizeLen Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
space
        chars :: Exp
chars = Lit -> Exp
LitE (Lit -> Exp) -> Lit -> Exp
forall a b. (a -> b) -> a -> b
$ [Word8] -> Lit
StringPrimL ([Word8] -> Lit) -> [Word8] -> Lit
forall a b. (a -> b) -> a -> b
$
#if MIN_VERSION_template_haskell(2,6,0)
            (Char -> Word8) -> FilePath -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> Word8
forall a. Enum a => Int -> a
toEnum (Int -> Word8) -> (Char -> Int) -> Char -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Int
forall a. Enum a => a -> Int
fromEnum) (FilePath -> [Word8]) -> FilePath -> [Word8]
forall a b. (a -> b) -> a -> b
$
#endif
            FilePath
start FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ Int -> Char -> FilePath
forall a. Int -> a -> [a]
replicate Int
space Char
'0'
    [| getInner (B.drop magicLen (unsafePerformIO (unsafePackAddressLen len $(return chars)))) |]
#endif

-- | Inject some raw data inside a @ByteString@ containing empty, dummy space
-- (allocated with @dummySpace@). Typically, the original @ByteString@ is an
-- executable read from the filesystem.
inject :: B.ByteString -- ^ bs to inject
       -> B.ByteString -- ^ original BS containing dummy
       -> Maybe B.ByteString -- ^ new BS, or Nothing if there is insufficient dummy space
inject :: ByteString -> ByteString -> Maybe ByteString
inject = ByteString -> ByteString -> ByteString -> Maybe ByteString
injectWith ByteString
"MS"

-- | Like 'inject', but takes a postfix for the magic string.
--
-- Since 0.0.8
injectWith :: B.ByteString -- ^ postfix of magic string
           -> B.ByteString -- ^ bs to inject
           -> B.ByteString -- ^ original BS containing dummy
           -> Maybe B.ByteString -- ^ new BS, or Nothing if there is insufficient dummy space
injectWith :: ByteString -> ByteString -> ByteString -> Maybe ByteString
injectWith ByteString
postfix ByteString
toInj ByteString
orig =
    if Int
toInjL Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
size
        then Maybe ByteString
forall a. Maybe a
Nothing
        else ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (ByteString -> Maybe ByteString) -> ByteString -> Maybe ByteString
forall a b. (a -> b) -> a -> b
$ [ByteString] -> ByteString
B.concat [ByteString
before, ByteString
magic', FilePath -> ByteString
B8.pack (FilePath -> ByteString) -> FilePath -> ByteString
forall a b. (a -> b) -> a -> b
$ Int -> FilePath
padSize Int
toInjL, ByteString
toInj, FilePath -> ByteString
B8.pack (FilePath -> ByteString) -> FilePath -> ByteString
forall a b. (a -> b) -> a -> b
$ Int -> Char -> FilePath
forall a. Int -> a -> [a]
replicate (Int
size Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
toInjL) Char
'0', ByteString
after]
  where
    magic' :: ByteString
magic' = ByteString -> ByteString
magic ByteString
postfix
    toInjL :: Int
toInjL = ByteString -> Int
B.length ByteString
toInj
    (ByteString
before, ByteString
rest) = ByteString -> ByteString -> (ByteString, ByteString)
B.breakSubstring ByteString
magic' ByteString
orig
    (ByteString
sizeBS, ByteString
rest') = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
sizeLen (ByteString -> (ByteString, ByteString))
-> ByteString -> (ByteString, ByteString)
forall a b. (a -> b) -> a -> b
$ Int -> ByteString -> ByteString
B.drop (ByteString -> Int
B8.length ByteString
magic') ByteString
rest
    size :: Int
size = case ReadS Int
forall a. Read a => ReadS a
reads ReadS Int -> ReadS Int
forall a b. (a -> b) -> a -> b
$ ByteString -> FilePath
B8.unpack ByteString
sizeBS of
            (Int
i, FilePath
_):[(Int, FilePath)]
_ -> Int
i
            [] -> FilePath -> Int
forall a. HasCallStack => FilePath -> a
error (FilePath -> Int) -> FilePath -> Int
forall a b. (a -> b) -> a -> b
$ FilePath
"Data.FileEmbed (inject): Your dummy space has been corrupted. Size is: " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ ByteString -> FilePath
forall a. Show a => a -> FilePath
show ByteString
sizeBS
    after :: ByteString
after = Int -> ByteString -> ByteString
B.drop Int
size ByteString
rest'

-- | Same as 'inject', but instead of performing the injecting in memory, read
-- the contents from the filesystem and write back to a different file on the
-- filesystem.
injectFile :: B.ByteString -- ^ bs to inject
           -> FilePath -- ^ template file
           -> FilePath -- ^ output file
           -> IO ()
injectFile :: ByteString -> FilePath -> FilePath -> IO ()
injectFile = ByteString -> ByteString -> FilePath -> FilePath -> IO ()
injectFileWith ByteString
"MS"

-- | Like 'injectFile', but takes a postfix for the magic string.
--
-- Since 0.0.8
injectFileWith :: B.ByteString -- ^ postfix of magic string
               -> B.ByteString -- ^ bs to inject
               -> FilePath -- ^ template file
               -> FilePath -- ^ output file
               -> IO ()
injectFileWith :: ByteString -> ByteString -> FilePath -> FilePath -> IO ()
injectFileWith ByteString
postfix ByteString
inj FilePath
srcFP FilePath
dstFP = do
    ByteString
src <- FilePath -> IO ByteString
B.readFile FilePath
srcFP
    case ByteString -> ByteString -> ByteString -> Maybe ByteString
injectWith ByteString
postfix ByteString
inj ByteString
src of
        Maybe ByteString
Nothing -> FilePath -> IO ()
forall a. HasCallStack => FilePath -> a
error FilePath
"Insufficient dummy space"
        Just ByteString
dst -> FilePath -> ByteString -> IO ()
B.writeFile FilePath
dstFP ByteString
dst

{- $inject

The inject system allows arbitrary content to be embedded inside a Haskell
executable, post compilation. Typically, file-embed allows you to read some
contents from the file system at compile time and embed them inside your
executable. Consider a case, instead, where you would want to embed these
contents after compilation. Two real-world examples are:

* You would like to embed a hash of the executable itself, for sanity checking in a network protocol. (Obviously the hash will change after you embed the hash.)

* You want to create a self-contained web server that has a set of content, but will need to update the content on machines that do not have access to GHC.

The typical workflow use:

* Use 'dummySpace' or 'dummySpaceWith' to create some empty space in your executable

* Use 'injectFile' or 'injectFileWith' from a separate utility to modify that executable to have the updated content.

The reason for the @With@-variant of the functions is for cases where you wish
to inject multiple different kinds of content, and therefore need control over
the magic key. If you know for certain that there will only be one dummy space
available, you can use the non-@With@ variants.

-}

-- | Take a relative file path and attach it to the root of the current
-- project.
--
-- The idea here is that, when building with Stack, the build will always be
-- executed with a current working directory of the root of the project (where
-- your .cabal file is located). However, if you load up multiple projects with
-- @stack ghci@, the working directory may be something else entirely.
--
-- This function looks at the source location of the Haskell file calling it,
-- finds the first parent directory with a .cabal file, and uses that as the
-- root directory for fixing the relative path.
--
-- @$(makeRelativeToProject "data/foo.txt" >>= embedFile)@
--
-- @since 0.0.10
makeRelativeToProject :: FilePath -> Q FilePath
makeRelativeToProject :: FilePath -> Q FilePath
makeRelativeToProject = (FilePath -> Bool) -> FilePath -> Q FilePath
makeRelativeToLocationPredicate ((FilePath -> Bool) -> FilePath -> Q FilePath)
-> (FilePath -> Bool) -> FilePath -> Q FilePath
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath -> Bool
forall a. Eq a => a -> a -> Bool
(==) FilePath
".cabal" (FilePath -> Bool) -> (FilePath -> FilePath) -> FilePath -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> FilePath
takeExtension

-- | Take a predicate to infer the project root and a relative file path, the given file path is then attached to the inferred project root
--
-- This function looks at the source location of the Haskell file calling it,
-- finds the first parent directory with a file matching the given predicate, and uses that as the
-- root directory for fixing the relative path.
--
-- @$(makeRelativeToLocationPredicate ((==) ".cabal" . takeExtension) "data/foo.txt" >>= embedFile)@
--
-- @since 0.0.15.0
makeRelativeToLocationPredicate :: (FilePath -> Bool) -> FilePath -> Q FilePath
makeRelativeToLocationPredicate :: (FilePath -> Bool) -> FilePath -> Q FilePath
makeRelativeToLocationPredicate FilePath -> Bool
isTargetFile FilePath
rel = do
    Loc
loc <- Q Loc
forall (m :: * -> *). Quasi m => m Loc
qLocation
    IO FilePath -> Q FilePath
forall a. IO a -> Q a
runIO (IO FilePath -> Q FilePath) -> IO FilePath -> Q FilePath
forall a b. (a -> b) -> a -> b
$ do
        FilePath
srcFP <- FilePath -> IO FilePath
canonicalizePath (FilePath -> IO FilePath) -> FilePath -> IO FilePath
forall a b. (a -> b) -> a -> b
$ Loc -> FilePath
loc_filename Loc
loc
        Maybe FilePath
mdir <- FilePath -> IO (Maybe FilePath)
findProjectDir FilePath
srcFP
        case Maybe FilePath
mdir of
            Maybe FilePath
Nothing -> FilePath -> IO FilePath
forall a. HasCallStack => FilePath -> a
error (FilePath -> IO FilePath) -> FilePath -> IO FilePath
forall a b. (a -> b) -> a -> b
$ FilePath
"Could not find .cabal file for path: " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
srcFP
            Just FilePath
dir -> FilePath -> IO FilePath
forall (m :: * -> *) a. Monad m => a -> m a
return (FilePath -> IO FilePath) -> FilePath -> IO FilePath
forall a b. (a -> b) -> a -> b
$ FilePath
dir FilePath -> FilePath -> FilePath
</> FilePath
rel
  where
    findProjectDir :: FilePath -> IO (Maybe FilePath)
findProjectDir FilePath
x = do
        let dir :: FilePath
dir = FilePath -> FilePath
takeDirectory FilePath
x
        if FilePath
dir FilePath -> FilePath -> Bool
forall a. Eq a => a -> a -> Bool
== FilePath
x
            then Maybe FilePath -> IO (Maybe FilePath)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe FilePath
forall a. Maybe a
Nothing
            else do
                [FilePath]
contents <- FilePath -> IO [FilePath]
getDirectoryContents FilePath
dir
                if (FilePath -> Bool) -> [FilePath] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any FilePath -> Bool
isTargetFile [FilePath]
contents
                    then Maybe FilePath -> IO (Maybe FilePath)
forall (m :: * -> *) a. Monad m => a -> m a
return (FilePath -> Maybe FilePath
forall a. a -> Maybe a
Just FilePath
dir)
                    else FilePath -> IO (Maybe FilePath)
findProjectDir FilePath
dir