82 lines
2.7 KiB
Python
82 lines
2.7 KiB
Python
|
# -*- coding: UTF-8 -*-
|
||
|
#
|
||
|
# Copyright (C) 2007 by Jan Dittberner.
|
||
|
#
|
||
|
# This program is free software; you can redistribute it and/or modify
|
||
|
# it under the terms of the GNU General Public License as published by
|
||
|
# the Free Software Foundation; either version 2 of the License, or
|
||
|
# (at your option) any later version.
|
||
|
#
|
||
|
# This program is distributed in the hope that it will be useful, but
|
||
|
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||
|
# General Public License for more details.
|
||
|
#
|
||
|
# You should have received a copy of the GNU General Public License
|
||
|
# along with this program; if not, write to the Free Software
|
||
|
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
|
||
|
# USA.
|
||
|
#
|
||
|
# Version: $Id$
|
||
|
|
||
|
import getopt, sys
|
||
|
|
||
|
class CliCommand:
|
||
|
"""Base class for command line interface."""
|
||
|
def usage(self):
|
||
|
"""This method should print usage information for the command."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def shortopts(self):
|
||
|
"""This method should return an option string for the short
|
||
|
options for getopt.gnu_getopt(...)."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def longopts(self):
|
||
|
"""This method should return a list of long options for
|
||
|
getopt.gnu_getopt(...)."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def handleoption(self, option, argument):
|
||
|
"""This method should handle each option known to the command."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def execute(self):
|
||
|
"""This method is called when the command is executed."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def checkrequired(self):
|
||
|
"""This methode is called after handling command line options
|
||
|
and should check whether all required values were set."""
|
||
|
raise NotImplementedError
|
||
|
|
||
|
def __parseopts(self, args):
|
||
|
"""This method parses the options given on the command line."""
|
||
|
longopts = ["help", "verbose"]
|
||
|
longopts.extend(self.longopts())
|
||
|
try:
|
||
|
opts, args = getopt.gnu_getopt(
|
||
|
args,
|
||
|
"hv" + self.shortopts(),
|
||
|
longopts)
|
||
|
except getopt.GetoptError:
|
||
|
self.usage()
|
||
|
sys.exit(2)
|
||
|
self.verbose = False
|
||
|
for o, a in opts:
|
||
|
if o in ("-v", "--verbose"):
|
||
|
self.verbose = True
|
||
|
if o in ("-h", "--help"):
|
||
|
self.usage()
|
||
|
sys.exit()
|
||
|
self.handleoption(o, a)
|
||
|
|
||
|
def __init__(self, args):
|
||
|
"""This initializes the command with the given command line
|
||
|
arguments and executes it."""
|
||
|
self.__parseopts(args)
|
||
|
if (self.checkrequired()):
|
||
|
self.execute()
|
||
|
else:
|
||
|
self.usage()
|