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
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.
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.
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/>.
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
28 class Option(optparse.Option):
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 = [
40 initial_indent=indent,
41 subsequent_indent=indent)
43 result = "\n".join(wrapped_paragraphs) + "\n"
47 class Command(object):
48 """A samba-tool command."""
50 def _get_short_description(self):
51 return self.__doc__.splitlines()[0].rstrip("\n")
53 short_description = property(_get_short_description)
55 def _get_full_description(self):
56 lines = self.__doc__.split("\n")
57 return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
59 full_description = property(_get_full_description)
62 name = self.__class__.__name__
63 if name.startswith("cmd_"):
67 name = property(_get_name)
69 # synopsis must be defined in all subclasses in order to provide the
74 takes_optiongroups = {
75 "sambaopts": options.SambaOptions,
76 "credopts": options.CredentialsOptions,
77 "versionopts": options.VersionOptions,
80 def __init__(self, outf=sys.stdout, errf=sys.stderr):
84 def usage(self, prog, *args):
85 parser, _ = self._create_parser(prog)
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
94 force_traceback = False
96 (etype, evalue, etraceback) = sys.exc_info()
98 message = "uncaught exception"
99 force_traceback = True
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))
115 self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
116 force_traceback = True
118 if force_traceback or samba.get_debug_level() >= 3:
119 traceback.print_tb(etraceback)
121 def _create_parser(self, prog):
122 parser = optparse.OptionParser(
124 description=self.full_description,
125 formatter=PlainHelpFormatter(),
127 parser.add_options(self.takes_options)
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
134 def message(self, text):
135 self.outf.write(text+"\n")
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
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)
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
154 undetermined_max_args = False
155 for i, arg in enumerate(self.takes_args):
159 undetermined_max_args = True
162 if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
167 return self.run(*args, **kwargs)
169 self.show_command_error(e)
173 """Run the command. This should be overriden by all subclasses."""
174 raise NotImplementedError(self.run)
176 def get_logger(self, name="netcmd"):
177 """Get a logger object."""
179 logger = logging.getLogger(name)
180 logger.addHandler(logging.StreamHandler(self.outf))
184 class SuperCommand(Command):
185 """A samba-tool command with subcommands."""
187 synopsis = "%prog <subcommand>"
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)
197 self.outf.write("Available subcommands:\n")
198 subcmds = self.subcommands.keys()
200 max_length = max([len(c) for c 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)
209 raise CommandError("No such subcommand '%s'" % subcommand)
213 class CommandError(Exception):
214 """An exception class for samba-tool Command errors."""
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()