changeset 1454:5d4888f3cd12

util: add a fileproperty helper method The code base uses the pattern that syncs a property with disk frequently. Let's have a helper method for declaring this kind of property.
author Jun Wu <quark@fb.com>
date Mon, 13 Jun 2016 16:59:51 +0100
parents d890d8d4e168
children 8cfe074cd463
files hgsubversion/util.py
diffstat 1 files changed, 21 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/hgsubversion/util.py
+++ b/hgsubversion/util.py
@@ -44,6 +44,27 @@ def configpath(ui, name):
     path = ui.config('hgsubversion', name)
     return path and hgutil.expandpath(path)
 
+def fileproperty(fname, pathfunc, default=None,
+                 serializer=str, deserializer=str):
+    """define a property that is backed by a file"""
+    def fget(self):
+        if not hgutil.safehasattr(self, fname):
+            path = pathfunc(self)
+            if os.path.exists(path):
+                with open(path, 'r') as f:
+                    setattr(self, fname, deserializer(f.read()))
+            else:
+                setattr(self, fname, default)
+        return getattr(self, fname)
+
+    def fset(self, value):
+        setattr(self, fname, value)
+        path = pathfunc(self)
+        with open(path, 'w') as f:
+            f.write(serializer(value))
+
+    return property(fget, fset)
+
 def filterdiff(diff, oldrev, newrev):
     diff = newfile_devnull_re.sub(r'--- \1\t(revision 0)' '\n'
                                   r'+++ \1\t(working copy)',