Source

vaultfs-main / vault.py

#!/usr/bin/env python2.5

# adjust python path
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'external'))
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..')))

from django.core.management import execute_manager
try:
    from vaultfs import settings
    #import settings # Assumed to be in the same directory.
except ImportError:
    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)

#if __name__ == "__main__":
#    execute_manager(settings)
from django.conf import settings as dsettings

dsettings.configure(settings)

#settings.configure(self,)


import optparse
from vaultdb import commands

from __init__ import VERSION, HVERSION

class LazyOptionParser(optparse.OptionParser):
    def __init__(self, *args, **kwargs):
        cb = kwargs.pop("command_base")
        optparse.OptionParser.__init__(self, *args, **kwargs)
        self.command_base = cb
        self.dosuper = False

    def print_help(self, *args, **kwargs):
        if  self.dosuper:
            optparse.OptionParser.print_help(self, *args, **kwargs)
            if self.command_base.current_command != None:
                print "\nCommands:"
                self.command_base.current_command.print_help()

    def error(self, *args, **kwargs):
        if  self.dosuper:
            optparse.OptionParser.error(self, *args, **kwargs)

    def exit(self, *args, **kwargs):
        if  self.dosuper:
            optparse.OptionParser.exit(self, *args, **kwargs)


class VaultCommandBase(object):
    def __init__(self):
        self.parser = LazyOptionParser(
          usage = '%prog [options] ...',
          version = '%%prog version %s' %HVERSION ,
          command_base = self,
        )
        self.parser.add_option("-n", "--name", help="Config name to use. NAME or USER:NAME")
        #self.parser.add_option("-V", "--version", help="Print version")
        self.parser.add_option("-v", "--verbose", help="Verbose",
                                action="count", dest="verbosity", default=0)

        self.commands = []
        self.current_command = None

        # register core commands
        for k,i in commands.__dict__.iteritems():
            if type(i) == type(type) and issubclass(i, commands.Command) and i != commands.Command:
                self.commands.append(i(self))

        # register plugin commands
        # FIXME

    def print_commandlist(self):
        self.parser.dosuper = True
        self.parser.print_help()
        print "\nCommands:"
        for i in self.commands:
            if i.prefix:
                print "\t%s\t %s" %(i.prefix, i._help_)

    def get_module(self, name):
        for i in self.commands:
            if i.prefix == name:
                return i


    def parse(self, argv):
        values, args = self.parser.parse_args(argv[1:])

        from vaultfs.core import conf
        #print values.mount
        try:
            conf.set_environment(values.name)
        except EnvironmentError, e:
            #self.parser.dosuper = True
            #self.parser.error("Can't detect config to use. Please use the -n NAME")
            pass

        # check if command is given
        if not len(args):
            self.parser.dosuper = True
            self.print_commandlist()
            return

        # register command options
        self.current_command = cc = self.get_module(args[0])
        if cc is None:
            if args[0] == "help":
                self.parser.dosuper = True
                if len(args) == 1:
                    self.print_commandlist()
                    return
                # help mode
                cm = self.get_module(args[1])
                if cm is None:
                    print self.parser.print_help()
                    print "Command not found"
                    #self.print_commandlist()
                    return

                print "Help for command: %s" %" ".join(args[1:])
                print ""

                if len(args) > 2:
                    rl = cm.help_for(*args[2:])
                    print rl[None].__doc__
                    #mod =
                else:
                    doc = cm.help_for('ALL') # *args[2:])
                    mod = doc[None]
                    for k,n in doc.iteritems():
                        if k is None:
                            print "%s\n" %n.__doc__
                        else:
                            mod.hl(k, n._help_)

            return
        self.current_command.register_options(self.parser)

        # reparse
        values, args = self.parser.parse_args(argv[1:])
        print values, args
        if cc is None:
            self.print_commandlist()
            return

        self.parser.dosuper = True

        try:
            cc.run(args, values)
        except commands.PrintHelpException, e:
            print "%s\n" %e
            self.parser.print_help()
        except optparse.BadOptionError, e:
            #self.parser.print_help()
            self.parser.error(e)
        except EnvironmentError, e:
            #self.parser.print_help()
            self.parser.error(e)


def main(argv):
    v = VaultCommandBase()
    v.parse(argv)

    #parser.add_option('--set', action = 'append', default = [ ])
    #parser.add_option('--remove', action = 'append', default = [ ])
    

if __name__ == "__main__":
    import sys
    main(sys.argv)