155
155
return os.path.basename(sys.argv[0])
159
"""A Juju charm config dictionary that can write itself to
160
disk (as json) and track which values have changed since
161
the previous hook invocation.
163
Do not instantiate this object directly - instead call
169
>>> from charmhelpers.core import hookenv
170
>>> config = hookenv.config()
173
>>> config['mykey'] = 'myval'
177
>>> # user runs `juju set mycharm foo=baz`
178
>>> # now we're inside subsequent config-changed hook
179
>>> config = hookenv.config()
182
>>> # test to see if this val has changed since last hook
183
>>> config.changed('foo')
185
>>> # what was the previous value?
186
>>> config.previous('foo')
188
>>> # keys/values that we add are preserved across hooks
191
>>> # don't forget to save at the end of hook!
195
CONFIG_FILE_NAME = '.juju-persistent-config'
197
def __init__(self, *args, **kw):
198
super(Config, self).__init__(*args, **kw)
199
self._prev_dict = None
200
self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
201
if os.path.exists(self.path):
204
def load_previous(self, path=None):
205
"""Load previous copy of config from disk so that current values
206
can be compared to previous values.
210
File path from which to load the previous config. If `None`,
211
config is loaded from the default location. If `path` is
212
specified, subsequent `save()` calls will write to the same
216
self.path = path or self.path
217
with open(self.path) as f:
218
self._prev_dict = json.load(f)
220
def changed(self, key):
221
"""Return true if the value for this key has changed since
225
if self._prev_dict is None:
227
return self.previous(key) != self.get(key)
229
def previous(self, key):
230
"""Return previous value for this key, or None if there
231
is no "previous" value.
235
return self._prev_dict.get(key)
239
"""Save this config to disk.
241
Preserves items in _prev_dict that do not exist in self.
245
for k, v in self._prev_dict.iteritems():
248
with open(self.path, 'w') as f:
159
253
def config(scope=None):
160
254
"""Juju charm configuration"""
348
445
class Hooks(object):
349
446
"""A convenient handler for hook functions.
354
452
# register a hook, taking its name from the function name
455
pass # your code here
359
457
# register a hook, providing a custom hook name
360
458
@hooks.hook("config-changed")
361
459
def config_changed():
460
pass # your code here
364
462
if __name__ == "__main__":
365
463
# execute a hook based on the name the program is called by