Commits

Daniel Poelzleithner committed c7d8cbb

start reorganizing filetree

Comments (0)

Files changed (57)

+externals
+.*\.pyc
+.*\.*~
+\.pida-metadata

.pida-metadata/project.json

+{
+  "targets":[],
+  "options":{
+    "name":"vaultfs-main"
+  }
+}

.pida-metadata/python/config.py

+# The default ``config.py``
+
+
+def set_prefs(prefs):
+    """This function is called before opening the project"""
+
+    # Specify which files and folders to ignore in the project.
+    # Changes to ignored resources are not added to the history and
+    # VCSs.  Also they are not returned in `Project.get_files()`.
+    # Note that ``?`` and ``*`` match all characters but slashes.
+    # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
+    # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
+    # '.svn': matches 'pkg/.svn' and all of its children
+    # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
+    # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
+    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
+                                  '.hg', '.svn', '_svn', '.git']
+
+    # Specifies which files should be considered python files.  It is
+    # useful when you have scripts inside your project.  Only files
+    # ending with ``.py`` are considered to be python files by
+    # default.
+    #prefs['python_files'] = ['*.py']
+
+    # Custom source folders:  By default rope searches the project
+    # for finding source folders (folders that should be searched
+    # for finding modules).  You can add paths to that list.  Note
+    # that rope guesses project source folders correctly most of the
+    # time; use this if you have any problems.
+    # The folders should be relative to project root and use '/' for
+    # separating folders regardless of the platform rope is running on.
+    # 'src/my_source_folder' for instance.
+    #prefs.add('source_folders', 'src')
+
+    # You can extend python path for looking up modules
+    #prefs.add('python_path', '~/python/')
+
+    # Should rope save object information or not.
+    prefs['save_objectdb'] = True
+    prefs['compress_objectdb'] = False
+
+    # If `True`, rope analyzes each module when it is being saved.
+    prefs['automatic_soa'] = True
+    # The depth of calls to follow in static object analysis
+    prefs['soa_followed_calls'] = 0
+
+    # If `False` when running modules or unit tests "dynamic object
+    # analysis" is turned off.  This makes them much faster.
+    prefs['perform_doa'] = True
+
+    # Rope can check the validity of its object DB when running.
+    prefs['validate_objectdb'] = True
+
+    # How many undos to hold?
+    prefs['max_history_items'] = 32
+
+    # Shows whether to save history across sessions.
+    prefs['save_history'] = True
+    prefs['compress_history'] = False
+
+    # Set the number spaces used for indenting.  According to
+    # :PEP:`8`, it is best to use 4 spaces.  Since most of rope's
+    # unit-tests use 4 spaces it is more reliable, too.
+    prefs['indent_size'] = 4
+
+    # Builtin and c-extension modules that are allowed to be imported
+    # and inspected by rope.
+    prefs['extension_modules'] = []
+
+    # Add all standard c-extensions to extension_modules list.
+    prefs['import_dynload_stdmods'] = True
+
+    # If `True` modules with syntax errors are considered to be empty.
+    # The default value is `False`; When `False` syntax errors raise
+    # `rope.base.exceptions.ModuleSyntaxError` exception.
+    prefs['ignore_syntax_errors'] = False
+
+    # If `True`, rope ignores unresolvable imports.  Otherwise, they
+    # appear in the importing namespace.
+    prefs['ignore_bad_imports'] = False
+
+
+def project_opened(project):
+    """This function is called after opening the project"""
+    # Do whatever you like here!

core/__init__.py

Empty file removed.

core/conf.py

-import os
-import os.path
-
-from django.utils.translation import ugettext as _
-import optparse
-
-_ENV_LOADED=False
-
-
-def CPATH(*args, **kwargs):
-    print CPATH
-
-def is_valid_name(name):
-    import re
-    if re.match('[a-z][a-z0-9][a-z0-9]+', name):
-        return True
-    return False
-
-
-def check_config(name):
-    """Checks if a config is ok"""
-    if name is None:
-        raise ValueError, "not a valid name"
-    if not os.path.exists(os.path.join(settings.VAULT_CONF_PREFIX, name)) or \
-        not os.path.exists(os.path.join(settings.VAULT_CONF_PREFIX, name, "settings_local.py")):
-
-        return False
-
-    return True
-
-def detect_current_config(name=None):
-    """Search for the wanted config and use them.
-    May be passed a wanted config name, elsewise
-    use some heuristic to detect the wanted config by environment.
-
-    If only one config exists, this will be used.
-    If the current CWD is a mounted vaultfs, use its config
-    """
-    if name and check_config(name):
-        return name
-
-    # test for entry
-    clist = os.listdir(settings.VAULT_CONF_PREFIX)
-    if len(clist) == 1 and check_config(clist[0]):
-        print _("\nWarning, using mount: %s\n") %clist[0]
-        return clist[0]
-
-    # test heuristic goes here
-    # FIXME
-
-    #raise optparse.BadOptionError("Can't detect config")
-
-    return None
-    
-
-def set_environment(name=None, detect=True, force=False):
-    global _ENV_LOADED, settings
-    if _ENV_LOADED and not force:
-        return
-    import os
-    import os.path
-    from django.conf import settings
-
-    if not getattr(settings, 'VAULT_SKELETON_DIR', None):
-        import vaultfs
-        sp = os.path.join(os.path.dirname(vaultfs.__file__), "skeleton")
-        settings.VAULT_SKELETON_DIR = sp
-
-    user = ""
-    if name and name.find(":") != -1:
-        user, name = name.split(":")
-
-    settings.VAULT_CONF_PREFIX = os.path.join(os.path.expanduser("~%s" %user), ".vaultfs")
-    if not os.path.exists(settings.VAULT_CONF_PREFIX):
-        os.mkdir(settings.VAULT_CONF_PREFIX)
-
-
-    #if detect:
-    wanted = None
-    if name is not None and detect is True:
-        wanted = detect_current_config(name)
-        if not wanted and detect is False:
-            raise EnvironmentError, "Can't detect which config to use"
-
-
-    settings.VAULT_CONFIG_NAME = None
-
-    if wanted:
-        settings.VAULT_CONFIGURED = True
-        settings.VAULT_CURRENT_PATH = VAULT_CONFIG_PATH(wanted)
-        settings.VAULT_CONFIG_NAME = wanted
-
-    _ENV_LOADED=False
-    #settings.VAULT_CONF_PREFIX = os.path.expanduser(os.path.join("~", ".vaultfs"))
-    settings.VAULT_CONFIGURED = True
-    settings.VAULT_CONFIG_PATH = VAULT_CONFIG_PATH
-
-    # import settings_local file
-    if wanted:
-        import imp
-        settings_local = imp.load_source("settings_local", os.path.join(settings.VAULT_CONFIG_PATH(wanted), "settings_local.py"))
-        slv = dir(settings_local)
-        for sln in slv:
-            if sln[0] != "_" and sln.upper() == sln:
-                setattr(settings, sln, getattr(settings_local, sln))
-
-
-    # load user settings module
-
-    _ENV_LOADED = True
-
-
-def VAULT_CONFIG_PATH(add=None):
-    from django.conf import settings
-    if add is None:
-        return settings.VAULT_CONF_PREFIX
-    return os.path.join(settings.VAULT_CONF_PREFIX,  add)

def_auth.json

-[{"pk": 1, "model": "auth.user", "fields": {"username": "poelzi", "first_name": "", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2008-02-22 09:17:19", "groups": [], "user_permissions": [], "password": "sha1$e9767$9211068e249a717317d56efa9ee6d799d3765212", "email": "p@p.com", "date_joined": "2008-02-22 09:17:19"}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 1}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 4}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_directory", "name": "Can add directory", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_directory", "name": "Can change directory", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_directory", "name": "Can delete directory", "content_type": 8}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_media", "name": "Can add media", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_media", "name": "Can change media", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_media", "name": "Can delete media", "content_type": 9}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_file", "name": "Can add file", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_file", "name": "Can change file", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_file", "name": "Can delete file", "content_type": 10}}]

genericoptions/__init__.py

Empty file removed.

genericoptions/fields.py

-from models import *
-from django.dispatch import dispatcher
-from django.db.models import signals
-
-
-class GenericOptions(object):
-    """
-    Provides a generic relation to any object through content-type/object-id
-    fields.
-    """
-
-    def __init__(self, ct_field="content_type", fk_field="object_id", instance=None, addident=0, parent=None):
-        self.addident = addident
-        self.instance = instance
-        self.parentname = parent
-
-    #    self.ct_field = ct_field
-    #    self.fk_field = fk_field
-
-    def contribute_to_class(self, cls, name):
-        # Make sure the fields exist (these raise FieldDoesNotExist,
-        # which is a fine error to raise here)
-        self.name = name
-        self.model = cls
-        #self.cache_attr = "_%s_cache" % name
-
-        # For some reason I don't totally understand, using weakrefs here doesn't work.
-        dispatcher.connect(self.instance_pre_init, signal=signals.pre_init, sender=cls, weak=False)
-
-        # Connect myself as the descriptor for this field
-        setattr(cls, name, self)
-
-    def instance_pre_init(self, signal, sender, args, kwargs):
-        # Handle initalizing an object with the generic FK instaed of
-        # content-type/object-id fields.
-        if self.name in kwargs:
-            #print "metas passed"
-            raise ValueError, "passing meta attributes in constructor is not supported"
-
-            #value = kwargs.pop(self.name)
-            #kwargs[self.ct_field] = self.get_content_type(value)
-            #kwargs[self.fk_field] = value._get_pk_val()
-
-    #def get_content_type(self, obj):
-    #    # Convenience function using get_model avoids a circular import when using this model
-    #    ContentType = get_model("contenttypes", "contenttype")
-    #    return ContentType.objects.get_for_model(obj)
-
-    def __get__(self, instance, instance_type=None):
-        if instance is None:
-            raise AttributeError, u"%s must be accessed via instance" % self.name
-
-        # fixme hack: this shouldn't be here when makeing it generic
-        #if isinstance(instance, RootDirectory):
-        #    return OptionWrapper(instance=None)
-        #if
-        key = None
-        for k,n in instance.__class__.__dict__.items():
-            if n == self:
-                key = k
-                break
-        def parent_lookup(model_instance, instance, name):
-            m = model_instance
-            while True:
-                c = getattr(m, key)
-                try:
-                    o = getattr(c, name)
-                    return o
-                except (KeyError, AttributeError):
-                    if not self.parentname:
-                        raise
-                    m2 = getattr(m, self.parentname)
-                    if m == m2 or m2 == None:
-                        raise KeyError, "Option not found in recrusive lookup"
-                    m = m2
-                    #getattr(o,
-
-
-        if self.instance == -1:
-            return OptionWrapper(instance=self.instance, addident=self.addident, parent_lookup=parent_lookup)
-        return OptionWrapper(instance=instance, addident=self.addident, parent_lookup=parent_lookup)
-        #try:
-        #    return getattr(instance, self.cache_attr)
-        #except AttributeError:
-        #    rel_obj = None
-        #    ct = getattr(instance, self.ct_field)
-        #    if ct:
-        #        try:
-        #            rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
-        #        except ObjectDoesNotExist:
-        #            pass
-        #    setattr(instance, self.cache_attr, rel_obj)
-        #    return rel_obj
-
-    #def __set__(self, instance, value):
-    #    if instance is None:
-    #        raise AttributeError, u"%s must be accessed via instance" % self.related.opts.object_name
-    #
-    #    ct = None
-    #    fk = None
-    #    if value is not None:
-    #        ct = self.get_content_type(value)
-    #        fk = value._get_pk_val()
-    #
-    #    setattr(instance, self.ct_field, ct)
-    #    setattr(instance, self.fk_field, fk)
-    #    setattr(instance, self.cache_attr, value)

genericoptions/models.py

-from django.db import models
-from django.contrib.contenttypes import generic
-from django.contrib.contenttypes import models as genmodels
-from django.db.models.loading import get_model
-import cPickle
-
-OPTION_TYPES = (
-    (0, "Unicode"),
-    (1, "String"),
-    (2, "Complex"),
-    (3, "Model"),
-)
-
-
-class Option(models.Model):
-    """Used to save options for a mount or specific object"""
-    key = models.CharField(max_length=255, null=False, blank=False, editable=False)
-    typ = models.IntegerField(null=False, choices=OPTION_TYPES, default=0)
-
-    instance_type = models.ForeignKey(genmodels.ContentType, null=True)
-    instance_id = models.PositiveIntegerField(null=True)
-    #target = generic.GenericForeignKey()
-    instance = generic.GenericForeignKey(ct_field=instance_type, fk_field=instance_id)
-    addident = models.IntegerField(default=0)
-
-    value = models.TextField(null=True, blank=True)
-
-    def set(self, value):
-        if isinstance(value, unicode):
-            self.typ = 0 # unicode
-            self.value = value
-        elif isinstance(value, str):
-            self.typ = 1 # string
-            self.value = value
-        elif isinstance(value, models.Model):
-            opts = value._meta
-            #key = (opts.app_label, opts.object_name.lower())
-            self.typ = 3
-            self.value = "%s %s %s" %(opts.app_label, opts.object_name.lower(), value.pk)
-        else:
-            self.typ = 2 # complex
-            self.value = cPickle.dumps(value)
-
-    def get(self):
-        if self.typ == 0:
-            return unicode(self.value)
-        elif self.typ == 1:
-            return str(self.value)
-        elif self.typ == 3:
-            opts = self.value.split()
-            try:
-                mod = models.get_model(opts[0], opts[1])
-                return mod.objects.get(pk=" ".join(opts[2:]))
-            except (mod.DoesNotExist, AttributeError):
-                return None
-        else:
-            return cPickle.loads(str(self.value))
-
-    def __repr__(self):
-        if self.instance_id:
-            return '<Option %.10s:%.10s... (idnt:%s) for %s:%s>' %(self.key, self.get(), self.addident, self.instance_type, self.instance_id)
-        return '<Option %(key).10s:%(value).10s... (idnt:%(addident)s)>' %self.__dict__
-
-DEFAULT_NOT_GIVEN="_DEFAULT_NOT_GIVEN_"
-
-def option_get(name, default_value=DEFAULT_NOT_GIVEN, instance=None, addident=0):
-    if not isinstance(name, basestring):
-        raise KeyError, "Key must be a string"
-
-
-    if instance != None:
-        ContentType = get_model("contenttypes", "contenttype")
-        ct = ContentType.objects.get_for_model(instance)
-
-        #print Option.objects.all()
-        #print name, default_value, instance, addident
-        #print Option.objects.filter(
-        #key__exact=name, instance_id=instance.pk, instance_type=ct, addident=addident)
-        #print "||"
-
-        try:
-            o = Option.objects.get(
-                    key=name, instance_id=instance.pk, instance_type=ct, addident=addident)
-            return o.get()
-        except Option.DoesNotExist:
-            if default_value != DEFAULT_NOT_GIVEN:
-                return default_value
-            raise KeyError, "Option with key '%s' not found" %name
-
-    try:
-        o = Option.objects.get(key__exact=name, instance_id__isnull=True, instance_type__isnull=True, addident__exact=addident)
-        return o.get()
-    except Option.DoesNotExist:
-        if id(default_value) != id(DEFAULT_NOT_GIVEN):
-            return default_value
-        raise KeyError, "Option with key %s not found" %name
-
-def option_set(name, value, instance=None, addident=0):
-    if not isinstance(name, basestring):
-        raise KeyError, "Key must be a string"
-
-    if instance is not None:
-        ContentType = get_model("contenttypes", "contenttype")
-        ct = ContentType.objects.get_for_model(instance)
-        (o, c) = Option.objects.get_or_create(
-                key=name, instance_id=instance.pk, instance_type=ct, addident=addident,
-                defaults={'key':name, 'value': None, 'instance_id':instance.pk, 'instance_type':ct, 'addident':addident}
-                )
-    else:
-        (o, c) = Option.objects.get_or_create( \
-                        key=name, instance_id__isnull=True, \
-                        instance_type__isnull=True, addident=addident, \
-                        defaults={'key':name, 'value':None, 'addident':addident})
-    o.set(value)
-    o.save()
-
-def option_has(name, instance=None, addident=0):
-    if instance is not None:
-        ContentType = get_model("contenttypes", "contenttype")
-        ct = ContentType.objects.get_for_model(instance)
-        return Option.objects.filter(
-                key=name, instance_id=instance.pk, instance_type=ct, addident=addident).count() == 1
-
-    return Option.objects.filter(key=name, instance_id__isnull=True, instance_type__isnull=True).count() == 1
-
-class OptionWrapper(object):
-    def __init__(self, instance=None, options=None, addident=0, parent_lookup=None):
-        self.options = options
-        self.instance = instance
-        self.addident = addident
-        self.parent_lookup = parent_lookup
-
-    def __getitem__(self, name):
-        rv = option_get(name, instance=self.instance, addident=self.addident)
-        return rv
-
-    def __getattr__(self, name):
-        try:
-            return self.__getitem__(name)
-        except KeyError, e:
-            raise AttributeError, e
-
-    def get_recrusive(self, name):
-        """
-        Does a recrusive lookup on option
-        It tries to lookup if the Object has option, if not it travels
-        the parents up (with the help of the parent_lookup function) until
-        it finds a parent with this option or reaches the top.
-        """
-        if self.parent_lookup:
-            return self.parent_lookup(self.instance, self, name)
-        else:
-            raise KeyError, "No option found"
-
-    def __setitem__(self, name, value):
-        return option_set(name, value, instance=self.instance, addident=self.addident)
-
-    def filter(self, *args, **kwargs):
-        self.all().filter(*args, **kwargs)
-
-    def all(self):
-        if self.instance is not None:
-            ContentType = get_model("contenttypes", "contenttype")
-            ct = ContentType.objects.get_for_model(self.instance)
-            return Option.objects.filter(
-                instance_id=self.instance.pk, instance_type=ct, addident=self.addident)
-        return Option.objects.filter(
-                instance_id__isnull=True, instance_type__isnull=True, addident=self.addident)
-
-    def get(self, *args, **kwargs):
-        self.all().get(*args, **kwargs)
-
-    def has_key(self, name):
-        try:
-            self.__getitem__(name)
-            return True
-        except:
-            return False
-
-    def __iter__(self):
-        for i in self.all():
-            yield i
-
-    def keys(self):
-        rv = []
-        for i in self.all():
-            rv.append(i.key)
-
-    def iteritems(self):
-        for i in self.all():
-            yield (i.key, i.get())
-
-    def iterkeys(self):
-        for i in self.all():
-            yield i.key
-
-    def __str__(self):
-        return 'OptionWrapper%s' %dict(self.iteritems()).__str__()
-
-    def __repr__(self):
-        return 'OptionWrapper%s' %dict(self.iteritems()).__repr__()
-
-    #def iter
-    # fixme: make more complete api here
-
-options = OptionWrapper()

genericoptions/tests.py

-from django.test import TestCase
-#from vaultfs.vaultdb.models import *
-from vaultfs.genericoptions.models import *
-from django.db import models
-import fields
-
-options = OptionWrapper()
-
-class Complex(object):
-    uno = 1
-    duofloat = 2.0
-    threestr = "3"
-    uniquad = u"4"
-
-    def __cmp__(self, other):
-        if self.uno != other.uno or \
-            self.duofloat != other.duofloat or \
-            self.threestr != other.threestr or \
-            self.uniquad != other.uniquad:
-            return -1
-        return 0
-
-class TestModel(models.Model):
-    test = models.CharField(max_length=10)
-    options = fields.GenericOptions()
-    metas = fields.GenericOptions(addident=99)
-
-    def __repr__(self):
-        return '<TestModel %s "%s">' %(self.id, self.test)
-
-    def __str__(self):
-        return '<TestModel %s "%s">' %(self.id, self.test)
-
-class TestRecrModel(models.Model):
-    parent = models.ForeignKey('self', null=True)
-    options = fields.GenericOptions(parent='parent')
-
-    def __repr__(self):
-        return '<TestRecr %s "%s">' %(self.id, self.parent_id)
-
-    def __str__(self):
-        return '<TestRecr %s "%s">' %(self.id, self.parent_id)
-
-
-class TestRecr(TestCase):
-    def setUp(self):
-        self.t1 = TestRecrModel()
-        self.t1.save()
-        self.t2 = TestRecrModel(parent=self.t1)
-        self.t2.save()
-        self.t3 = TestRecrModel(parent=self.t2)
-        self.t3.save()
-        self.s1 = TestRecrModel()
-        self.s1.save()
-        self.t4 = TestRecrModel(parent=self.t1)
-        self.t4.save()
-
-    def geto(self, mod, key):
-        return mod.options[key]
-
-
-    def test_recrmeta(self):
-        self.t1.options['rootset'] = 'test'
-        self.assertEqual(self.t1.options.get_recrusive('rootset'), 'test')
-        self.assertEqual(self.t2.options.get_recrusive('rootset'), 'test')
-        self.assertEqual(self.t3.options.get_recrusive('rootset'), 'test')
-        self.assertEqual(self.t4.options.get_recrusive('rootset'), 'test')
-        self.assertRaises(KeyError, self.geto, self.s1, 'rootset')
-        self.assertRaises(KeyError, self.geto, self.t1, 'rootset2')
-        self.t2.options['rootset'] = 'test2'
-        self.assertEqual(self.t1.options.get_recrusive('rootset'), 'test')
-        self.assertEqual(self.t2.options.get_recrusive('rootset'), 'test2')
-        self.assertEqual(self.t3.options.get_recrusive('rootset'), 'test2')
-        self.assertEqual(self.t4.options.get_recrusive('rootset'), 'test')
-        self.t4.options['rootset'] = 'test3'
-        self.assertEqual(self.t1.options.get_recrusive('rootset'), 'test')
-        self.assertEqual(self.t2.options.get_recrusive('rootset'), 'test2')
-        self.assertEqual(self.t3.options.get_recrusive('rootset'), 'test2')
-        self.assertEqual(self.t4.options.get_recrusive('rootset'), 'test3')
-
-
-
-
-
-
-class TestFields(TestCase):
-    def setUp(self):
-        self.t1 = TestModel(test="bla")
-        self.t1.save()
-        self.t2 = TestModel(test="second")
-        self.t2.save()
-        
-        
-    def test_fields(self):
-        #print self.t1.options
-        self.t1.options['test'] = 1
-        self.t1.options['test2'] = 2
-        #print self.t1.options
-        self.assertEqual(self.t1.options['test'], 1)
-        self.assertEqual(self.t1.options['test2'], 2)
-        self.assertEqual(self.t1.options.has_key('test'), True)
-        self.assertEqual(self.t1.options.has_key('test2'), True)
-        self.assertEqual(self.t1.options.has_key('test3'), False)
-        self.assertEqual(self.t2.options.has_key('test'), False)
-        self.assertEqual(self.t2.options.has_key('test2'), False)
-
-        
-    def geto(self, mod, key):
-        return mod.options[key]
-
-
-    def getm(self, mod, key):
-        return mod.metas[key]
-
-    def test_existing(self):
-        self.t1.options['test'] = 1001
-        self.assertRaises(KeyError, self.geto, self.t2, 'test')
-        self.assertEqual(self.t1.options['test'], 1001)
-        self.t2.options['test2'] = 2002
-        self.assertRaises(KeyError, self.geto, self.t1, 'test2')
-
-        self.assertEqual(getattr(self.t2.options,'test2',None), 2002)
-
-        self.assertEqual(getattr(self.t2.options,'test3',None), None)
-        self.assertEqual(getattr(self.t2.options,'test3',-120), -120)
-
-    def test_second(self):
-        # test that second optionsfield doesn't have values
-
-        self.t1.options['test'] = 99
-        self.assertRaises(KeyError, self.getm, self.t1, 'test')
-        self.assertRaises(KeyError, self.getm, self.t2, 'test')
-
-        self.t1.metas['testm'] = 99
-        self.assertRaises(KeyError, self.geto, self.t1, 'testm')
-        self.assertRaises(KeyError, self.geto, self.t2, 'testm')
-
-
-class TestOptions(TestCase):
-    """ Test option interface """
-    def test_options(self):
-        o = options
-        o['test'] = 1
-        o['test2'] = 2
-        o['uni1'] = u'unicode'
-        o['uni2'] = u'unicode'
-        o['uni3'] = 'unicode'
-        o['str1'] = 'str'
-
-        self.assertEqual(o['test'], 1)
-        self.assertEqual(o['test2'], 2)
-        self.assertEqual(o['uni1'], u'unicode')
-        self.assertEqual(o['uni2'], u'unicode')
-        self.assertEqual(o['uni1'], o['uni1'])
-        self.assertNotEqual(o['str1'], o['uni1'])
-        self.assertEqual(o['uni3'], o['uni2'])
-
-    def test_complex(self):
-        o = options
-        o['comp1'] = Complex()
-        self.assertEqual(o['comp1'], Complex())
-
-        # default complex python types
-        o['k1'] = {'a':1, 'b':2}
-        self.assertEqual(o['k1'], {'a':1, 'b':2})
-        o['k2'] = None
-        self.assertEqual(o['k2'], None)
-        o['k3'] = [1,2,3]
-        self.assertEqual(o['k3'], [1 ,2 ,3 ])
-        self.assertEqual(o['k3'], [1,2,3])
-        self.assertNotEqual(o['k3'], [1,2,3,4])
-        self.assertNotEqual(o['k3'], (1,2,3))
-
-        o['k4'] = (1,2,3)
-        self.assertEqual(o['k4'], (1,2,3))
-        self.assertNotEqual(o['k4'], [1 ,2 ,3])
-
-    def mkmodels(self):
-        self.t1 = TestModel(test="bla")
-        self.t1.save()
-        self.t2 = TestModel(test="second")
-        self.t2.save()
-        self.t3 = TestModel(test="tree")
-        self.t3.save()
-        self.t4 = TestModel(test="qu a d")
-        self.t4.save()
-
-
-    def test_model(self):
-        o = options
-        self.mkmodels()
-        o['m1'] = self.t1
-        self.assertEqual(o['m1'], self.t1)
-
-        o['m2'] = self.t2
-        o['m3'] = self.t3
-        self.assertEqual(o['m1'], self.t1)
-        self.assertEqual(o['m2'], self.t2)
-        self.assertEqual(o['m3'], self.t3)
-
-        o['m2'] = None
-        self.assertEqual(o['m1'], self.t1)
-        self.assertEqual(o['m2'], None)
-        self.assertEqual(o['m3'], self.t3)
-
-        self.t1.delete()
-        self.assertEqual(o['m1'], None)
-        self.assertEqual(o['m2'], None)
-        self.assertEqual(o['m3'], self.t3)
-
-
-        o['m3'] = {'a':1}
-        self.assertEqual(o['m1'], None)
-        self.assertEqual(o['m2'], None)
-        self.assertEqual(o['m3'], {'a':1})
-
-    def test_lowlevel(self):
-        """Test lowlevel API"""
-        option_set('test.1', 1)
-        option_set('test.2', 2)
-        self.assertEqual(option_get('test.1'), 1)
-        self.assertEqual(option_get('test.2'), 2)
-        self.assertNotEqual(option_get('test.1'), 2)
-        self.assertRaises(KeyError, option_get, 'NOTEXISTING')
-        self.assertRaises(KeyError, option_get, u'NOTEXISTING')
-        self.assertRaises(KeyError, option_get, 999)
-        self.assertRaises(KeyError, option_get, 0)
-        option_set('9', 2)
-        self.assertRaises(KeyError, option_get, 9)
-        # test if option_set is save for wrong name types
-        self.assertRaises(KeyError, option_set, 9, 'bla')
-        self.assertRaises(KeyError, option_set, 9, 999)
-        self.assertRaises(KeyError, option_set, 9.0, 'bla')
-        self.assertRaises(KeyError, option_set, None, 'bla')
-
-        # test default values
-        self.assertEqual(option_get('test.3', None), None)
-        self.assertEqual(option_get('test.4', None), None)
-        self.assertEqual(option_get('test.4', 1), 1)
-        self.assertEqual(option_get('test.4', 0.121), 0.121)
-
-        #self.assertEqual(option_get('test.4', None), None)
-
-
-
-

skeleton/settings_local.py

-from django.conf import settings
-import os
-
-DATABASE_ENGINE = 'sqlite3'      
-DATABASE_NAME = os.path.join(settings.VAULT_CURRENT_PATH,"sqlite.db")
-
-TEMPLATE_DIRS = (
-    #"/path/to/your/ernesto/templates",
-)
-
-MEDIA_ROOT = '/' #'/path/to/your/ernesto/media/'
-
-FIXTURE_DIRS = (
-    #for global auth fixtures
-    #'/path/to/your/ernesto/fixtures',
-)

update_externals.sh

+#!/bin/sh
+get_or_update() {
+    vcs=$2;name=$1;repo=$3;
+    echo -n syncing $name \ 
+    if [ ! -d "src/$name" ]
+    then
+        echo -n checkout\ 
+        case $vcs in
+            hg) hg clone -q $repo src/$name;;
+            bzr) bzr checkout -q $repo src/$name;;
+			svn) svn checkout -q $repo src/$name;
+        esac
+    else
+        echo -n update\ 
+        cd src/$name >/dev/null
+        case $vcs in
+            hg) hg pull -uq;;
+            bzt) bzr update -q;;
+			svn) svn update -q;;
+        esac
+        cd ../.. >/dev/null
+    fi
+
+    ln -sf src/$name/$name $name #XXX: asume normal forms
+    cd src/$name >/dev/null
+    echo -n build\ 
+    python setup.py build_ext -i >/dev/null
+    echo done
+    cd ../.. >/dev/null
+}
+
+if [ ! `which bzr` ]
+then
+    print "Error: You must install bzr to update Kiwi."
+    exit
+fi
+
+if [ ! `which hg` ]
+then 
+    print "Error: You must install Mercurial to update anyvnc and rope."
+    exit
+fi
+
+if [ ! `which svn` ]
+then 
+    print "Error: You must install Subversion to update externals"
+    exit
+fi
+
+FROM_WD=`pwd`
+cd $(dirname $(dirname $PWD/$0))
+mkdir -p externals/src >/dev/null
+cd externals >/dev/null
+
+#get_or_update rope hg http://www.bitbucket.org/agr/rope/
+#get_or_update anyvc hg http://bitbucket.org/RonnyPfannschmidt/anyvc/
+#get_or_update kiwi bzr lp:kiwi
+#get_or_update pygtkhelpers hg http://bitbucket.org/aafshar/pygtkhelpers-main/
+
+#get_or_update django svn http://code.djangoproject.com/svn/django/branches/releases/1.1.X/
+#get_or_update piston hg http://bitbucket.org/jespern/django-piston/
+get_or_update mptt svn http://django-mptt.googlecode.com/svn/trunk/
+
+
+cd $FROM_WD

vault

-vault.py
+#!/usr/bin/env python2.5
+
+# This is a setup to run vautfs out of the development directory only
+
+import sys, os
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "externals"))
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "tests"))
+
+
+from vaultfs.core.conf import setup_environ
+
+#from django.core.management import setup_environ
+
+try:
+    import settings # Assumed to be in the same directory.
+    setup_environ(settings)
+except ImportError:
+    # don't do anything, maybe its defined somewhere
+    pass
+    #import sys
+    #sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    #sys.exit(1)
+
+
+
+from vaultfs.fuse.vault_fuse import main
+
+main()

vaultdb/__init__.py

Empty file removed.

vaultdb/backends/__init__.py

-
-_MEDIA_TYPES = {}
-
-def register_media_type(type_manager):
-    """Register a MediaType to allow handing of those media files"""
-    print "register ...", type_manager
-    if _MEDIA_TYPES.has_key(type_manager.name):
-        raise ValueError, "Type already registered"
-    else:
-        _MEDIA_TYPES[type_manager.name] = type_manager
-
-
-def get_media_types():
-    return _MEDIA_TYPES
-
-
-_BACKENDS_INSTALLED = False
-def install_backends(force=False):
-    """Install all configures backends"""
-    global _BACKENDS_INSTALLED, _MEDIA_TYPES
-
-    if _BACKENDS_INSTALLED and not force:
-        return
-
-    from django.conf import settings
-    for backend in settings.VAULTFS_BACKENDS:
-        #pass
-        tm = __import__('vaultdb.backends', {}, {}, [backend])
-        #print tm.__dict__
-        #print "---"
-        #print getattr(tm,backend)
-        #print "<<<"
-        #print tm
-        #_MEDIA_TYPES[tm.name] = tm
-
-
-def get_media_types_choices():
-    rv = []
-    for mt in _MEDIA_TYPES:
-        rv.append(tuple(mt.name, mt.name_display))
-    return rv
-
-def get_backend(name):
-    """Returns the backend of the given name"""
-    global _MEDIA_TYPES
-    try:
-        return _MEDIA_TYPES[name]
-    except KeyError:
-        raise
-
-def get_backends():
-    """Returns a dictionary with all backends"""
-    rv = {}
-    for mt in _MEDIA_TYPES:
-        rv[mt.name] = mt.name_display
-    return rv
-
-def guess_backend_for_path(path):
-    best = None
-    bp = 0
-    for mt in _MEDIA_TYPES:
-        c = mt.get_backend_chance(path, best)
-        if c > bp:
-            best, bp = mt, c
-    return best
-
-
-class MediaBackend(object):
-    name = "dummy"
-    name_display = "dummy"
-    description = "dummy"
-
-
-    def get_backend_chance(self, path, current_match=None):
-        """
-        Returns how much this backend thinks its the best one for a given
-        path. Higher numbers mean better.
-        """
-        # this can handle every medium that can be mount....
-        return 1.0
-
-
-    def is_ready(self, media):
-        """Checks if a requested media is ready"""
-        return True
-
-    def __repr__(self):
-        return '<MediaBackend %s>' %self.name

vaultdb/backends/simple_directory.py

-from vaultfs.vaultdb.backends import MediaBackend
-
-
-class SimpleDirectory(MediaBackend):
-    name = "SimpleDirectory"
-    name_display = "Simple Directory"
-    description = "Maps a already existing directory into your vault"
-
-
-    def is_writable(self, path):
-        return True
-
-    def get_backend_chance(self, path, current_match=None):
-        """
-        Returns how much this backend thinks its the best one for a given
-        path. Higher numbers mean better.
-        """
-        # this can handle every medium that can be mount....
-        return 1.0

vaultdb/commands.py

-from django.utils.translation import ugettext as _
-import optparse
-
-class PrintHelpException(Exception):
-    pass
-
-
-def run_command(args="", help_="", requires_config=False):
-    #return fnk
-
-    def wrapper(fnk):
-
-        if requires_config:
-            # we have to wrapp if requires config is true,
-            # because evaluation happens on call only
-
-            def inner(*args, **kwargs):
-                from django.conf import settings
-                if requires_config and not getattr(settings, "VAULT_CONFIG_NAME", None):
-                    raise EnvironmentError, "Command requires a valid config"
-                fnk(*args, **kwargs)
-    
-            inner._args_ = args
-            inner._help_ = help_
-            inner.__name__ = fnk.__name__
-            inner.__doc__ = fnk.__doc__
-                    
-            return inner
-        else:
-            fnk._args_ = args
-            fnk._help_ = help_
-                    
-            return fnk
-            
-
-    return wrapper
-
-class Command(object):
-    prefix = ""
-    _args_ = "COMMAND"
-    help = _help_ = ""
-    help_usage = ""
-
-    def __init__(self, base):
-        self.base = base
-
-    def run(self, args, options):
-        if len(args) < 2:
-            raise PrintHelpException('Command requiered')
-
-        rm = self.get_run(args[1])
-
-        if rm is None:
-            raise optparse.BadOptionError, "Unknown command"
-
-        rm(self, args, options)
-
-    def register_options(self, parser):
-        pass
-
-    def print_help(self):
-        for name, rm in self.list_runs():
-            self.hl(rm.__name__[4:], rm._args_, rm._help_)
-        pass
-
-    def help_for(self, *args):
-        rv = {None:self}
-        if len(args) == 0:
-            return rv
-
-        elif args[0] == "ALL":
-            rv[None] = self
-            for nam, rm in self.list_runs(True):
-                rv[nam] = rm
-            return rv
-
-        else:
-            rm = self.get_run(args[0])
-            if rm:
-                rv[None] = rm
-
-        return rv #{}
-        #rr = self.get_command(name)
-
-    def hl(self, *args):
-        """easier help line printer"""
-        spc = " "*(min(24-max(len(args[0]),0), 24)+1)
-        print "  %s%s%s" %(args[0], spc, args[1])
-
-    def get_run(self, name):
-        """Checks if run method with name exists"""
-        cname = "run_%s" %name
-        try:
-            return self.__class__.__dict__[cname]
-        except KeyError:
-            return None
-
-    def list_runs(self, short=False):
-        """Returns list of run names"""
-        for nm, rm in self.__class__.__dict__.iteritems():
-            if nm[0:4] == "run_":
-                if short:
-                    yield (nm[4:], rm)
-                else:
-                    yield (nm, rm)
-
-class Media(Command):
-    """Manages medias in your vaultfs mountpoint."""
-    prefix = "media"
-    _help_ = "manage medias"
-    help_usage = " [command]"
-
-    def register_options(self, parser):
-        parser.add_option('-t', '--type', action="store", dest="backend_type")
-
-    @run_command(args="MEDIAPATH",
-                 help_=_("Add new media located at MEDIAPATH"))
-    def run_add(self, args, options):
-        """verbose help"""
-
-        print "run_add ", args
-        import os
-        if len(args) < 3:
-            #print "Path required"
-            raise optparse.OptionError("path required")
-        path = args[2]
-        if not os.path.exists(path):
-            #print
-            raise optparse.OptionValueError("Path %s does not exist" %path)
-
-        from vaultfs.vaultdb.backends import guess_backend_for_path
-
-        rv = guess_backend_for_path(path)
-        print "guessed backend %s" %rv
-
-
-    @run_command(args="MEDIAPATH",
-                 help_=_("Remove media from path MEDIAPATH"))
-    def run_del(self, args, options):
-        """verbose help"""
-        
-        print "run_del"
-
-
-    @run_command(args="MEDIAPATH",
-                 help_=_("Reindex files from MEDIAPATH"))
-    def run_index(self, args, options):
-        """verbose help"""
-        
-        print "run_index"
-
-
-
-class Conf(Command):
-    prefix = "conf"
-    _help_ = "manage configs"
-    help_usage = " [command]"
-
-
-    @run_command(args="NAME",
-                 help_=_("Creates default config with given name"))
-    def run_init(self, args, options):
-        """You can start a new config by running init with appended name"""
-
-        from vaultfs.core import conf
-        if not conf.is_valid_name(args[2]):
-            #print "not a valid name"
-            raise optparse.BadOptionError('Not a valid option name')
-        conf.set_environment(None, False)
-        #import vaultfs.settings_local
-        import vaultfs
-        import shutil
-        import os
-        name = args[2]
-        from django.conf import settings
-        src = settings.VAULT_SKELETON_DIR
-        dst = settings.VAULT_CONFIG_PATH(na)
-        print dst
-        if os.path.exists(dst):
-            print "config exists, skipping"
-            #return
-        else:
-            print _("Copy %s to %s") %(src, dst)
-            shutil.copytree(src, dst)
-            print "done"
-           #print "Sync database ?"
-        conf.set_environment(name, force=True)
-        cont = raw_input(_('Sync Database [y/n]: '))
-        if cont.lower() == _('y'):
-            from django.core.management import execute_manager #execute_from_command_line # execute_manager
-            from django.core.management import ManagementUtility
-            print settings._target.__dict__
-            execute_manager(settings, ['manage', 'syncdb'])
-            #execute_from_command_line(['manage', 'syncdb'])
-            #man = ManagementUtility(['syncdb'])
-            #man.execute()
-
-       
-    @run_command(args="",
-                 help_=_("List all config names"))
-    def run_list(self, args, options):
-        """You can start a new config by running init with appended name"""
-
-        from vaultfs.core import conf
-        #import vaultfs.settings_local
-        import os
-        from django.conf import settings
-        lst = os.listdir(settings.VAULT_CONF_PREFIX)
-        for i in lst:
-            print i
-    
-
-    @run_command(args="",
-                 help_=_("Checks filesystem for consistancy"),
-                 requires_config=True)
-    def run_fschk(self, args, options):
-        """You can start a new config by running init with appended name"""
-
-        from vaultfs.vaultdb import fschk
-        #import vaultfs.settings_local
-        fschk.run(verbosity=options.verbosity)
-
-
-
-class Fs(Command):
-    prefix = "fs"
-    _help_ = "fs utils"
-    help_usage = " [command]"
-
-
-    @run_command(args="[TARGET]",
-                 help_=_("Mounts filesystem to target or default"))
-    def run_mount(self, args, options):
-        """You can easily mount a vaultfs running this command"""
-
-        from vaultfs.core import conf
-        #conf.set_environment()
-        #import vaultfs.settings_local
-        import vaultfs
-        import shutil
-        import os
-        from vaultfs.vaultfuse.vault_fuse import main
-        if len(args) > 1:
-            path = args[2]
-        else:
-            path = "/tmp/bla"
-        main([path])
- 

vaultdb/fields.py

-from django.db import models
-
-class MediaField(models.CharField):
-    def get_choices(self):
-        from backends import get_media_types_choices
-        return get_media_types_choices

vaultdb/models.py

-from django.db import models
-from django.contrib.contenttypes import generic
-import django.contrib.contenttypes.models as genmodels
-
-from vaultfs.genericoptions.fields import GenericOptions
-from vaultfs.genericoptions.models import OptionWrapper
-from vaultfs.vaultdb.tools import Path
-
-
-import os
-import cPickle
-
-import fields
-
-from vaulterrors import *
-
-
-META_PREFIX = "..."
-
-class MediaManager(models.Manager):
-
-    def detect_backend_type(self, path):
-        from backends import get_media_types
-        current_score = 0.0
-        current_match = None
-        for backend in get_media_backends():
-            cm = backend.get_backend_chance(path, current_match)
-            if cm < 0.0: continue
-            if cm > current_score:
-                current_match = backend
-                current_score = cm
-
-        print "found backend %s for %s" %(current_match, path)
-        return current_match
-
-    def get_media(self, path):
-        """Return Media instance for patch """
-        pass
-
-
-class Media(models.Model):
-    uuid = models.CharField("UUID of media", unique=True, max_length=255)
-    media_type = fields.MediaField("Type of Media", choices=(), max_length=30)
-    mountpoint = models.CharField("Current Mountpoint of media", max_length=255)
-    mounted = models.BooleanField("Is medium mounted", default=False)
-    options = GenericOptions()
-
-    def _get_backend(self):
-        from backends import get_backend
-        return get_backend(self.media_type)
-
-    def _set_backend(self, value):
-        self.media_type = value
-
-    backend = property(_get_backend, _set_backend)
-
-    def is_ready(self):
-        # FIXME: use media backend to test
-        return self.backend.is_ready(self)
-        #return True
-
-    def is_writable(self):
-        return False
-
-    class Admin: pass
-
-class DirectoryManager(models.Manager):
-
-    def parse_path(self, path):
-        #rv = os.path.split(os.path.normpath(path))
-        #rv = os.path.normpath(path).split(os.sep)
-        return Path(path) #list(rv)
-
-    def resolve_parent(self, path):
-        """returns the latest database entry of the filesystem,
-        return a tuple of last matching directory object and the
-        reminding objects list"""
-        if isinstance(path, basestring):
-            ppath = self.parse_path(path)
-        else:
-            ppath = list(path[:])
-
-        #print "resolve ", path, ppath
-        last = ROOTDIRECTORY
-        # the root directory return none
-        if len(path) == 2 and path[0] == "" and path[1] == "":
-            return (last, [])
-
-        # drop '' prefix
-        if ppath and ppath[0] == '':
-            del ppath[0]
-
-        ppath.reverse()
-        
-        #for ci in ppath[1:]:
-        while True:
-            if len(ppath) == 1:
-                break
-            try: ci = ppath.pop()
-            except IndexError: break
-            #print "walk:",ci, "last:", last
-
-            try:
-                last = last.get_child(ci)
-            except VaultDoesNotExist:#Directory.DoesNotExist:
-                ppath.insert(0, ci)
-                print "last ", ppath
-                return (last, ppath)
-
-        # if the last element is a empty string, we can savely remove it from
-        # the left path elements stack
-        if len(ppath) == 1 and ppath[0] == "":
-            del ppath[0]
-            
-        return (last, ppath)
-
-    def resolve_complete(self, path):
-        #print "resolve complete ", path
-        (par, ppath) = self.resolve_parent(path)
-        #print "resolve compl", (par, ppath)
-        if len(ppath) > 1:
-            raise ValueError, "Can't resolve path complete, more non existing childs %s" %ppath
-
-        #Directory.objects.filter(parent=par,
-        # root directory entries
-        #if par is :
-        #    try:
-        #        return File.objects.get(_name__exact=ppath[0], parent__isnull=True)
-        #    except File.DoesNotExist:
-        #        try:
-        #            return Directory.objects.get(_name__exact=ppath[0], parent__isnull=True)
-        #        except Directory.DoesNotExist:
-        #            return None
-        if len(ppath) == 0:
-            return par
-        return par.get_child(ppath[0])
-
-class RealDirectory(models.Model):
-    """Real Directory entry"""
-    media = models.ForeignKey(Media)
-    name = models.CharField("name of directory", null=False, blank=False, max_length=255)
-    media_path = models.TextField('path of file on media')
-    parent = models.ForeignKey('self', null=True)
-    dir_access = models.IntegerField("Access rights", null=True)
-    dir_mtime = models.DateTimeField("Last modify time", null=True)
-    dir_ctime = models.DateTimeField("Creation time", null=True)
-    dir_atime = models.DateTimeField("Last access time", null=True)
-    dir_access = models.IntegerField("Access rights", null=True)
-    dir_owner = models.IntegerField("User ID", null=True)
-    dir_group = models.IntegerField("Group ID", null=True)
-
-class BaseOperations(object):
-    """
-    BaseOperations is the root object for filesystem classes.
-    It implements most of the basic API.
-    """
-
-    def _get_optionr(self, name):
-        pass
-
-    def get_absolute_path(self):
-        """Returns a Path object representing the complete path"""
-        na = []
-        st = self
-        while st:
-            na.append(st.name)
-            st = st.parent
-        #na.append("/")
-        na.reverse()
-        return Path(na)
-
-    def update_absolute(self):
-        """Updates internal absolute path"""
-        self.absolute_path = str(self.get_absolute_path())[:255]
-
-    def _get_name(self):
-        return self._name
-
-    def _set_name(self, value):
-        self._name = value
-        self.update_absolute()
-    name = property(_get_name, _set_name)
-
-
-    def rename(self, newname):
-        """Rename a object and checks for uniqueness of the new name"""
-        par = self.parent
-        if par is None:
-            par = ROOTDIRECTORY
-        if par.has_child(newname):
-            raise VaultNameAlreadyExists, "Name already exists"
-        self.name = newname
-
-#    def __getattr__(self, name):
-
-#keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update()
-        """
-__len__(	self)
-
-Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context. 
-__getitem__(	self, key)
-
-Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised. Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence. 
-__setitem__(	self, key, value)
-
-Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper key values as for the __getitem__() method. 
-__delitem__(	self, key)
-
-Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method. 
-__iter__(	self)        
-"""
-#    def __getitem__(self, key):
-#        try:
-#            return self.get_child(key)
-#        except:
-#            raise KeyError, key
-#
-#    def __len__(self):
-#        try:
-#            return self.children_len
-#        except: pass
-#        return 01
-
-
-    is_dir = False
-    is_file = False
-    is_symlink = False
-
-class BaseDirectory(BaseOperations):
-    is_dir = True
-
-    def get_child(self, name):
-        if name == ".":
-            return self
-        try:
-            return self.file_set.get(_name__exact=name)
-        except:
-            try:
-                return self.directory_set.get(_name__exact=name)
-            except:
-                try:
-                    return self.symlink_set.get(_name__exact=name)
-                except:
-                    raise VaultDoesNotExist, "Child does not exist"
-
-        raise VaultDoesNotExist, "Child does not exist"
-
-    def has_child(self, name):
-        try:
-            self.get_child(name)
-            return True
-        except VaultDoesNotExist:
-            return False
-
-    def _get_children(self):
-        for i in self.directory_set.filter():
-            yield i
-
-        for i in self.file_set.filter():
-            yield i
-
-        for i in self.symlink_set.filter():
-            yield i
-
-    children = property(_get_children)
-
-
-    def _get_children_names(self):
-        for i in self.children:
-            yield i.name
-
-    children_names = property(_get_children_names)
-
-    def _get_children_num(self):
-        return self.directory_set.count() + \
-               self.file_set.count() + \
-               self.symlink_set.count()
-
-    children_num = property(_get_children_num)
-
-
-    def add_child(self, child, name=None, save=False):
-        """Adds a child to directory. if name is given the child object's name
-        will be set to this, else it will be lookuped by its name
-        """
-        if name is not None:
-            child.name = name
-
-        if self.directory_set.filter(_name=child.name).count() or \
-           self.file_set.filter(_name=child.name).count() or \
-           self.symlink_set.filter(_name=child.name).count():
-           raise VaultNameAlreadyExists, "Object with name already exist"
-
-        #if isinstance(child, File):
-        child.parent = self.get_as_parent()
-        if save:
-            self.save()
-            child.save()
-
-    def get_as_parent(self):
-        return self
-
-
-    def validate(self, repaire=False):
-        # check if all children have a unique name
-        pass
-
-    def __unicode__(self):
-        return self._name
-
-    def __repr__(self):
-        return "<Directory: %s (id:%s, name:%s)>" %(self.absolute_path, self.id, self._name)
-
-    def __str__(self):
-        return str(self._name)
-
-    def _get_rootdir(self):
-        return ROOTDIRECTORY
-
-    root_directory = property(_get_rootdir)
-
-class RootDirectory(BaseDirectory):
-    """
-    Emulates the root Directory object by acting as it would be a normal
-    Directory object but represents as a NULL pointer
-    """
-    name = ''
-    _name = ''
-    parent = None
-    media = None
-    mode = 0x655
-    real_directory = None
-    absolute_path = None
-    id = None
-    options = GenericOptions(instance=None)
-
-    def _dirset(self):
-        return Directory.objects.filter(parent__isnull=True)
-    directory_set = property(_dirset)
-
-    def _fileset(self):
-        return File.objects.filter(parent__isnull=True)
-    file_set = property(_fileset)
-
-    def _symset(self):
-        return Symlink.objects.filter(parent__isnull=True)
-    symlink_set = property(_symset)
-
-    def get_as_parent(self):
-        return None
-
-    def save(self): pass
-    def delete(self): pass
-
-    def __repr__(self):
-        return "<RootDirectory>"
-
-    def __str__(self):
-        return "/"
-
-    def __unicode__(self):
-        return u"/"
-
-
-# fixme: unique index over _name & parent
-class Directory(models.Model, BaseDirectory):
-    """
-    Directories act as container which usually have files inthem
-    """
-    absolute_path = models.CharField("Absolut pathname", max_length=255, editable=False)
-    _name = models.CharField("Relative Name", max_length=255)
-    parent = models.ForeignKey('self', null=True)
-    media = models.ForeignKey(Media, null=True)
-    mode = models.IntegerField("permission mode of file", default=0x655)
-    real_directory = models.ForeignKey(RealDirectory, null=True)
-    mtime  = models.DateTimeField(auto_now=True, editable=False)
-    ctime  = models.DateTimeField(auto_now_add=True, editable=False)
-    options = GenericOptions()
-
-    objects = DirectoryManager()
-
-
-    def save(self, *args, **kwargs):
-        self.update_absolute()
-        if self.parent:
-            self.parent = self.parent.get_as_parent()
-        #print self.__dict__
-        #print self.__dict__
-        models.Model.save(self, *args, **kwargs)
-
-    def __init__(self, *args, **kwargs):
-        if kwargs.has_key('name'):
-            kwargs['_name'] = kwargs.pop('name')
-        models.Model.__init__(self, *args, **kwargs)
-
-    class Admin:
-        pass
-
-
-class RealFile(models.Model):
-    """Represents a real File on some medium"""
-    name = models.CharField("filename in filesystem", max_length=255, editable=False, db_index=True) # fix length
-    file_size = models.IntegerField("Filesize in bytes", null=True, db_index=True)
-    file_mtime = models.DateTimeField("Last modify time", null=True)
-    file_ctime = models.DateTimeField("Creation time", null=True)
-    file_atime = models.DateTimeField("Last access time", null=True)
-    file_access = models.IntegerField("Access rights", null=True)
-    file_owner = models.IntegerField("User ID", null=True)
-    file_group = models.IntegerField("Group ID", null=True)
-    file_blocks = models.IntegerField("Number of Blocks", null=True)
-    file_blocksize = models.IntegerField("Size of Blocks", null=True)
-    file_links = models.IntegerField("Number of Links", null=True)
-    hash = models.CharField("Hash of file", max_length=64, editable=False, db_index=True, null=True) # fix length
-    media = models.ForeignKey(Media)
-    media_path = models.TextField('path of file on media')
-    parent = models.ForeignKey(RealDirectory, null=False)
-    options = GenericOptions()
-    # contains meta information parsed out of the data part of file
-    metadata = GenericOptions(addident=1)
-
-    def __init__(self, create_from_file=False, *args, **kwargs):
-        models.Model.__init__(self, *args, **kwargs)
-
-        if isinstance(create_from_file, File):
-            # we create a new real file on the default mountpoint
-            #if not self.media:
-            #    pass
-            #return
-
-            if not os.path.exists(self.media_path):
-                #r = getattr(OPTIONS, '
-                #fp = open(
-                # lookup default
-                print "no real file found"
-
-                try:
-                    wm = create_from_file.options.get_recrusive('realfile_media')
-                except AttributeError:
-                    raise VaultConfigException, "No default write media configured"
-
-
-                pass
-
-            if not os.isfile(media_path):
-                raise EnvironmentError, "Error creating new File, non file already exists"
-
-
-    def _aliases_get(self):
-        return RealFile.objects.filter(file_size=self.file_size, hash=self.hash, hash__isnull=False)
-    aliases = property(_aliases_get)
-
-    def _aliasesnum_get(self):
-        return RealFile.objects.filter(file_size=self.file_size, hash=self.hash, hash__isnull=False).count()
-
-    aliasesnum = property(_aliasesnum_get)
-
-    def update_hash(self):
-        """ Recalculates the hash value of file. This is a expensive operation"""
-        import hashlib
-        if not self.media.is_ready():
-            raise vaulterrors.VaultMediaNotReady, "Media is not available"
-
-        hi = hashlib.sha256()
-
-        fp = open(self.media_path, "r")
-        while True:
-            chk = fp.read(1024)
-            if not chk:
-                break
-            hi.update(chk)
-
-        self.hash = hi.hexdigest()
-
-
-class File(BaseOperations, models.Model):
-    """Represents a Link in the filesystem to a real media file"""
-    absolute_path = models.CharField("Absolut pathname", max_length=255, editable=False, null=True)
-    _name = models.CharField("Relative Name", max_length=255, db_index=True)
-    parent = models.ForeignKey(Directory, null=True, db_index=True)
-    real_file = models.ForeignKey(RealFile, null=True)
-    mtime  = models.DateTimeField(auto_now=True, editable=False)
-    ctime  = models.DateTimeField(auto_now_add=True, editable=False)
-    mode   = models.IntegerField(default=0x655) # fixme
-    options = GenericOptions()
-
-    is_file = True
-
-    def __init__(self, *args, **kwargs):
-        if kwargs.has_key('name'):
-            kwargs['_name'] = kwargs.pop('name')
-        if kwargs.has_key('create_realfile'):
-            self.create_realfile = kwargs.pop('create_realfile')
-        else:
-            self.create_realfile = False
-
-        super(File, self).__init__(*args, **kwargs)
-
-    def save(self, *args, **kwargs):
-        self.update_absolute()
-        if self.parent:
-            self.parent = self.parent.get_as_parent()
-        if self.create_realfile:
-            if not self.real_file:
-                rf = RealFile(create_from_file=self)
-                print rf
-                self.real_file = rf
-                rf.save()
-                #self.real_file.save()
-        super(File, self).save(*args, **kwargs)
-
-    def __repr__(self):
-        return "<File %s (parent: %s)>" %(self.name, self.parent_id)
-
-    def __str__(self):
-        return str(self.name)
-
-    def __unicode__(self):
-        return unicode(self.name)
-
-    def create_real_file(self, media=None):
-        """Creats a real file on media if it doesn't exist"""
-        if self.real_file is None:
-            pass
-        pass
-
-
-class Symlink(BaseOperations, models.Model):
-    absolute_path = models.CharField("Absolut pathname", max_length=255, editable=False, null=True)
-    _name = models.CharField("Relative Name", max_length=255, db_index=True)
-    parent = models.ForeignKey(Directory, null=True, db_index=True)
-
-    target = models.TextField(null=False)
-
-    options = GenericOptions()
-
-    #target_type = models.ForeignKey(genmodels.ContentType)
-    #target_id = models.PositiveIntegerField()
-    #target = generic.GenericForeignKey()
-    #models.ForeignKey(RealFile, null=True)
-
-    is_symlink = True
-
-    def __init__(self, *args, **kwargs):
-        if kwargs.has_key('name'):
-            kwargs['_name'] = kwargs.pop('name')
-
-        super(Symlink, self).__init__(*args, **kwargs)
-
-    def save(self, *args, **kwargs):
-        self.update_absolute()
-        if self.parent:
-            self.parent = self.parent.get_as_parent()
-        super(Symlink, self).save(*args, **kwargs)
-
-    def __repr__(self):
-        return "<Symlink %s -> %s>" %(self.name, self.target)
-
-    def __str__(self):
-        return self.name.encode('utf-8')
-
-    def __unicode__(self):
-        return self.name
-    
-
-
-ACCESS_TYPES = (
-    (0, 'Read'),
-    (1, 'Write'),
-    (2, 'Create'),
-    (3, 'Archived'),
-)
-
-
-class AccessHistory(models.Model):
-    file = models.ForeignKey(File, editable=False)
-    mode = models.IntegerField(choices=ACCESS_TYPES)
-    when = models.DateTimeField()#auto_create=True)
-
-
-ROOTDIRECTORY = RootDirectory()
-OPTIONS = OptionWrapper(instance=None)
-
-
-
-from backends import install_backends
-install_backends()
-

vaultdb/tests/__init__.py

-from vaultfs.vaultdb.tests.basic import *
-from vaultfs.vaultdb.tests.file import *

vaultdb/tests/basic.py

-from django.test import TestCase
-from vaultfs.vaultdb.models import *
-
-class TestBasic(TestCase):
-    """ Tests Basic functionality of db model
-    """
-
-    def setUp(self):
-        self.r1 = Directory(name="r1")
-        self.r1.save()
-
-        self.r2 = Directory(name="r2")
-        self.r2.save()
-
-        self.r1s1 = Directory(name="r1s1", parent=self.r1)
-        self.r1s1.save()
-
-        self.f1 = File(_name="f1")
-        self.f1.save()
-        self.f2 = File(name="f2", parent=self.r1)
-        self.f2.save()
-
-        self.f3 = File(name="f3", parent=self.r1s1)
-        self.f3.save()
-
-
-    def tearDown(self):
-        #self.r1.delete()
-        #self.r2.delete()
-        #self.r3.delete()
-        for n,i in self.__dict__.iteritems():
-            if isinstance(i, (File,Directory)):
-                i.delete()
-
-    def test_resolver(self):
-        #self.equal( Directory.objects.resolve_parent("/r1/r1s1")
-        ROOT = ROOTDIRECTORY
-        self.assertEqual(Directory.objects.resolve_parent("/r1/r1s1"), (self.r1, Path('r1s1')))
-        self.assertEqual(Directory.objects.resolve_parent("/r1"), (ROOT, Path('r1')))
-        self.assertEqual(Directory.objects.resolve_parent(""), (ROOT, Path('')))
-        self.assertEqual(Directory.objects.resolve_parent("/"), (ROOT, Path('')))
-
-        self.assertEqual(Directory.objects.resolve_complete(""), ROOT)
-        self.assertEqual(Directory.objects.resolve_complete("/r1"), self.r1)
-        self.assertEqual(Directory.objects.resolve_complete("/r1/r1s1"), self.r1s1)
-
-    def test_files(self):
-        self.assertEqual(self.r1.get_child('f2'), self.f2)
-        self.assertEqual(self.r1s1.get_child('f3'), self.f3)
-
-    def test_directories(self):
-        self.assertEqual(self.r1.get_child('r1s1'), self.r1s1)
-        
-
-
-
-class TestDirectory(TestBasic):
-    """ Tests Basic functionality of db model
-    """
-    def test_children(self):
-        self.assertEqual(list(self.r1.children), [self.r1s1,self.f2])
-        self.assertEqual(list(self.r1.children_names), ['r1s1','f2'])
-
-    def test_directory_api(self):
-        root = Directory.objects.resolve_complete("")
-        self.assertEqual(root, ROOTDIRECTORY)
-        self.assertEqual(str(root), "/")
-
-
-class TestOptions(TestBasic):
-    """ Test option interface """
-    def test_options(self):
-        o = OPTIONS
-        o.assign1 = 0
-        o['test'] = 1
-        o['test2'] = 2
-        o['uni1'] = u'unicode'
-        o['uni2'] = u'unicode'
-        o['str1'] = 'str'
-
-        self.assertEqual(o['test'], 1)
-        self.assertEqual(o['test2'], 2)
-        self.assertEqual(o['uni1'], u'unicode')
-        self.assertEqual(o['uni2'], u'unicode')
-        self.assertEqual(o['uni1'], o['uni1'])
-        self.assertNotEqual(o['str1'], o['uni1'])
-
-
-from vaultfs.vaultdb.tools import Path
-
-class TestPath(TestCase):
-    def test_init(self):
-        p1 = Path("/test/bla")
-        p2 = Path("/test/bla2")
-        p3 = Path("test")
-        p4 = Path("test/bla")
-        p5 = Path("")
-        p6 = Path("/")
-        p7 = Path(".")
-        p8 = Path("./")
-        p9 = Path("/.")
-        p10 = Path("/.bla")
-        p11 = Path("/./bla")
-
-
-        self.assertEqual(str(p1), "/test/bla")
-        self.assertEqual(str(p2), "/test/bla2")
-        self.assertEqual(str(p3), "test")
-        self.assertEqual(str(p4), "test/bla")
-        self.assertEqual(str(p5), "")
-        self.assertEqual(str(p6), "/")
-        self.assertEqual(str(p7), "./")
-        self.assertEqual(str(p8), "./")
-        self.assertEqual(str(p9), "/")
-        self.assertEqual(str(p10), "/.bla")
-        self.assertEqual(str(p11), "/bla")
-
-
-        # absolute test
-        self.assertEqual(p1.is_absolute(), True)
-        self.assertEqual(p2.is_absolute(), True)
-        self.assertEqual(p3.is_absolute(), False)
-        self.assertEqual(p4.is_absolute(), False)
-        self.assertEqual(p5.is_absolute(), False)
-        self.assertEqual(p6.is_absolute(), True)
-        self.assertEqual(p7.is_absolute(), False)
-        self.assertEqual(p8.is_absolute(), False)
-        self.assertEqual(p9.is_absolute(), True)
-        self.assertEqual(p10.is_absolute(), True)
-        self.assertEqual(p11.is_absolute(), True)
-
-        self.assertEqual(len(p1), 3)
-        self.assertEqual(len(p2), 3)
-        self.assertEqual(len(p3), 1)
-        self.assertEqual(len(p4), 2)
-        self.assertEqual(len(p5), 0)
-        self.assertEqual(len(p6), 2)
-        self.assertEqual(len(p7), 2)
-        self.assertEqual(len(p8), 2)
-        self.assertEqual(len(p9), 2)
-        self.assertEqual(len(p10), 2)
-        self.assertEqual(len(p11), 2)
-
-    def test_cmp(self):
-        pl = [
-          Path("/test/bla"), Path("/test/bla"),
-          Path("/test/cla"), Path("/a"), Path("/b/bla"),
-          Path("/b"), Path("/z"), Path("/b/"), Path("/b/b"), Path("/b/c")
-          ]
-
-        ps = [
-          Path("/a"), Path("/b/"), Path("/b"), Path("/b/b"), Path("/b/bla"), Path("/b/c"),
-          Path("/test/bla"), Path("/test/bla"),
-          Path("/test/cla"), Path("/z")
-          ]
-        
-        pl.sort()
-        self.assertEqual(pl, ps)
-
-        p1 = Path("/")
-        p2 = Path("/")
-
-    def test_eq(self):
-        self.assertEqual(Path("/"), Path("/"))
-        self.assertNotEqual(Path("/"), Path("/bla"))
-        self.assertNotEqual(Path("/blubb"), Path("/"))
-        self.assertNotEqual(Path("/bla"), Path("/"))
-        self.assertEqual(Path("/"), Path("/"))
-        self.assertEqual(Path("/bla"), Path("/bla"))
-        self.assertEqual(Path("/test/"), Path("/test/"))
-        self.assertEqual(Path("/test/"), Path("/test/."))
-        self.assertEqual(Path("/./bla"), Path("/bla"))
-        self.assertEqual(Path("."), Path("."))
-        self.assertEqual(Path("."), Path("./"))
-
-
-    def test_len(self):
-        p1 = Path("/test/blubb")
-        p2 = Path("/")
-
-        self.assertEqual(len(p1), 3)
-        self.assertEqual(len(p2), 2)
-

vaultdb/tests/file.py

-from django.test import TestCase
-from vaultfs.vaultdb.models import *
-
-class TestFile(TestCase):
-#    def setUp(self):
-
-    def test_filecreate(self):
-        #f1 = File(name="fw1", create_realfile=True)
-        #f1.save()
-        pass

vaultdb/tools.py

-import os.path
-
-class Path(list):
-    """Path object represents a filesystem path"""
-    def __init__(self, path):
-        self._isreversed = False
-
-        if isinstance(path, basestring):
-            if path == "":
-                chunks = []
-            elif path == ".":
-                chunks = ['.','']
-            else:
-                #rv = os.path.split(os.path.normpath(path))
-                chunks = os.path.normpath(path).split(os.sep)
-                if len(chunks) == 1 and chunks[0] == ".":
-                    chunks.append('')
-                #if chunks[-1] == '':
-                #    del chunks[-1]
-
-        elif isinstance(path, list):
-            chunks = path
-        elif isinstance(path, tuple):
-            chunks = list(path)
-        else:
-            raise ValueError, "unsupported path type"
-        super(Path, self).__init__(chunks)
-
-    #def __getitem__(self, num):
-    #    return
-
-    def __unicode__(self):
-        return unicode(os.path.sep).join(self)
-
-    def __str__(self):
-        return os.path.sep.join(self)
-
-    def __repr__(self):
-        return "<Path %s>" %list.__repr__(self)
-
-    def __cmp__(self, other):
-        rv = 0
-        if isinstance(other, Path):
-            for i in xrange(min(len(self), len(other))):
-                rv = cmp(self[i], other[i])
-                if rv:
-                    break
-            if not rv:
-                rv = cmp(len(self), len(other))
-            return rv