samba-tool: Some more unifications...
[samba.git] / source4 / scripting / python / samba / netcmd / __init__.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009-2012
3 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
4 #
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.
9 #
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.
14 #
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/>.
17 #
18
19 import optparse, samba
20 from samba import getopt as options
21 from ldb import LdbError
22 import sys, traceback
23 import textwrap
24
25 class Option(optparse.Option):
26     pass
27
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
42
43     def format_epilog(self, epilog):
44         if epilog:
45             return "\n" + epilog + "\n"
46         else:
47             return ""
48
49 class Command(object):
50     """A samba-tool command."""
51
52     def _get_short_description(self):
53         return self.__doc__.splitlines()[0].rstrip("\n")
54
55     short_description = property(_get_short_description)
56
57     def _get_full_description(self):
58         lines = self.__doc__.split("\n")
59         return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
60
61     full_description = property(_get_full_description)
62
63     def _get_name(self):
64         name = self.__class__.__name__
65         if name.startswith("cmd_"):
66             return name[4:]
67         return name
68
69     name = property(_get_name)
70
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 = {}
77
78     hidden = False
79
80     raw_argv = None
81     raw_args = None
82     raw_kwargs = None
83
84     def __init__(self, outf=sys.stdout, errf=sys.stderr):
85         self.outf = outf
86         self.errf = errf
87
88     def usage(self, prog, *args):
89         parser, _ = self._create_parser(prog)
90         parser.print_usage()
91
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
104
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
121
122         if force_traceback or samba.get_debug_level() >= 3:
123             traceback.print_tb(etraceback)
124
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
137
138     def message(self, text):
139         self.outf.write(text+"\n")
140
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)
152
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
169
170         self.raw_argv = list(argv)
171         self.raw_args = args
172         self.raw_kwargs = kwargs
173
174         try:
175             return self.run(*args, **kwargs)
176         except Exception, e:
177             self.show_command_error(e)
178             return -1
179
180     def run(self):
181         """Run the command. This should be overriden by all subclasses."""
182         raise NotImplementedError(self.run)
183
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
190
191
192 class SuperCommand(Command):
193     """A samba-tool command with subcommands."""
194
195     synopsis = "%prog <subcommand>"
196
197     subcommands = {}
198
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)
203
204         epilog = "\nAvailable subcommands:\n"
205         subcmds = self.subcommands.keys()
206         subcmds.sort()
207         max_length = max([len(c) for c in subcmds])
208         for cmd_name in subcmds:
209             cmd = self.subcommands[cmd_name]
210             if not cmd.hidden:
211                 epilog += "  %*s  - %s\n" % (
212                     -max_length, cmd_name, cmd.short_description)
213         epilog += "For more help on a specific subcommand, please type: %s <subcommand> (-h|--help)\n" % myname
214
215         parser, optiongroups = self._create_parser(myname, epilog=epilog)
216         args_list = list(args)
217         if subcommand:
218             args_list.insert(0, subcommand)
219         opts, args = parser.parse_args(args_list)
220
221         parser.print_help()
222         return -1
223
224
225 class CommandError(Exception):
226     """An exception class for samba-tool Command errors."""
227
228     def __init__(self, message, inner_exception=None):
229         self.message = message
230         self.inner_exception = inner_exception
231         self.exception_info = sys.exc_info()