~jconti/recent-notifications/trunk

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""
Config.py
February 13, 2011

Reads and writes config files in a simple (key = value) or just (key) for boolean
properties, and notifies listeners when the values are changed.
"""

import errno
import logging
import os

from threading import Lock

logger = logging.getLogger("Config")

class Config(object):
  """A config file"""
  def __init__(self, path):
    self._path = os.path.expanduser(path)
  
    self._options = {}
    self._listeners = {}

    self._lock = Lock()

    self.load()

  def __contains__(self, key):
    """Returns true if this config has the given key."""
    return key in self._options

  def __iter__(self):
    """Returns an iterator over the keys of this Config object."""
    return iter(self._options)

  def load(self):
    """Loads a config file, if it exists."""
    try:
      f = open(self._path, "r")
    except:
      logger.warning("Failed to open config file: {0}".format(self._path))
      self._options = {}
      return

    try:
      for line in f:
        item = line.split("=", 1)
        if len(item) == 1:
          key = item[0].strip()
          self._options[key] = True
        else:
          key = item[0].strip()
          value = item[1].strip()
          self._options[key] = value
    except:
      logger.warning("Error reading config file: {0}".format(self._path))
      self._options = {}

  def save(self):
    """Saves the config file, creating the destination directory if necessary."""
    # Create the destination directory
    dirname = os.path.dirname(self._path)
    try:
      os.makedirs(dirname, 0700)
    except os.error, e:
      if e.errno != errno.EEXIST:
        logger.error("Failed to create directory: {0}".format(dirname))
        return

    with open(self._path, "w") as f:
      for key, value in self._options.items():
        f.write("{0} = {1}\n".format(key, value))

  def add_listener(self, key, callback):
    """Adds a listener to notify the given callback when the given key is changed.
    Callbacks should be of the form f(key, value)."""
    if key in self._listeners:
      self._listeners[key].append(callback)
    else:
      self._listeners[key] = [callback]

  def notify_all(self):
    """Notifies all listeners of the current value for each key they are watching."""
    for key in self._listeners:
      if key in self._options:
        value = self._options[key]
        for f in self._listeners[key]:
          f(key, value)

  def get(self, key, default = ""):
    """Returns the value of the given key, or the default value."""
    if key in self._options:
      return self._options[key]
    else:
      return default

  def get_bool(self, key, default = False):
    """Returns the value of the given key as a boolean, or the default value if it fails
    to convert or does not exist."""
    if key not in self._options:
      return default
    value = self._options[key]
    if value == True or value == "True":
      return True
    elif value == False or value == "False":
      return False
    else:
      return default

  def get_int(self, key, default = 0):
    """Returns this value of the given key as an int, or the default value if it fails to
    convert or does not exist."""
    if key not in self._options:
      return default
    value = self._options[key]
    try:
      return int(value)
    except:
      return default

  def set(self, key, value):
    """Sets the value for the given key, saves the config file and notifies any
    listeners that the value has changed."""
    with self._lock:
      self._options[key] = value
      self.save()

    if key in self._listeners:
      for f in self._listeners[key]:
        f(key, value)

  def set_if_unset(self, key, value):
    """Calls set(key, value) only if the key does not exist in this config."""
    if key not in self._options:
      self.set(key, value)