File: TConfig.hs

package info (click to toggle)
hedgewars 0.9.22-dfsg-2~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports-sloppy
  • size: 196,004 kB
  • sloc: ansic: 48,003; pascal: 46,947; cpp: 23,903; java: 8,210; haskell: 6,188; xml: 2,676; objc: 363; sh: 273; python: 105; makefile: 37
file content (63 lines) | stat: -rw-r--r-- 1,845 bytes parent folder | download | duplicates (13)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
-- Module      : Data.TConfig
-- Copyright   : (c) Anthony Simpson 2009
-- License     : BSD3
--
-- Maintainer  : DiscipleRayne@gmail.com
-- Stability   : relatively stable
-- Portability : portable
---------------------------------------------------
{-|
  A small and simple text file configuration
  library written in Haskell. It is similar
  to the INI file format, but lacks a few of
  it's features, such as sections. It is
  suitable for simple games that need to
  keep track of certain information between
  plays.
-}
module Data.TConfig
    (
     getValue
   , repConfig
   , readConfig
   , writeConfig
   , remKey
   , addKey
   , Conf ()
   ) where

import Data.Char
import qualified Data.Map as M
import Control.Monad

type Key   = String
type Value = String
type Conf  = M.Map Key Value

-- |Adds a key and value to the end of the configuration.
addKey :: Key -> Value -> Conf -> Conf
addKey = M.insert

-- |Utility function.
-- Removes a key and its value from the configuration.
remKey :: Key -> Conf -> Conf
remKey = M.delete

-- |Utility function. Searches a configuration for a
-- key, and returns its value.
getValue :: Key -> Conf -> Maybe Value
getValue = M.lookup

-- |Utility function. Replaces the value
-- associated with a key in a configuration.
repConfig :: Key -> Value -> Conf -> Conf
repConfig k rv conf = let f _ = Just rv
                      in M.alter f k conf

-- |Reads a file and parses to a Map String String.
readConfig :: FilePath -> IO Conf
readConfig path = liftM (M.fromList . map ((\(a, b) -> (filter (not . isSpace) a, dropWhile isSpace $ tail b)) . break (== '=')) . filter (not . null) . lines) $ readFile path

-- |Parses a parsed configuration back to a file.
writeConfig :: FilePath -> Conf -> IO ()
writeConfig path = writeFile path . unlines . map (\(a, b) -> a ++ " = " ++ b) . M.toList