s4:samba-tool: add optional epilog to _create_parser()
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / netcmd / __init__.py
blob677f4f0fc2a40a93a1dabcd45dca006cfd182e87
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009-2012
3 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 import optparse, samba
20 from samba import getopt as options
21 from ldb import LdbError
22 import sys, traceback
23 import textwrap
25 class Option(optparse.Option):
26 pass
28 # This help formatter does text wrapping and preserves newlines
29 class PlainHelpFormatter(optparse.IndentedHelpFormatter):
30 def format_description(self,description=""):
31 desc_width = self.width - self.current_indent
32 indent = " "*self.current_indent
33 paragraphs = description.split('\n')
34 wrapped_paragraphs = [
35 textwrap.fill(p,
36 desc_width,
37 initial_indent=indent,
38 subsequent_indent=indent)
39 for p in paragraphs]
40 result = "\n".join(wrapped_paragraphs) + "\n"
41 return result
43 def format_epilog(self, epilog):
44 if epilog:
45 return "\n" + epilog + "\n"
46 else:
47 return ""
49 class Command(object):
50 """A samba-tool command."""
52 def _get_short_description(self):
53 return self.__doc__.splitlines()[0].rstrip("\n")
55 short_description = property(_get_short_description)
57 def _get_full_description(self):
58 lines = self.__doc__.split("\n")
59 return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
61 full_description = property(_get_full_description)
63 def _get_name(self):
64 name = self.__class__.__name__
65 if name.startswith("cmd_"):
66 return name[4:]
67 return name
69 name = property(_get_name)
71 # synopsis must be defined in all subclasses in order to provide the
72 # command usage
73 synopsis = None
74 takes_args = []
75 takes_options = []
76 takes_optiongroups = {}
78 hidden = False
80 raw_argv = None
81 raw_args = None
82 raw_kwargs = None
84 def __init__(self, outf=sys.stdout, errf=sys.stderr):
85 self.outf = outf
86 self.errf = errf
88 def usage(self, prog, *args):
89 parser, _ = self._create_parser(prog)
90 parser.print_usage()
92 def show_command_error(self, e):
93 '''display a command error'''
94 if isinstance(e, CommandError):
95 (etype, evalue, etraceback) = e.exception_info
96 inner_exception = e.inner_exception
97 message = e.message
98 force_traceback = False
99 else:
100 (etype, evalue, etraceback) = sys.exc_info()
101 inner_exception = e
102 message = "uncaught exception"
103 force_traceback = True
105 if isinstance(inner_exception, LdbError):
106 (ldb_ecode, ldb_emsg) = inner_exception
107 self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
108 elif isinstance(inner_exception, AssertionError):
109 self.errf.write("ERROR(assert): %s\n" % message)
110 force_traceback = True
111 elif isinstance(inner_exception, RuntimeError):
112 self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
113 elif type(inner_exception) is Exception:
114 self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
115 force_traceback = True
116 elif inner_exception is None:
117 self.errf.write("ERROR: %s\n" % (message))
118 else:
119 self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
120 force_traceback = True
122 if force_traceback or samba.get_debug_level() >= 3:
123 traceback.print_tb(etraceback)
125 def _create_parser(self, prog, epilog=None):
126 parser = optparse.OptionParser(
127 usage=self.synopsis,
128 description=self.full_description,
129 formatter=PlainHelpFormatter(),
130 prog=prog,epilog=epilog)
131 parser.add_options(self.takes_options)
132 optiongroups = {}
133 for name, optiongroup in self.takes_optiongroups.iteritems():
134 optiongroups[name] = optiongroup(parser)
135 parser.add_option_group(optiongroups[name])
136 return parser, optiongroups
138 def message(self, text):
139 self.outf.write(text+"\n")
141 def _run(self, *argv):
142 parser, optiongroups = self._create_parser(argv[0])
143 opts, args = parser.parse_args(list(argv))
144 # Filter out options from option groups
145 args = args[1:]
146 kwargs = dict(opts.__dict__)
147 for option_group in parser.option_groups:
148 for option in option_group.option_list:
149 if option.dest is not None:
150 del kwargs[option.dest]
151 kwargs.update(optiongroups)
153 # Check for a min a max number of allowed arguments, whenever possible
154 # The suffix "?" means zero or one occurence
155 # The suffix "+" means at least one occurence
156 min_args = 0
157 max_args = 0
158 undetermined_max_args = False
159 for i, arg in enumerate(self.takes_args):
160 if arg[-1] != "?":
161 min_args += 1
162 if arg[-1] == "+":
163 undetermined_max_args = True
164 else:
165 max_args += 1
166 if (len(args) < min_args) or (not undetermined_max_args and len(args) > max_args):
167 parser.print_usage()
168 return -1
170 self.raw_argv = list(argv)
171 self.raw_args = args
172 self.raw_kwargs = kwargs
174 try:
175 return self.run(*args, **kwargs)
176 except Exception, e:
177 self.show_command_error(e)
178 return -1
180 def run(self):
181 """Run the command. This should be overriden by all subclasses."""
182 raise NotImplementedError(self.run)
184 def get_logger(self, name="netcmd"):
185 """Get a logger object."""
186 import logging
187 logger = logging.getLogger(name)
188 logger.addHandler(logging.StreamHandler(self.errf))
189 return logger
192 class SuperCommand(Command):
193 """A samba-tool command with subcommands."""
195 synopsis = "%prog <subcommand>"
197 subcommands = {}
199 def _run(self, myname, subcommand=None, *args):
200 if subcommand in self.subcommands:
201 return self.subcommands[subcommand]._run(
202 "%s %s" % (myname, subcommand), *args)
204 self.usage(myname)
205 self.outf.write("Available subcommands:\n")
206 subcmds = self.subcommands.keys()
207 subcmds.sort()
208 max_length = max([len(c) for c in subcmds])
209 for cmd_name in subcmds:
210 cmd = self.subcommands[cmd_name]
211 if not cmd.hidden:
212 self.outf.write(" %*s - %s\n" % (
213 -max_length, cmd_name, cmd.short_description))
214 if subcommand in [None]:
215 raise CommandError("You must specify a subcommand")
216 if subcommand in ['help', '-h', '--help']:
217 self.outf.write("For more help on a specific subcommand, please type: %s <subcommand> (-h|--help)\n" % myname)
218 return 0
219 raise CommandError("No such subcommand '%s'" % subcommand)
222 class CommandError(Exception):
223 """An exception class for samba-tool Command errors."""
225 def __init__(self, message, inner_exception=None):
226 self.message = message
227 self.inner_exception = inner_exception
228 self.exception_info = sys.exc_info()