@@ -19,6 +19,7 @@
19module Data.FileEmbed
19module Data.FileEmbed
20 ( -- * Embed at compile time
20 ( -- * Embed at compile time
22 , embedOneFileOf
23 , embedOneFileOf
23 , embedDir
24 , embedDir
24 , embedDirListing
25 , embedDirListing
@@ -60,13 +61,14 @@ import qualified Data.ByteString.Internal as B
61import System.Directory (doesDirectoryExist, doesFileExist,
62import System.Directory (doesDirectoryExist, doesFileExist,
62 getDirectoryContents, canonicalizePath)
63 getDirectoryContents, canonicalizePath)
63−import Control.Exception (throw, ErrorCall(..))
64+import Control.Exception (throw, tryJust, ErrorCall(..))
64−import Control.Monad (filterM)
65+import Control.Monad (filterM, guard)
65import qualified Data.ByteString as B
66import qualified Data.ByteString as B
66import qualified Data.ByteString.Char8 as B8
67import qualified Data.ByteString.Char8 as B8
67import Control.Arrow ((&&&), second)
68import Control.Arrow ((&&&), second)
68import Control.Applicative ((<$>))
69import Control.Applicative ((<$>))
69import Data.ByteString.Unsafe (unsafePackAddressLen)
70import Data.ByteString.Unsafe (unsafePackAddressLen)
71+import System.IO.Error (isDoesNotExistError)
70import System.IO.Unsafe (unsafePerformIO)
72import System.IO.Unsafe (unsafePerformIO)
71import System.FilePath ((</>), takeDirectory, takeExtension)
73import System.FilePath ((</>), takeDirectory, takeExtension)
72import Data.String (fromString)
74import Data.String (fromString)
@@ -87,6 +89,31 @@ embedFile fp =
88 (runIO $ B.readFile fp) >>= bsToExp
90 (runIO $ B.readFile fp) >>= bsToExp
92+-- | Maybe embed a single file in your source code depending on whether or not file exists.
94+-- Warning: When a build is compiled with the file missing, a recompile when the file exists might not trigger an embed of the file.
95+-- You might try to fix this by doing a clean build.
97+-- > import qualified Data.ByteString
99+-- > maybeMyFile :: Maybe Data.ByteString.ByteString
100+-- > maybeMyFile = $(embedFileIfExists "dirName/fileName")
101+embedFileIfExists :: FilePath -> Q Exp
102+embedFileIfExists fp = do
103+ mbs <- runIO maybeFile
105+ Nothing -> [| Nothing |]
107+#if MIN_VERSION_template_haskell(2,7,0)
108+ qAddDependentFile fp
110+ [| Just $(bsToExp bs) |]
112+ maybeFile :: IO (Maybe B.ByteString)
114+ either (const Nothing) Just <$>
115+ tryJust (guard . isDoesNotExistError) (B.readFile fp)
90-- | Embed a single existing file in your source code
117-- | Embed a single existing file in your source code
91-- out of list a list of paths supplied.
118-- out of list a list of paths supplied.