From 44a722042a4e321c38ac50b0b796a4fa494f09e4 Mon Sep 17 00:00:00 2001 From: Steven Armstrong Date: Mon, 10 Oct 2011 14:37:33 +0200 Subject: [PATCH] new class for using filesystem as backend for boolean properties Signed-off-by: Steven Armstrong --- lib/cdist/core/property.py | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/lib/cdist/core/property.py b/lib/cdist/core/property.py index e63cadcf..11dddcf3 100644 --- a/lib/cdist/core/property.py +++ b/lib/cdist/core/property.py @@ -165,3 +165,50 @@ class DirectoryDictProperty(DirectoryDict): def __delete__(self, obj): raise AttributeError("can't delete attribute") + + +class FileBooleanProperty(object): + def __init__(self, path): + """ + :param path: string or callable + + Usage: + + class Foo(object): + changed = FileBoolean(lambda obj: os.path.join(obj.absolute_path, 'changed')) + other_boolean = FileBoolean('/tmp/other_boolean') + + def __init__(self): + self.absolute_path = '/tmp/foo_boolean' + + """ + self._path = path + + def _get_path(self, *args, **kwargs): + path = self._path + if callable(path): + return path(*args, **kwargs) + if not os.path.isabs(path): + raise AbsolutePathRequiredError(path) + return path + + # Descriptor Protocol + def __get__(self, obj, objtype=None): + if obj is None: + return self.__class__ + path = self._get_path(obj) + return os.path.isfile(path) + + def __set__(self, obj, value): + path = self._get_path(obj) + if value: + open(path, "w").close() + else: + try: + os.remove(path) + except EnvironmentError: + # ignore + pass + + def __delete__(self, obj): + raise AttributeError("can't delete attribute")