@@ -19,6 +19,7 @@
1919module Data.FileEmbed
2020 ( -- * Embed at compile time
2121 embedFile
22+ , embedFileIfExists
2223 , embedOneFileOf
2324 , embedDir
2425 , embedDirListing
@@ -60,13 +61,14 @@ import qualified Data.ByteString.Internal as B
6061#endif
6162import System.Directory (doesDirectoryExist, doesFileExist,
6263 getDirectoryContents, canonicalizePath)
63−import Control.Exception (throw, ErrorCall(..))
64−import Control.Monad (filterM)
64+import Control.Exception (throw, tryJust, ErrorCall(..))
65+import Control.Monad (filterM, guard)
6566import qualified Data.ByteString as B
6667import qualified Data.ByteString.Char8 as B8
6768import Control.Arrow ((&&&), second)
6869import Control.Applicative ((<$>))
6970import Data.ByteString.Unsafe (unsafePackAddressLen)
71+import System.IO.Error (isDoesNotExistError)
7072import System.IO.Unsafe (unsafePerformIO)
7173import System.FilePath ((</>), takeDirectory, takeExtension)
7274import Data.String (fromString)
@@ -87,6 +89,31 @@ embedFile fp =
8789#endif
8890 (runIO $ B.readFile fp) >>= bsToExp
8991
92+-- | Maybe embed a single file in your source code depending on whether or not file exists.
93+--
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.
96+--
97+-- > import qualified Data.ByteString
98+-- >
99+-- > maybeMyFile :: Maybe Data.ByteString.ByteString
100+-- > maybeMyFile = $(embedFileIfExists "dirName/fileName")
101+embedFileIfExists :: FilePath -> Q Exp
102+embedFileIfExists fp = do
103+ mbs <- runIO maybeFile
104+ case mbs of
105+ Nothing -> [| Nothing |]
106+ Just bs -> do
107+#if MIN_VERSION_template_haskell(2,7,0)
108+ qAddDependentFile fp
109+#endif
110+ [| Just $(bsToExp bs) |]
111+ where
112+ maybeFile :: IO (Maybe B.ByteString)
113+ maybeFile =
114+ either (const Nothing) Just <$>
115+ tryJust (guard . isDoesNotExistError) (B.readFile fp)
116+
90117-- | Embed a single existing file in your source code
91118-- out of list a list of paths supplied.
92119--