@@ -22,6 +22,9 @@ module Data.FileEmbed
22 , embedOneFileOf
22 , embedOneFileOf
23 , embedDir
23 , embedDir
25+ -- * Embed as a IsString
27+ , embedOneStringFileOf
25 -- * Inject into an executable
28 -- * Inject into an executable
26 -- $inject
29 -- $inject
27#if MIN_VERSION_template_haskell(2,5,0)
30#if MIN_VERSION_template_haskell(2,5,0)
@@ -35,6 +38,7 @@ module Data.FileEmbed
35 -- * Internal
38 -- * Internal
36 , stringToBs
39 , stringToBs
40import Language.Haskell.TH.Syntax
44import Language.Haskell.TH.Syntax
@@ -61,6 +65,8 @@ import Control.Applicative ((<$>))
61import Data.ByteString.Unsafe (unsafePackAddressLen)
65import Data.ByteString.Unsafe (unsafePackAddressLen)
62import System.IO.Unsafe (unsafePerformIO)
66import System.IO.Unsafe (unsafePerformIO)
63import System.FilePath ((</>))
67import System.FilePath ((</>))
68+import Data.String (fromString)
65-- | Embed a single file in your source code.
71-- | Embed a single file in your source code.
@@ -144,6 +150,47 @@ bsToExp bs = do
144stringToBs :: String -> B.ByteString
150stringToBs :: String -> B.ByteString
145stringToBs = B8.pack
151stringToBs = B8.pack
153+-- | Embed a single file in your source code.
155+-- > import Data.String
157+-- > myFile :: IsString a => a
158+-- > myFile = $(embedStringFile "dirName/fileName")
159+embedStringFile :: FilePath -> Q Exp
161+#if MIN_VERSION_template_haskell(2,7,0)
162+ qAddDependentFile fp >>
164+ (runIO $ P.readFile fp) >>= strToExp
166+-- | Embed a single existing string file in your source code
167+-- out of list a list of paths supplied.
168+embedOneStringFileOf :: [FilePath] -> Q Exp
169+embedOneStringFileOf ps =
170+ (runIO $ readExistingFile ps) >>= \ ( path, content ) -> do
171+#if MIN_VERSION_template_haskell(2,7,0)
172+ qAddDependentFile path
176+ readExistingFile :: [FilePath] -> IO ( FilePath, String )
177+ readExistingFile xs = do
178+ ys <- filterM doesFileExist xs
180+ (p:_) -> P.readFile p >>= \ c -> return ( p, c )
181+ _ -> throw $ ErrorCall "Cannot find file to embed as resource"
183+strToExp :: String -> Q Exp
184+#if MIN_VERSION_template_haskell(2, 5, 0)
186+ return $ VarE 'fromString
187+ `AppE` LitE (StringL s)
190+ helper <- [| fromString |]
191+ return $! AppE helper $! LitE $! StringL s
147notHidden :: FilePath -> Bool
194notHidden :: FilePath -> Bool
148notHidden ('.':_) = False
195notHidden ('.':_) = False
149notHidden _ = True
196notHidden _ = True