Commits

poelzi  committed 3376ab2

use Path objects
changes api what a Path("") means
more bugfixes

  • Participants
  • Parent commits 441ea02

Comments (0)

Files changed (7)

File genericoptions/models.py

             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:

File 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
 
     def parse_path(self, path):
         #rv = os.path.split(os.path.normpath(path))
-        rv = os.path.normpath(path).split(os.sep)
-        return list(rv)
+        #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 (last, [])
 
         # drop '' prefix
-        if ppath[0] == '':
+        if ppath and ppath[0] == '':
             del ppath[0]
 
         ppath.reverse()
                 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:
+        if len(ppath) > 1:
             raise ValueError, "Can't resolve path complete, more non existing childs %s" %ppath
 
         #Directory.objects.filter(parent=par,
         #            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):
     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:
             st = st.parent
         #na.append("/")
         na.reverse()
-        return os.path.join(*na)
+        return Path(na)
 
     def update_absolute(self):
-        self.absolute_path = self.get_absolute_path()[:255]
+        """Updates internal absolute path"""
+        self.absolute_path = str(self.get_absolute_path())[:255]
 
     def _get_name(self):
         return self._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
     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
     options = GenericOptions(instance=None)
 
     def _dirset(self):
-        print
         return Directory.objects.filter(parent__isnull=True)
     directory_set = property(_dirset)
 
 
 # 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)
     ctime  = models.DateTimeField(auto_now_add=True, editable=False)
     options = GenericOptions()
 
-
     objects = DirectoryManager()
 
 
         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):
     parent = models.ForeignKey(RealDirectory, null=False)
     options = GenericOptions()
     # contains meta information parsed out of the data part of file
-    metadata = GenericOptions()
+    metadata = GenericOptions(addident=1)
 
-    def __init__(self, create=False, *args, **kwargs):
-        models.Model.__init__(*args, **kwargs)
-        if create:
-            
-            if not os.exists(media_path):
+    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"
+                raise EnvironmentError, "Error creating new File, non file already exists"
 
 
     def _aliases_get(self):
     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()
     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)
 
         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.save()
         super(File, self).save(*args, **kwargs)
 
     def __repr__(self):

File vaultdb/tests/__init__.py

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

File vaultdb/tests/basic.py

 
         self.f1 = File(_name="f1")
         self.f1.save()
-        #print self.r1
         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()
     def test_resolver(self):
         #self.equal( Directory.objects.resolve_parent("/r1/r1s1")
         ROOT = ROOTDIRECTORY
-        self.assertEqual(Directory.objects.resolve_parent("/r1/r1s1"), (self.r1, ['r1s1']))
-        self.assertEqual(Directory.objects.resolve_parent("/r1"), (ROOT, ['r1']))
-        self.assertEqual(Directory.objects.resolve_parent(""), (ROOT, ['.']))
-        self.assertEqual(Directory.objects.resolve_parent("/"), (ROOT, ['']))
+        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(root, ROOTDIRECTORY)
         self.assertEqual(str(root), "/")
 
-        
-
 
 class TestOptions(TestBasic):
     """ Test option interface """
         self.assertEqual(str(p2), "/test/bla2")
         self.assertEqual(str(p3), "test")
         self.assertEqual(str(p4), "test/bla")
-        self.assertEqual(str(p5), "./")
+        self.assertEqual(str(p5), "")
         self.assertEqual(str(p6), "/")
         self.assertEqual(str(p7), "./")
         self.assertEqual(str(p8), "./")
         self.assertEqual(len(p2), 3)
         self.assertEqual(len(p3), 1)
         self.assertEqual(len(p4), 2)
-        self.assertEqual(len(p5), 2)
+        self.assertEqual(len(p5), 0)
         self.assertEqual(len(p6), 2)
         self.assertEqual(len(p7), 2)
         self.assertEqual(len(p8), 2)
         self.assertEqual(len(p10), 2)
         self.assertEqual(len(p11), 2)
 
-
-
-
     def test_cmp(self):
         pl = [
           Path("/test/bla"), Path("/test/bla"),
         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("/")

File vaultdb/tools.py

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

File vaultdb/vaulterrors.py

 class VaultException(Exception):
     pass
 
+
+class VaultConfigException(VaultException):
+    pass
+
 class VaultMediaException(VaultException):
     pass
 

File vaultfuse/vault_fuse.py

 
         if S_ISREG(flags):
             mode = S_IMODE(flags)
-            nf = models.File(mode=mode, _name = left[0])
+            nf = models.File(mode=mode, _name = left[0], create_realfile=True)
             par.add_child(nf, save=True)
-            nf.create_real_file()
         #if(par