3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009
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
):
33 class Command(object):
34 """A samba-tool command."""
36 def _get_description(self
):
37 return self
.__doc
__.splitlines()[0].rstrip("\n")
39 description
= property(_get_description
)
41 # synopsis must be defined in all subclasses in order to provide the command usage
42 synopsis
= "Please provide synopsis for this command."
43 # long_description is a string describing the command in details
47 takes_optiongroups
= {
48 "sambaopts": options
.SambaOptions
,
49 "credopts": options
.CredentialsOptions
,
50 "versionopts": options
.VersionOptions
,
52 # This epilog will print at the end when the user invokes the command w/ -h or --help
56 def usage(self
, *args
):
57 parser
, _
= self
._create
_parser
()
60 def show_command_error(self
, e
):
61 '''display a command error'''
62 if isinstance(e
, CommandError
):
63 (etype
, evalue
, etraceback
) = e
.exception_info
64 inner_exception
= e
.inner_exception
66 force_traceback
= False
68 (etype
, evalue
, etraceback
) = sys
.exc_info()
70 message
= "uncaught exception"
71 force_traceback
= True
73 if isinstance(inner_exception
, LdbError
):
74 (ldb_ecode
, ldb_emsg
) = inner_exception
75 print >>sys
.stderr
, "ERROR(ldb): %s - %s" % (message
, ldb_emsg
)
76 elif isinstance(inner_exception
, AssertionError):
77 print >>sys
.stderr
, "ERROR(assert): %s" % message
78 force_traceback
= True
79 elif isinstance(inner_exception
, RuntimeError):
80 print >>sys
.stderr
, "ERROR(runtime): %s - %s" % (message
, evalue
)
81 elif type(inner_exception
) is Exception:
82 print >>sys
.stderr
, "ERROR(exception): %s - %s" % (message
, evalue
)
83 force_traceback
= True
84 elif inner_exception
is None:
85 print >>sys
.stderr
, "ERROR: %s" % (message
)
87 print >>sys
.stderr
, "ERROR(%s): %s - %s" % (str(etype
), message
, evalue
)
88 force_traceback
= True
90 if force_traceback
or samba
.get_debug_level() >= 3:
91 traceback
.print_tb(etraceback
)
94 def _create_parser(self
):
95 parser
= optparse
.OptionParser(usage
=self
.synopsis
, epilog
=self
.epilog
,
96 description
=self
.long_description
)
97 parser
.add_options(self
.takes_options
)
99 for name
, optiongroup
in self
.takes_optiongroups
.iteritems():
100 optiongroups
[name
] = optiongroup(parser
)
101 parser
.add_option_group(optiongroups
[name
])
102 return parser
, optiongroups
104 def message(self
, text
):
107 def _run(self
, *argv
):
108 parser
, optiongroups
= self
._create
_parser
()
109 opts
, args
= parser
.parse_args(list(argv
))
110 # Filter out options from option groups
112 kwargs
= dict(opts
.__dict
__)
113 for option_group
in parser
.option_groups
:
114 for option
in option_group
.option_list
:
115 if option
.dest
is not None:
116 del kwargs
[option
.dest
]
117 kwargs
.update(optiongroups
)
119 # Check for a min a max number of allowed arguments, whenever possible
120 # The suffix "?" means zero or one occurence
121 # The suffix "+" means at least one occurence
124 undetermined_max_args
= False
125 for i
, arg
in enumerate(self
.takes_args
):
129 undetermined_max_args
= True
132 if (len(args
) < min_args
) or (undetermined_max_args
== False and len(args
) > max_args
):
137 return self
.run(*args
, **kwargs
)
139 self
.show_command_error(e
)
143 """Run the command. This should be overriden by all subclasses."""
144 raise NotImplementedError(self
.run
)
148 class SuperCommand(Command
):
149 """A samba-tool command with subcommands."""
153 def _run(self
, myname
, subcommand
=None, *args
):
154 if subcommand
in self
.subcommands
:
155 return self
.subcommands
[subcommand
]._run
(subcommand
, *args
)
157 if (myname
== "samba-tool"):
158 usage
= "samba-tool <subcommand>"
160 usage
= "samba-tool %s <subcommand>" % myname
161 print "Usage: %s [options]" %usage
162 print "Available subcommands:"
163 subcmds
= self
.subcommands
.keys()
165 max_length
= max(map(lambda c
: len(c
), subcmds
))
167 print " %*s - %s" % (-max_length
, cmd
, self
.subcommands
[cmd
].description
)
168 print " * server connection needed"
169 if subcommand
in [None]:
170 raise CommandError("You must specify a subcommand")
171 if subcommand
in ['help', '-h', '--help']:
172 print "For more help on a specific subcommand, please type: %s (-h|--help)" % usage
174 raise CommandError("No such subcommand '%s'" % subcommand
)
178 class CommandError(Exception):
179 '''an exception class for samba-tool cmd errors'''
180 def __init__(self
, message
, inner_exception
=None):
181 self
.message
= message
182 self
.inner_exception
= inner_exception
183 self
.exception_info
= sys
.exc_info()