Merge branch 'master' of code.garrettmills.dev:garrettmills/haskell
This commit is contained in:
commit
349c3c6e66
67
fenv.hs
Normal file
67
fenv.hs
Normal file
@ -0,0 +1,67 @@
|
||||
import System.Environment
|
||||
import System.Directory
|
||||
import System.IO
|
||||
import Data.List
|
||||
|
||||
type EnvKey = String
|
||||
type EnvValue = String
|
||||
|
||||
data EnvFile =
|
||||
End
|
||||
| Entry EnvKey EnvValue EnvFile
|
||||
deriving (Show,Eq,Read)
|
||||
|
||||
dispatch :: [(String, [String] -> IO ())]
|
||||
dispatch = [
|
||||
("get", cliGet),
|
||||
("set", cliSet),
|
||||
("unset", cliUnset)
|
||||
]
|
||||
|
||||
main = do
|
||||
let f = (Entry "foo" "bar" End)
|
||||
putStrLn (show f)
|
||||
|
||||
cliGet :: [String] -> IO ()
|
||||
cliGet (name:_) = do
|
||||
env <- getEnvFile
|
||||
case (getEntry env name) of
|
||||
(Just value) -> putStrLn value
|
||||
Nothing -> putStrLn "ERROR: No value defined"
|
||||
|
||||
setEntry :: EnvFile -> EnvKey -> EnvValue -> EnvFile
|
||||
setEntry env key value = let env'=(removeEntry env key) in
|
||||
(Entry key value env')
|
||||
|
||||
removeEntry :: EnvFile -> EnvKey -> EnvFile
|
||||
removeEntry End _ = End
|
||||
removeEntry (Entry entryKey entryValue rest) key = if entryKey==key
|
||||
then rest
|
||||
else (Entry entryKey entryValue (removeEntry rest key))
|
||||
|
||||
getEntry :: EnvFile -> EnvKey -> Maybe EnvValue
|
||||
getEntry End _ = Nothing
|
||||
getEntry (Entry entryKey entryValue rest) key = if entryKey==key
|
||||
then return entryValue
|
||||
else (getEntry rest key)
|
||||
|
||||
replaceEnvFile :: EnvFile -> IO ()
|
||||
replaceEnvFile env = do
|
||||
path <- getEnvFilePath
|
||||
(tempName, tempHandle) <- openTempFile "/tmp" ".fenv"
|
||||
hPutStr tempHandle (show env)
|
||||
hClose tempHandle
|
||||
removeFile path
|
||||
renameFile tempName path
|
||||
|
||||
getEnvFile :: IO EnvFile
|
||||
getEnvFile = do
|
||||
path <- getEnvFilePath
|
||||
contents <- readFile path
|
||||
return $ read contents
|
||||
|
||||
getEnvFilePath :: IO FilePath
|
||||
getEnvFilePath = do
|
||||
home <- getHomeDirectory
|
||||
return (home ++ "/.fenv")
|
||||
|
Loading…
Reference in New Issue
Block a user