From a93755b2d1e9efbd63723f5302ca7c8f43521aa8 Mon Sep 17 00:00:00 2001 From: Will Song Date: Sat, 16 Jul 2016 16:15:33 -0500 Subject: Add expandEnv function and use it in PipeReader family of monitors expandEnv takes a string and expands the environment variables it can find. variable substringing (e.g. ${VAR:1} to lop off the first character) is not supported, but $VAR and ${VAR} formats are, with the former being delimited by punctuation, but not underscores. --- src/Environment.hs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/Environment.hs (limited to 'src/Environment.hs') diff --git a/src/Environment.hs b/src/Environment.hs new file mode 100644 index 0000000..ebdf733 --- /dev/null +++ b/src/Environment.hs @@ -0,0 +1,48 @@ +----------------------------------------------------------------------------- +-- | +-- Module : XMobar.Environment +-- Copyright : (c) William Song +-- License : BSD-style (see LICENSE) +-- +-- Maintainer : Will Song +-- Stability : stable +-- Portability : portable +-- +-- A function to expand environment variables in strings +-- +----------------------------------------------------------------------------- +module Environment where + +import Data.Maybe (fromMaybe) +import System.Environment (lookupEnv) + +expandEnv :: String -> IO String +expandEnv "" = return "" +expandEnv (c:s) = case c of + '$' -> do + envVar <- fromMaybe "" <$> lookupEnv e + remainder <- expandEnv s' + return $ envVar ++ remainder + where (e, s') = getVar s + getVar "" = ("", "") + getVar ('{':s) = (takeUntil "}" s, drop 1 . dropUntil "}" $ s) + getVar s = (takeUntil filterstr s, dropUntil filterstr s) + filterstr = ",./? \t;:\"'~`!@#$%^&*()<>-+=\\|" + takeUntil f = takeWhile (not . flip elem f) + dropUntil f = dropWhile (not . flip elem f) + + '\\' -> case s == "" of + True -> return "\\" + False -> do + remainder <- expandEnv $ drop 1 s + return $ escString s ++ remainder + where escString s = let (cc:ss) = s in + case cc of + 't' -> "\t" + 'n' -> "\n" + '$' -> "$" + _ -> [cc] + + _ -> do + remainder <- expandEnv s + return $ c : remainder -- cgit v1.2.3