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/>.
19 import optparse
, samba
20 from samba
import getopt
as options
21 from ldb
import LdbError
25 class Option(optparse
.Option
):
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
= [
37 initial_indent
=indent
,
38 subsequent_indent
=indent
)
40 result
= "\n".join(wrapped_paragraphs
) + "\n"
43 def format_epilog(self
, epilog
):
45 return "\n" + epilog
+ "\n"
49 class Command(object):
50 """A samba-tool command."""
52 def _get_short_description(self
):
53 return self
.__doc
__.splitlines()[0].rstrip("\n")
55 short_description
= property(_get_short_description
)
57 def _get_full_description(self
):
58 lines
= self
.__doc
__.split("\n")
59 return lines
[0] + "\n" + textwrap
.dedent("\n".join(lines
[1:]))
61 full_description
= property(_get_full_description
)
64 name
= self
.__class
__.__name
__
65 if name
.startswith("cmd_"):
69 name
= property(_get_name
)
71 # synopsis must be defined in all subclasses in order to provide the
76 takes_optiongroups
= {}
84 def __init__(self
, outf
=sys
.stdout
, errf
=sys
.stderr
):
88 def usage(self
, prog
, *args
):
89 parser
, _
= self
._create
_parser
(prog
)
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
98 force_traceback
= False
100 (etype
, evalue
, etraceback
) = sys
.exc_info()
102 message
= "uncaught exception"
103 force_traceback
= True
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
))
119 self
.errf
.write("ERROR(%s): %s - %s\n" % (str(etype
), message
, evalue
))
120 force_traceback
= True
122 if force_traceback
or samba
.get_debug_level() >= 3:
123 traceback
.print_tb(etraceback
)
125 def _create_parser(self
, prog
, epilog
=None):
126 parser
= optparse
.OptionParser(
128 description
=self
.full_description
,
129 formatter
=PlainHelpFormatter(),
130 prog
=prog
,epilog
=epilog
)
131 parser
.add_options(self
.takes_options
)
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
138 def message(self
, text
):
139 self
.outf
.write(text
+"\n")
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
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
)
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
158 undetermined_max_args
= False
159 for i
, arg
in enumerate(self
.takes_args
):
163 undetermined_max_args
= True
166 if (len(args
) < min_args
) or (not undetermined_max_args
and len(args
) > max_args
):
170 self
.raw_argv
= list(argv
)
172 self
.raw_kwargs
= kwargs
175 return self
.run(*args
, **kwargs
)
177 self
.show_command_error(e
)
181 """Run the command. This should be overriden by all subclasses."""
182 raise NotImplementedError(self
.run
)
184 def get_logger(self
, name
="netcmd"):
185 """Get a logger object."""
187 logger
= logging
.getLogger(name
)
188 logger
.addHandler(logging
.StreamHandler(self
.errf
))
192 class SuperCommand(Command
):
193 """A samba-tool command with subcommands."""
195 synopsis
= "%prog <subcommand>"
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
)
204 epilog
= "\nAvailable subcommands:\n"
205 subcmds
= self
.subcommands
.keys()
207 max_length
= max([len(c
) for c
in subcmds
])
208 for cmd_name
in subcmds
:
209 cmd
= self
.subcommands
[cmd_name
]
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
215 parser
, optiongroups
= self
._create
_parser
(myname
, epilog
=epilog
)
216 args_list
= list(args
)
218 args_list
.insert(0, subcommand
)
219 opts
, args
= parser
.parse_args(args_list
)
225 class CommandError(Exception):
226 """An exception class for samba-tool Command errors."""
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()