summaryrefslogtreecommitdiffstats
path: root/tv/5pkgs/haskell/th-env/src
diff options
context:
space:
mode:
authormakefu <github@syntax-fehler.de>2020-10-23 21:02:02 +0200
committermakefu <github@syntax-fehler.de>2020-10-23 21:02:02 +0200
commite8b6cc0587929a7ebd0d00f83d298640b20b055f (patch)
treee0f813b8264119a84d6b8c32fa68041c8541ab59 /tv/5pkgs/haskell/th-env/src
parentfd41a76d4cab2765f9ef95ce5322b7bffe52b8a7 (diff)
parent242530680d5dcb37a5a023d0b8f6155ab441cead (diff)
Merge remote-tracking branch 'lass/master'
Diffstat (limited to 'tv/5pkgs/haskell/th-env/src')
-rw-r--r--tv/5pkgs/haskell/th-env/src/THEnv.hs49
1 files changed, 49 insertions, 0 deletions
diff --git a/tv/5pkgs/haskell/th-env/src/THEnv.hs b/tv/5pkgs/haskell/th-env/src/THEnv.hs
new file mode 100644
index 000000000..b04f2ce0b
--- /dev/null
+++ b/tv/5pkgs/haskell/th-env/src/THEnv.hs
@@ -0,0 +1,49 @@
+{-# LANGUAGE TemplateHaskell #-}
+module THEnv
+ (
+ -- * Compile-time configuration
+ lookupCompileEnv
+ , lookupCompileEnvExp
+ , getCompileEnv
+ , getCompileEnvExp
+ , fileAsString
+ ) where
+
+import Control.Monad
+import qualified Data.Text as T
+import qualified Data.Text.IO as T
+import Language.Haskell.TH
+import Language.Haskell.TH.Syntax (Lift(..))
+import System.Environment (getEnvironment)
+
+-- Functions that work with compile-time configuration
+
+-- | Looks up a compile-time environment variable.
+lookupCompileEnv :: String -> Q (Maybe String)
+lookupCompileEnv key = lookup key `liftM` runIO getEnvironment
+
+-- | Looks up a compile-time environment variable. The result is a TH
+-- expression of type @Maybe String@.
+lookupCompileEnvExp :: String -> Q Exp
+lookupCompileEnvExp = (`sigE` [t| Maybe String |]) . lift <=< lookupCompileEnv
+ -- We need to explicly type the result so that things like `print Nothing`
+ -- work.
+
+-- | Looks up an compile-time environment variable and fail, if it's not
+-- present.
+getCompileEnv :: String -> Q String
+getCompileEnv key =
+ lookupCompileEnv key >>=
+ maybe (fail $ "Environment variable " ++ key ++ " not defined") return
+
+-- | Looks up an compile-time environment variable and fail, if it's not
+-- present. The result is a TH expression of type @String@.
+getCompileEnvExp :: String -> Q Exp
+getCompileEnvExp = lift <=< getCompileEnv
+
+-- | Loads the content of a file as a string constant expression.
+-- The given path is relative to the source directory.
+fileAsString :: FilePath -> Q Exp
+fileAsString = do
+ -- addDependentFile path -- works only with template-haskell >= 2.7
+ stringE . T.unpack . T.strip <=< runIO . T.readFile