s4: samba-tool user --help documenation improvements
[tridge/samba.git] / source4 / scripting / python / samba / netcmd / __init__.py
1 #!/usr/bin/env python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009-2011
5 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
6 # Copyright (C) Giampaolo Lauria <lauria2@yahoo.com> 2011
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
25 import sys, traceback
26 import textwrap
27
28 class Option(optparse.Option):
29     pass
30
31 # This help formatter does text wrapping and preserves newlines
32 class PlainHelpFormatter(optparse.IndentedHelpFormatter):
33     def format_description(self,description=""):
34             desc_width = self.width - self.current_indent
35             indent = " "*self.current_indent
36             paragraphs = description.split('\n')
37             wrapped_paragraphs = [
38                 textwrap.fill(p,
39                         desc_width,
40                         initial_indent=indent,
41                         subsequent_indent=indent)
42                 for p in paragraphs]
43             result = "\n".join(wrapped_paragraphs) + "\n"
44             return result
45
46
47 class Command(object):
48     """A samba-tool command."""
49
50     def _get_short_description(self):
51         return self.__doc__.splitlines()[0].rstrip("\n")
52
53     short_description = property(_get_short_description)
54
55     def _get_full_description(self):
56         lines = self.__doc__.split("\n")
57         return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
58
59     full_description = property(_get_full_description)
60
61     def _get_name(self):
62         name = self.__class__.__name__
63         if name.startswith("cmd_"):
64             return name[4:]
65         return name
66
67     name = property(_get_name)
68
69     # synopsis must be defined in all subclasses in order to provide the
70     # command usage
71     synopsis = None
72     takes_args = []
73     takes_options = []
74     takes_optiongroups = {
75         "sambaopts": options.SambaOptions,
76         "credopts": options.CredentialsOptions,
77         "versionopts": options.VersionOptions,
78         }
79
80     def __init__(self, outf=sys.stdout, errf=sys.stderr):
81         self.outf = outf
82         self.errf = errf
83
84     def usage(self, prog, *args):
85         parser, _ = self._create_parser(prog)
86         parser.print_usage()
87
88     def show_command_error(self, e):
89         '''display a command error'''
90         if isinstance(e, CommandError):
91             (etype, evalue, etraceback) = e.exception_info
92             inner_exception = e.inner_exception
93             message = e.message
94             force_traceback = False
95         else:
96             (etype, evalue, etraceback) = sys.exc_info()
97             inner_exception = e
98             message = "uncaught exception"
99             force_traceback = True
100
101         if isinstance(inner_exception, LdbError):
102             (ldb_ecode, ldb_emsg) = inner_exception
103             self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
104         elif isinstance(inner_exception, AssertionError):
105             self.errf.write("ERROR(assert): %s\n" % message)
106             force_traceback = True
107         elif isinstance(inner_exception, RuntimeError):
108             self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
109         elif type(inner_exception) is Exception:
110             self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
111             force_traceback = True
112         elif inner_exception is None:
113             self.errf.write("ERROR: %s\n" % (message))
114         else:
115             self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
116             force_traceback = True
117
118         if force_traceback or samba.get_debug_level() >= 3:
119             traceback.print_tb(etraceback)
120
121     def _create_parser(self, prog):
122         parser = optparse.OptionParser(
123             usage=self.synopsis,
124             description=self.full_description,
125             formatter=PlainHelpFormatter(),
126             prog=prog)
127         parser.add_options(self.takes_options)
128         optiongroups = {}
129         for name, optiongroup in self.takes_optiongroups.iteritems():
130             optiongroups[name] = optiongroup(parser)
131             parser.add_option_group(optiongroups[name])
132         return parser, optiongroups
133
134     def message(self, text):
135         self.outf.write(text+"\n")
136
137     def _run(self, *argv):
138         parser, optiongroups = self._create_parser(argv[0])
139         opts, args = parser.parse_args(list(argv))
140         # Filter out options from option groups
141         args = args[1:]
142         kwargs = dict(opts.__dict__)
143         for option_group in parser.option_groups:
144             for option in option_group.option_list:
145                 if option.dest is not None:
146                     del kwargs[option.dest]
147         kwargs.update(optiongroups)
148
149         # Check for a min a max number of allowed arguments, whenever possible
150         # The suffix "?" means zero or one occurence
151         # The suffix "+" means at least one occurence
152         min_args = 0
153         max_args = 0
154         undetermined_max_args = False
155         for i, arg in enumerate(self.takes_args):
156             if arg[-1] != "?":
157                min_args += 1
158             if arg[-1] == "+":
159                undetermined_max_args = True
160             else:
161                max_args += 1
162         if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
163             parser.print_usage()
164             return -1
165
166         try:
167             return self.run(*args, **kwargs)
168         except Exception, e:
169             self.show_command_error(e)
170             return -1
171
172     def run(self):
173         """Run the command. This should be overriden by all subclasses."""
174         raise NotImplementedError(self.run)
175
176     def get_logger(self, name="netcmd"):
177         """Get a logger object."""
178         import logging
179         logger = logging.getLogger(name)
180         logger.addHandler(logging.StreamHandler(self.outf))
181         return logger
182
183
184 class SuperCommand(Command):
185     """A samba-tool command with subcommands."""
186
187     synopsis = "%prog <subcommand>"
188
189     subcommands = {}
190
191     def _run(self, myname, subcommand=None, *args):
192         if subcommand in self.subcommands:
193             return self.subcommands[subcommand]._run(
194                 "%s %s" % (myname, subcommand), *args)
195
196         self.usage(myname)
197         self.outf.write("Available subcommands:\n")
198         subcmds = self.subcommands.keys()
199         subcmds.sort()
200         max_length = max([len(c) for c in subcmds])
201         for cmd in subcmds:
202             self.outf.write("  %*s  - %s\n" % (
203                 -max_length, cmd, self.subcommands[cmd].short_description))
204         if subcommand in [None]:
205             raise CommandError("You must specify a subcommand")
206         if subcommand in ['help', '-h', '--help']:
207             self.outf.write("For more help on a specific subcommand, please type: %s (-h|--help)\n" % myname)
208             return 0
209         raise CommandError("No such subcommand '%s'" % subcommand)
210
211
212
213 class CommandError(Exception):
214     """An exception class for samba-tool Command errors."""
215
216     def __init__(self, message, inner_exception=None):
217         self.message = message
218         self.inner_exception = inner_exception
219         self.exception_info = sys.exc_info()