1
0
Fork 0

start argparse transition (addresses #33)

* use argparse instead of old home grown solution for argument
   parsing
 * change ClientCli class to use argparse
 * disable SysuserCli, DomainCli and RecordCli
 * mark strings as translatable (addresses #34)
This commit is contained in:
Jan Dittberner 2009-08-01 15:33:34 +02:00
parent 076621a0be
commit b8139e91f2
3 changed files with 91 additions and 93 deletions

View file

@ -18,13 +18,13 @@
# USA. # USA.
# #
# Version: $Id$ # Version: $Id$
import getopt import argparse
import sys import sys
import logging import logging
from gnuviechadmin.exceptions import GnuviechadminError from gnuviechadmin.exceptions import GnuviechadminError
class CliCommand: class CliCommand(object):
"""Base class for command line interface. """Base class for command line interface.
A specific implementation class must define the fields name, A specific implementation class must define the fields name,
@ -50,7 +50,7 @@ class CliCommand:
"""This method shows usage information. The implementation """This method shows usage information. The implementation
relies on the information in the fields name, description and relies on the information in the fields name, description and
_optionmap in the implementation classes.""" _optionmap in the implementation classes."""
print """GNUViechAdmin command line interface return """GNUViechAdmin command line interface
Subcommand: %(command)s Subcommand: %(command)s
@ -201,26 +201,7 @@ Common options:
"""This initializes the command with the given command line """This initializes the command with the given command line
arguments and executes it.""" arguments and executes it."""
self.config = config self.config = config
self.args = args
self.logger = logging.getLogger("%s.%s" % ( self.logger = logging.getLogger("%s.%s" % (
self.__class__.__module__, self.__class__.__name__)) self.__class__.__module__, self.__class__.__name__))
self._data = {} self._execute()
if len(args) > 0:
if args[0] in self._subcommands():
self._parseopts(args[0], args[1:])
reqcheck = self._checkrequired(args[0])
if reqcheck[0]:
try:
self._execute(args[0])
except GnuviechadminError, e:
print e
else:
self._usage()
print """
the following required arguments are missing:
"""
print "\n".join(reqcheck[1])
else:
self._usage()
print "invalid sub command"
else:
self._usage()

View file

@ -27,36 +27,28 @@ __all__ = ["client", "sysuser", "domain", "record"]
from logging import getLogger from logging import getLogger
from sys import exit from sys import exit
from argparse import ArgumentParser
from gettext import gettext as _
class CommandLineInterface(object): class CommandLineInterface(object):
def __init__(self, config, args): def __init__(self, config, args):
self.log = getLogger(__name__) self.log = getLogger(__name__)
self.config = config self.config = config
if len(args) < 2: parser = ArgumentParser(prog=args[0])
self._usage(args[0]) parser.add_argument(
exit(1) '-v', '--verbose',
self.commands = [command for command in self._get_commands() \ help = _('enable verbose output'),
if command.name == args[1]] action = 'store_true')
self.cmdargs = args[2:] subparsers = parser.add_subparsers(
title = _('subcommands'), dest = 'command')
def _usage(self, callee):
print """%s <command> [commandargs]
where command is one of
""" % callee
for command in self._get_commands():
print "%10s - %s" % (command.name, command.description)
def run(self):
for cmd in self.commands:
cmd(self.cmdargs, self.config)
def _get_commands(self):
from gnuviechadmin.cli.client import ClientCli from gnuviechadmin.cli.client import ClientCli
from gnuviechadmin.cli.sysuser import SysuserCli from gnuviechadmin.cli.sysuser import SysuserCli
from gnuviechadmin.cli.domain import DomainCli from gnuviechadmin.cli.domain import DomainCli
from gnuviechadmin.cli.record import RecordCli from gnuviechadmin.cli.record import RecordCli
return [ClientCli, SysuserCli, DomainCli, RecordCli] for command in [ClientCli]:
command.setup_argparser(subparsers)
self.parsedargs = parser.parse_args(args[1:])
def run(self):
self.parsedargs.commandclass(self.parsedargs, self.config)

View file

@ -20,66 +20,91 @@
# Version: $Id$ # Version: $Id$
import CliCommand import CliCommand
import sys import sys
from gettext import gettext as _
class ClientCli(CliCommand.CliCommand): class ClientCli(CliCommand.CliCommand):
"""Command line interface command for client management.""" """Command line interface command for client management."""
name = "client" @staticmethod
description = "manage clients" def setup_argparser(subparsers):
_optionmap = { parser = subparsers.add_parser(
'create': ("creates a new client", 'client',
[(["-f", "--firstname"], "firstname", help = _('manage clients'))
"the client's first name", True), parser.set_defaults(commandclass=ClientCli)
(["-l", "--lastname"], "lastname", cmdsub = parser.add_subparsers(
"the client's last name", True), title = _('client subcommands'), dest = 'subcommand')
(["-t", "--title"], "title", cmdparser = cmdsub.add_parser(
"the client's title", False), 'create',
(["-a", "--address"], "address1", help = _('creates a new client'))
"the address of the client", True), cmdparser.add_argument(
(["--address2"], "address2", '-f', '--firstname', required = True,
"second line of the client's address", False), help = _("the client's first name"))
(["-z", "--zip"], "zip", cmdparser.add_argument(
"the zipcode of the client's address", True), '-l', '--lastname', required = True,
(["-c", "--city"], "city", help = _("the client's last name"))
"the city of the client's address", True), cmdparser.add_argument(
(["--country"], "country", '-t', '--title',
"the client's country", False), help = _("the client's title"))
(["-e", "--email"], "email", cmdparser.add_argument(
"the client's email address", True), '-a', '--address', dest = 'address1', required = True,
(["-p", "--phone"], "phone", help = _("the address of the client"))
"the client's phone number", True), cmdparser.add_argument(
(["-m", "--mobile"], "mobile", '--address2',
"the client's mobile phone number", False), help = _("second line of the client's address"))
(["-x", "--fax"], "fax", cmdparser.add_argument(
"the client's fax number", False)]), '-z', '--zip', required = True,
'list': ("lists existing clients", []), help = _("the zipcode of the client's address"))
'delete': ("deletes the specified client if it has no dependent data", cmdparser.add_argument(
[(["-c", "--clientid"], "clientid", '-c', '--city', required = True,
"the client id", True)])} help = _("the city of the client's address"))
cmdparser.add_argument(
'--country',
help = _("the client's country"))
cmdparser.add_argument(
'-e', '--email', required = True,
help = _("the client's email address"))
cmdparser.add_argument(
'-p', '--phone', required = True,
help = _("the client's phone number"))
cmdparser.add_argument(
'-m', '--mobile',
help = _("the client's mobile phone number"))
cmdparser.add_argument(
'-x', '--fax',
help = _("the client's fax number"))
cmdparser = cmdsub.add_parser(
'list',
help = _('lists existing clients'))
cmdparser = cmdsub.add_parser(
'delete',
help = _(
'deletes the specified client if it has no dependent data'))
cmdparser.add_argument(
'-c', '--clientid', required = True,
help = _("the client id"))
def _execute(self, subcommand): def _execute(self):
self.logger.debug("execute %s with data %s", subcommand, self.logger.debug("execute %s", self.args)
str(self._data))
from gnuviechadmin.backend.client import ClientHandler from gnuviechadmin.backend.client import ClientHandler
from gnuviechadmin.exceptions import CreationFailedError from gnuviechadmin.exceptions import CreationFailedError
if subcommand == "create": ch = ClientHandler(self.config, self.args.verbose)
if self.args.subcommand == "create":
try: try:
myclient = ClientHandler(self.config, myclient = ch.create(**self.args)
self._verbose).create(**self._data) if self.args.verbose:
if self._verbose:
print myclient print myclient
except CreationFailedError, cfe: except CreationFailedError, cfe:
self._usage() self._usage()
print cfe print cfe
sys.exit(2) sys.exit(2)
elif subcommand == "list": elif self.args.subcommand == "list":
clients = ClientHandler(self.config, self._verbose).fetchall() clients = ch.fetchall()
for client in clients: for client in clients:
print client print client
elif subcommand == "delete": elif self.args.subcommand == "delete":
ClientHandler(self.config, ch.delete(self.args.clientid)
self._verbose).delete(self._data["clientid"])
def __init__(self, args, config):
CliCommand.CliCommand.__init__(self, args, config)
def __init__(self, argv, config):
CliCommand.CliCommand.__init__(self, argv, config)