on 63c7b21 help sign in
51 lines 1.7 kB history raw
1{-# LANGUAGE OverloadedStrings #-}
2module Obelisk.ExecutableConfig.Inject where
4import Control.Monad (mapM_)
5import Control.Monad.IO.Class (MonadIO, liftIO)
6import Data.Semigroup ((<>))
7import Data.ByteString (ByteString)
8import Data.Text (Text)
9import qualified Data.Text as T
10import qualified Data.Text.IO as T
11import Reflex.Dom.Core hiding (value)
12import System.Directory
13import System.FilePath ((</>))
15-- | Produces a @<script>@ tag containing the contents of the config item,
16-- rendered as a 'ByteString'.
17inject :: FilePath -> IO ByteString
18inject key = do
19 value <- T.readFile key
20 fmap snd $ renderStatic $ injectPure (T.pack key) value
22-- | Produces a @<script>@ tag with an @id@ attribute containing the key and
23-- whose value is the provided configuration
24injectPure :: DomBuilder t m => Text -> Text -> m ()
25injectPure key value =
26 let attrs = ("type" =: "text/plain" <> "id" =: ("config-" <> key))
27 in elAttr "script" attrs $ text value
29-- | Scans the "common" and "frontend" configuration folders and produces
30-- injectable @<script>@ tags containing the configuration keys (filepaths) and
31-- values.
32injectExecutableConfigs :: (MonadIO m, DomBuilder t m) => m ()
33injectExecutableConfigs = do
34 cfgC <- getConfigs "config/common"
35 cfgF <- getConfigs "config/frontend"
36 mapM_ (uncurry injectPure) (cfgC <> cfgF)
38getConfigs :: MonadIO m => FilePath -> m [(Text, Text)]
39getConfigs fp = liftIO $ do
40 dir <- doesDirectoryExist fp
41 if dir
42 then do
43 ps <- listDirectory fp
44 fmap concat $ mapM (\p -> getConfigs $ fp </> p) ps
45 else do
46 file <- doesFileExist fp
47 if file
48 then do
49 f <- T.readFile fp
50 return [(T.pack fp, f)]
51 else return []