git.iko.soy/typeable/file-embed
on master help sign in
Add embedStringFile and embedOneStringFileOf
commit40285aa01ac52eb5b804e07fe8e7cd5da0be002e authorOleg Grenrus <oleg.grenrus@iki.fi> dateThu 13 Aug 2015, 23:45 (11 years ago) parent793d985
1 file changed+47
Data/FileEmbed.hs+47
Data/FileEmbed.hs+47
@@ -22,6 +22,9 @@ module Data.FileEmbed
2222 , embedOneFileOf
2323 , embedDir
2424 , getDir
25+ -- * Embed as a IsString
26+ , embedStringFile
27+ , embedOneStringFileOf
2528 -- * Inject into an executable
2629 -- $inject
2730#if MIN_VERSION_template_haskell(2,5,0)
@@ -35,6 +38,7 @@ module Data.FileEmbed
3538 -- * Internal
3639 , stringToBs
3740 , bsToExp
41+ , strToExp
3842 ) where
3943
4044import Language.Haskell.TH.Syntax
@@ -61,6 +65,8 @@ import Control.Applicative ((<$>))
6165import Data.ByteString.Unsafe (unsafePackAddressLen)
6266import System.IO.Unsafe (unsafePerformIO)
6367import System.FilePath ((</>))
68+import Data.String (fromString)
69+import Prelude as P
6470
6571-- | Embed a single file in your source code.
6672--
@@ -144,6 +150,47 @@ bsToExp bs = do
144150stringToBs :: String -> B.ByteString
145151stringToBs = B8.pack
146152
153+-- | Embed a single file in your source code.
154+--
155+-- > import Data.String
156+-- >
157+-- > myFile :: IsString a => a
158+-- > myFile = $(embedStringFile "dirName/fileName")
159+embedStringFile :: FilePath -> Q Exp
160+embedStringFile fp =
161+#if MIN_VERSION_template_haskell(2,7,0)
162+ qAddDependentFile fp >>
163+#endif
164+ (runIO $ P.readFile fp) >>= strToExp
165+
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
173+#endif
174+ strToExp content
175+ where
176+ readExistingFile :: [FilePath] -> IO ( FilePath, String )
177+ readExistingFile xs = do
178+ ys <- filterM doesFileExist xs
179+ case ys of
180+ (p:_) -> P.readFile p >>= \ c -> return ( p, c )
181+ _ -> throw $ ErrorCall "Cannot find file to embed as resource"
182+
183+strToExp :: String -> Q Exp
184+#if MIN_VERSION_template_haskell(2, 5, 0)
185+strToExp s =
186+ return $ VarE 'fromString
187+ `AppE` LitE (StringL s)
188+#else
189+strToExp s = do
190+ helper <- [| fromString |]
191+ return $! AppE helper $! LitE $! StringL s
192+#endif
193+
147194notHidden :: FilePath -> Bool
148195notHidden ('.':_) = False
149196notHidden _ = True