4989
|
1 |
-- Module : Data.TConfig
|
|
2 |
-- Copyright : (c) Anthony Simpson 2009
|
|
3 |
-- License : BSD3
|
|
4 |
--
|
|
5 |
-- Maintainer : DiscipleRayne@gmail.com
|
|
6 |
-- Stability : relatively stable
|
|
7 |
-- Portability : portable
|
|
8 |
---------------------------------------------------
|
|
9 |
{-|
|
|
10 |
A small and simple text file configuration
|
|
11 |
library written in Haskell. It is similar
|
|
12 |
to the INI file format, but lacks a few of
|
|
13 |
it's features, such as sections. It is
|
|
14 |
suitable for simple games that need to
|
|
15 |
keep track of certain information between
|
|
16 |
plays.
|
|
17 |
-}
|
|
18 |
module Data.TConfig
|
|
19 |
(
|
|
20 |
getValue
|
|
21 |
, repConfig
|
|
22 |
, readConfig
|
|
23 |
, writeConfig
|
|
24 |
, remKey
|
|
25 |
, addKey
|
|
26 |
, Conf ()
|
|
27 |
) where
|
|
28 |
|
|
29 |
import Data.Char
|
|
30 |
import qualified Data.Map as M
|
4992
|
31 |
import Control.Monad
|
4989
|
32 |
|
|
33 |
type Key = String
|
|
34 |
type Value = String
|
|
35 |
type Conf = M.Map Key Value
|
|
36 |
|
|
37 |
-- |Adds a key and value to the end of the configuration.
|
|
38 |
addKey :: Key -> Value -> Conf -> Conf
|
4992
|
39 |
addKey = M.insert
|
4989
|
40 |
|
|
41 |
-- |Utility function.
|
4995
|
42 |
-- Removes a key and its value from the configuration.
|
4989
|
43 |
remKey :: Key -> Conf -> Conf
|
4992
|
44 |
remKey = M.delete
|
4989
|
45 |
|
|
46 |
-- |Utility function. Searches a configuration for a
|
4995
|
47 |
-- key, and returns its value.
|
4989
|
48 |
getValue :: Key -> Conf -> Maybe Value
|
4992
|
49 |
getValue = M.lookup
|
4989
|
50 |
|
|
51 |
-- |Utility function. Replaces the value
|
|
52 |
-- associated with a key in a configuration.
|
|
53 |
repConfig :: Key -> Value -> Conf -> Conf
|
|
54 |
repConfig k rv conf = let f _ = Just rv
|
|
55 |
in M.alter f k conf
|
|
56 |
|
|
57 |
-- |Reads a file and parses to a Map String String.
|
|
58 |
readConfig :: FilePath -> IO Conf
|
4993
|
59 |
readConfig path = liftM (M.fromList . map ((\(a, b) -> (filter (not . isSpace) a, dropWhile isSpace $ tail b)) . break (== '=')) . filter (not . null) . lines) $ readFile path
|
4989
|
60 |
|
|
61 |
-- |Parses a parsed configuration back to a file.
|
|
62 |
writeConfig :: FilePath -> Conf -> IO ()
|
4992
|
63 |
writeConfig path = writeFile path . unlines . map (\(a, b) -> a ++ " = " ++ b) . M.toList
|