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/>.
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
30 class Option(optparse.Option):
33 # This help formatter does text wrapping and preserves newlines
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 = [
44 initial_indent=indent,
45 subsequent_indent=indent)
47 result = "\n".join(wrapped_paragraphs) + "\n"
50 def format_epilog(self, epilog):
52 return "\n" + epilog + "\n"
57 class Command(object):
58 """A samba-tool command."""
60 def _get_short_description(self):
61 return self.__doc__.splitlines()[0].rstrip("\n")
63 short_description = property(_get_short_description)
65 def _get_full_description(self):
66 lines = self.__doc__.split("\n")
67 return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
69 full_description = property(_get_full_description)
72 name = self.__class__.__name__
73 if name.startswith("cmd_"):
77 name = property(_get_name)
79 # synopsis must be defined in all subclasses in order to provide the
84 takes_optiongroups = {}
92 def __init__(self, outf=sys.stdout, errf=sys.stderr):
96 def usage(self, prog, *args):
97 parser, _ = self._create_parser(prog)
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
106 force_traceback = False
108 (etype, evalue, etraceback) = sys.exc_info()
110 message = "uncaught exception"
111 force_traceback = True
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))
127 self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
128 force_traceback = True
130 if force_traceback or samba.get_debug_level() >= 3:
131 traceback.print_tb(etraceback, file=self.errf)
133 def _create_parser(self, prog, epilog=None):
134 parser = optparse.OptionParser(
136 description=self.full_description,
137 formatter=PlainHelpFormatter(),
138 prog=prog, epilog=epilog)
139 parser.add_options(self.takes_options)
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
146 def message(self, text):
147 self.outf.write(text + "\n")
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
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)
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
167 undetermined_max_args = False
168 for i, arg in enumerate(self.takes_args):
169 if arg[-1] != "?" and arg[-1] != "*":
171 if arg[-1] == "+" or arg[-1] == "*":
172 undetermined_max_args = True
175 if (len(args) < min_args) or (not undetermined_max_args and len(args) > max_args):
179 self.raw_argv = list(argv)
181 self.raw_kwargs = kwargs
184 return self.run(*args, **kwargs)
185 except Exception as e:
186 self.show_command_error(e)
190 """Run the command. This should be overridden by all subclasses."""
191 raise NotImplementedError(self.run)
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,
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
206 requested = requested.lower()
207 if requested == 'no':
208 colour.switch_colour_off()
210 elif requested == 'yes':
211 colour.switch_colour_on()
213 elif requested == 'auto':
214 if (hasattr(self.outf, 'isatty') and self.outf.isatty()):
215 colour.switch_colour_on()
217 colour.switch_colour_off()
220 raise CommandError("Unknown --color option: %s "
221 "please choose from yes, no, auto")
224 class SuperCommand(Command):
225 """A samba-tool command with subcommands."""
227 synopsis = "%prog <subcommand>"
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)
236 if subcommand == 'help':
237 # pass the request down
239 sub = self.subcommands.get(args[0])
240 if isinstance(sub, SuperCommand):
241 return sub._run("%s %s" % (myname, args[0]), 'help',
243 elif sub is not None:
244 return sub._run("%s %s" % (myname, args[0]), '--help',
247 subcommand = '--help'
249 epilog = "\nAvailable subcommands:\n"
250 subcmds = self.subcommands.keys()
252 max_length = max([len(c) for c in subcmds])
253 for cmd_name in subcmds:
254 cmd = self.subcommands[cmd_name]
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
260 parser, optiongroups = self._create_parser(myname, epilog=epilog)
261 args_list = list(args)
263 args_list.insert(0, subcommand)
264 opts, args = parser.parse_args(args_list)
270 class CommandError(Exception):
271 """An exception class for samba-tool Command errors."""
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()
279 return "CommandError(%s)" % self.message