0687016c6d769a0e10975ef635d615c8305c3232
[samba.git] / 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
20 import samba
21 from samba import getopt as options
22 from samba import colour
23 from samba.logger import get_samba_logger
24 from ldb import LdbError
25 import sys
26 import traceback
27 import textwrap
28
29
30 class Option(optparse.Option):
31     pass
32
33 # This help formatter does text wrapping and preserves newlines
34
35
36 class PlainHelpFormatter(optparse.IndentedHelpFormatter):
37     def format_description(self, description=""):
38         desc_width = self.width - self.current_indent
39         indent = " " * self.current_indent
40         paragraphs = description.split('\n')
41         wrapped_paragraphs = [
42             textwrap.fill(p,
43                           desc_width,
44                           initial_indent=indent,
45                           subsequent_indent=indent)
46             for p in paragraphs]
47         result = "\n".join(wrapped_paragraphs) + "\n"
48         return result
49
50     def format_epilog(self, epilog):
51         if epilog:
52             return "\n" + epilog + "\n"
53         else:
54             return ""
55
56
57 class Command(object):
58     """A samba-tool command."""
59
60     def _get_short_description(self):
61         return self.__doc__.splitlines()[0].rstrip("\n")
62
63     short_description = property(_get_short_description)
64
65     def _get_full_description(self):
66         lines = self.__doc__.split("\n")
67         return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
68
69     full_description = property(_get_full_description)
70
71     def _get_name(self):
72         name = self.__class__.__name__
73         if name.startswith("cmd_"):
74             return name[4:]
75         return name
76
77     name = property(_get_name)
78
79     # synopsis must be defined in all subclasses in order to provide the
80     # command usage
81     synopsis = None
82     takes_args = []
83     takes_options = []
84     takes_optiongroups = {}
85
86     hidden = False
87
88     raw_argv = None
89     raw_args = None
90     raw_kwargs = None
91
92     def __init__(self, outf=sys.stdout, errf=sys.stderr):
93         self.outf = outf
94         self.errf = errf
95
96     def usage(self, prog, *args):
97         parser, _ = self._create_parser(prog)
98         parser.print_usage()
99
100     def show_command_error(self, e):
101         '''display a command error'''
102         if isinstance(e, CommandError):
103             (etype, evalue, etraceback) = e.exception_info
104             inner_exception = e.inner_exception
105             message = e.message
106             force_traceback = False
107         else:
108             (etype, evalue, etraceback) = sys.exc_info()
109             inner_exception = e
110             message = "uncaught exception"
111             force_traceback = True
112
113         if isinstance(inner_exception, LdbError):
114             (ldb_ecode, ldb_emsg) = inner_exception.args
115             self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
116         elif isinstance(inner_exception, AssertionError):
117             self.errf.write("ERROR(assert): %s\n" % message)
118             force_traceback = True
119         elif isinstance(inner_exception, RuntimeError):
120             self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
121         elif type(inner_exception) is Exception:
122             self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
123             force_traceback = True
124         elif inner_exception is None:
125             self.errf.write("ERROR: %s\n" % (message))
126         else:
127             self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
128             force_traceback = True
129
130         if force_traceback or samba.get_debug_level() >= 3:
131             traceback.print_tb(etraceback, file=self.errf)
132
133     def _create_parser(self, prog, epilog=None):
134         parser = optparse.OptionParser(
135             usage=self.synopsis,
136             description=self.full_description,
137             formatter=PlainHelpFormatter(),
138             prog=prog, epilog=epilog)
139         parser.add_options(self.takes_options)
140         optiongroups = {}
141         for name, optiongroup in self.takes_optiongroups.items():
142             optiongroups[name] = optiongroup(parser)
143             parser.add_option_group(optiongroups[name])
144         return parser, optiongroups
145
146     def message(self, text):
147         self.outf.write(text + "\n")
148
149     def _run(self, *argv):
150         parser, optiongroups = self._create_parser(argv[0])
151         opts, args = parser.parse_args(list(argv))
152         # Filter out options from option groups
153         args = args[1:]
154         kwargs = dict(opts.__dict__)
155         for option_group in parser.option_groups:
156             for option in option_group.option_list:
157                 if option.dest is not None:
158                     del kwargs[option.dest]
159         kwargs.update(optiongroups)
160
161         # Check for a min a max number of allowed arguments, whenever possible
162         # The suffix "?" means zero or one occurence
163         # The suffix "+" means at least one occurence
164         # The suffix "*" means zero or more occurences
165         min_args = 0
166         max_args = 0
167         undetermined_max_args = False
168         for i, arg in enumerate(self.takes_args):
169             if arg[-1] != "?" and arg[-1] != "*":
170                 min_args += 1
171             if arg[-1] == "+" or arg[-1] == "*":
172                 undetermined_max_args = True
173             else:
174                 max_args += 1
175         if (len(args) < min_args) or (not undetermined_max_args and len(args) > max_args):
176             parser.print_usage()
177             return -1
178
179         self.raw_argv = list(argv)
180         self.raw_args = args
181         self.raw_kwargs = kwargs
182
183         try:
184             return self.run(*args, **kwargs)
185         except Exception as e:
186             self.show_command_error(e)
187             return -1
188
189     def run(self):
190         """Run the command. This should be overridden by all subclasses."""
191         raise NotImplementedError(self.run)
192
193     def get_logger(self, name="", verbose=False, quiet=False, **kwargs):
194         """Get a logger object."""
195         return get_samba_logger(
196             name=name or self.name, stream=self.errf,
197             verbose=verbose, quiet=quiet,
198             **kwargs)
199
200     def apply_colour_choice(self, requested):
201         """Heuristics to work out whether the user wants colour output, from a
202         --color=yes|no|auto option. This alters the ANSI 16 bit colour
203         "constants" in the colour module to be either real colours or empty
204         strings.
205         """
206         requested = requested.lower()
207         if requested == 'no':
208             colour.switch_colour_off()
209
210         elif requested == 'yes':
211             colour.switch_colour_on()
212
213         elif requested == 'auto':
214             if (hasattr(self.outf, 'isatty') and self.outf.isatty()):
215                 colour.switch_colour_on()
216             else:
217                 colour.switch_colour_off()
218
219         else:
220             raise CommandError("Unknown --color option: %s "
221                                "please choose from yes, no, auto")
222
223
224 class SuperCommand(Command):
225     """A samba-tool command with subcommands."""
226
227     synopsis = "%prog <subcommand>"
228
229     subcommands = {}
230
231     def _run(self, myname, subcommand=None, *args):
232         if subcommand in self.subcommands:
233             return self.subcommands[subcommand]._run(
234                 "%s %s" % (myname, subcommand), *args)
235
236         if subcommand == 'help':
237             # pass the request down
238             if len(args) > 0:
239                 sub = self.subcommands.get(args[0])
240                 if isinstance(sub, SuperCommand):
241                     return sub._run("%s %s" % (myname, args[0]), 'help',
242                                     *args[1:])
243                 elif sub is not None:
244                     return sub._run("%s %s" % (myname, args[0]), '--help',
245                                     *args[1:])
246
247             subcommand = '--help'
248
249         epilog = "\nAvailable subcommands:\n"
250         subcmds = self.subcommands.keys()
251         subcmds.sort()
252         max_length = max([len(c) for c in subcmds])
253         for cmd_name in subcmds:
254             cmd = self.subcommands[cmd_name]
255             if not cmd.hidden:
256                 epilog += "  %*s  - %s\n" % (
257                     -max_length, cmd_name, cmd.short_description)
258         epilog += "For more help on a specific subcommand, please type: %s <subcommand> (-h|--help)\n" % myname
259
260         parser, optiongroups = self._create_parser(myname, epilog=epilog)
261         args_list = list(args)
262         if subcommand:
263             args_list.insert(0, subcommand)
264         opts, args = parser.parse_args(args_list)
265
266         parser.print_help()
267         return -1
268
269
270 class CommandError(Exception):
271     """An exception class for samba-tool Command errors."""
272
273     def __init__(self, message, inner_exception=None):
274         self.message = message
275         self.inner_exception = inner_exception
276         self.exception_info = sys.exc_info()
277
278     def __repr__(self):
279         return "CommandError(%s)" % self.message