summaryrefslogtreecommitdiffhomepage
path: root/src/Xmobar/System/Environment.hs
blob: 0491bccecc535add09e237b027ef4b9d8a688c75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
-----------------------------------------------------------------------------
-- |
-- Module      :  XMobar.Environment
-- Copyright   :  (c) William Song
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Will Song <incertia@incertia.net>
-- Stability   :  stable
-- Portability :  portable
--
-- A function to expand environment variables in strings
--
-----------------------------------------------------------------------------
module Xmobar.System.Environment(expandEnv) where

import qualified Data.Maybe as M
import qualified System.Environment as E

expandEnv :: String -> IO String
expandEnv "" = return ""
expandEnv (c:s) = case c of
  '$'       -> do
    envVar <- M.fromMaybe "" <$> E.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 (cc:_) =
              case cc of
                't' -> "\t"
                'n' -> "\n"
                '$' -> "$"
                _   -> [cc]
            escString [] = ""

  _    -> do
    remainder <- expandEnv s
    return $ c : remainder