git.iko.soy/typeable/file-embed
on master help sign in
added 'embedFileIfExists'
commit4a280ee4fc6954950db587352b49bbab6cd36828 authorCharlie Durham <cpdurham@protonmail.com> dateSun 9 May 2021, 22:40 (5 years ago) parenta2af89f
1 file changed+24−2
Data/FileEmbed.hs+24−2
Data/FileEmbed.hs+24−2
@@ -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,26 @@ 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: Does not use `qAddDependentFile` to force a recompile depending on changes to or appearance of the file.
95+--
96+-- > import qualified Data.ByteString
97+-- >
98+-- > maybeMyFile :: Maybe Data.ByteString.ByteString
99+-- > maybeMyFile = $(embedFileIfExists "dirName/fileName")
100+embedFileIfExists :: FilePath -> Q Exp
101+embedFileIfExists fp = runIO maybeFile >>= maybeBsToExp
102+ where
103+ maybeFile :: IO (Maybe B.ByteString)
104+ maybeFile =
105+ either (const Nothing) Just <$>
106+ tryJust (guard . isDoesNotExistError) (B.readFile fp)
107+
108+ maybeBsToExp :: Maybe B.ByteString -> Q Exp
109+ maybeBsToExp Nothing = [| Nothing |]
110+ maybeBsToExp (Just bs) = [| Just $(bsToExp bs) |]
111+
90112-- | Embed a single existing file in your source code
91113-- out of list a list of paths supplied.
92114--