metashelf / directory.py

#  metashelf: A vcs-friendly store for filesystem metadata
#
#  Copyright (C) 2008       Solomon Hykes <solomon.hykes@gmail.com>
#  Copyright (C) 2009-2010  dotCloud SARL <solomon.hykes@dotcloud.com>

import os
import shutil

class Directory(object):

    def __init__(self, path):
        self.__path = os.path.abspath(path)

    def path(self, *subpath):
        return os.path.normpath(os.path.sep.join((self.__path, ) + subpath))

    def relpath(self, abspath):
        d = Directory(abspath)
        if not self.contains(d):
            raise ValueError("%s is not contained by %s" % (d.path(), self.path()))
        if d == self:
            return "."
        return d.path().replace(self.path() + "/", "")
    
    def __cmp__(self, other):
        return cmp(self.path(), other.path())

    def subdir(self, *subpath):
        d = Directory(self.path(*subpath))
        if not self.contains(d):
            raise ValueError("%s is not contained by %s" % (d.path(), self.path()))
        return d

    def exists(self):
        return os.path.exists(self.path())

    def contains(self, other):
        if os.path.commonprefix([self.path(), other.path()]) == self.path():
            return True
        return False

    def remove(self):
        shutil.rmtree(self.path())

    def create(self):
        os.makedirs(self.path())

    def makedirs(self, *subpath):
        return os.makedirs(self.path(*subpath))

    def __iter__(self):
        if not self.exists():
            return iter(())
        return iter(os.listdir(self.path()))

    def walk(self):
        """ Iterate over all sub-paths inside this directory """
        for (dirpath, dirnames, filenames) in os.walk(self.path()):
            yield self.relpath(dirpath)
            for filename in filenames:
                yield self.relpath(os.path.join(dirpath, filename))

    def __len__(self):
        return len(list(iter(self)))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.