samba-tool: Moved command definition to sambatool command
[Samba.git] / source4 / scripting / python / samba / netcmd / __init__.py
bloba4a3397d80e53247e7ca2bd962e430faee18044a
1 #!/usr/bin/env python
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009
5 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
6 # Copyright (C) Giampaolo Lauria <lauria2@yahoo.com> 2011
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
25 import sys, traceback
28 class Option(optparse.Option):
29 pass
33 class Command(object):
34 """A samba-tool command."""
36 def _get_description(self):
37 return self.__doc__.splitlines()[0].rstrip("\n")
39 description = property(_get_description)
41 # synopsis must be defined in all subclasses in order to provide the command usage
42 synopsis = ""
43 # long_description is a string describing the command in details
44 long_description = ""
45 takes_args = []
46 takes_options = []
47 takes_optiongroups = {
48 "sambaopts": options.SambaOptions,
49 "credopts": options.CredentialsOptions,
50 "versionopts": options.VersionOptions,
52 # This epilog will print at the end when the user invokes the command w/ -h or --help
53 epilog = ""
54 outf = sys.stdout
56 def usage(self, *args):
57 parser, _ = self._create_parser()
58 parser.print_usage()
60 def show_command_error(self, e):
61 '''display a command error'''
62 if isinstance(e, CommandError):
63 (etype, evalue, etraceback) = e.exception_info
64 inner_exception = e.inner_exception
65 message = e.message
66 force_traceback = False
67 else:
68 (etype, evalue, etraceback) = sys.exc_info()
69 inner_exception = e
70 message = "uncaught exception"
71 force_traceback = True
73 if isinstance(inner_exception, LdbError):
74 (ldb_ecode, ldb_emsg) = inner_exception
75 print >>sys.stderr, "ERROR(ldb): %s - %s" % (message, ldb_emsg)
76 elif isinstance(inner_exception, AssertionError):
77 print >>sys.stderr, "ERROR(assert): %s" % message
78 force_traceback = True
79 elif isinstance(inner_exception, RuntimeError):
80 print >>sys.stderr, "ERROR(runtime): %s - %s" % (message, evalue)
81 elif type(inner_exception) is Exception:
82 print >>sys.stderr, "ERROR(exception): %s - %s" % (message, evalue)
83 force_traceback = True
84 elif inner_exception is None:
85 print >>sys.stderr, "ERROR: %s" % (message)
86 else:
87 print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
88 force_traceback = True
90 if force_traceback or samba.get_debug_level() >= 3:
91 traceback.print_tb(etraceback)
92 sys.exit(1)
94 def _create_parser(self):
95 parser = optparse.OptionParser(usage=self.synopsis, epilog=self.epilog,
96 description=self.long_description)
97 parser.add_options(self.takes_options)
98 optiongroups = {}
99 for name, optiongroup in self.takes_optiongroups.iteritems():
100 optiongroups[name] = optiongroup(parser)
101 parser.add_option_group(optiongroups[name])
102 return parser, optiongroups
104 def message(self, text):
105 print text
107 def _run(self, *argv):
108 parser, optiongroups = self._create_parser()
109 opts, args = parser.parse_args(list(argv))
110 # Filter out options from option groups
111 args = args[1:]
112 kwargs = dict(opts.__dict__)
113 for option_group in parser.option_groups:
114 for option in option_group.option_list:
115 if option.dest is not None:
116 del kwargs[option.dest]
117 kwargs.update(optiongroups)
119 # Check for a min a max number of allowed arguments, whenever possible
120 # The suffix "?" means zero or one occurence
121 # The suffix "+" means at least one occurence
122 min_args = 0
123 max_args = 0
124 undetermined_max_args = False
125 for i, arg in enumerate(self.takes_args):
126 if arg[-1] != "?":
127 min_args += 1
128 if arg[-1] == "+":
129 undetermined_max_args = True
130 else:
131 max_args += 1
132 if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
133 parser.print_usage()
134 return -1
136 try:
137 return self.run(*args, **kwargs)
138 except Exception, e:
139 self.show_command_error(e)
140 return -1
142 def run(self):
143 """Run the command. This should be overriden by all subclasses."""
144 raise NotImplementedError(self.run)
148 class SuperCommand(Command):
149 """A samba-tool command with subcommands."""
151 subcommands = {}
153 def _run(self, myname, subcommand=None, *args):
154 if subcommand in self.subcommands:
155 return self.subcommands[subcommand]._run(subcommand, *args)
157 if (myname == "samba-tool"):
158 usage = "samba-tool <subcommand>"
159 else:
160 usage = "samba-tool %s <subcommand>" % myname
161 print "Usage: %s [options]" %usage
162 print "Available subcommands:"
163 subcmds = self.subcommands.keys()
164 subcmds.sort()
165 for cmd in subcmds:
166 print " %-20s - %s" % (cmd, self.subcommands[cmd].description)
167 if subcommand in [None]:
168 raise CommandError("You must specify a subcommand")
169 if subcommand in ['help', '-h', '--help']:
170 print "For more help on a specific subcommand, please type: %s (-h|--help)" % usage
171 return 0
172 raise CommandError("No such subcommand '%s'" % subcommand)
176 class CommandError(Exception):
177 '''an exception class for samba-tool cmd errors'''
178 def __init__(self, message, inner_exception=None):
179 self.message = message
180 self.inner_exception = inner_exception
181 self.exception_info = sys.exc_info()