samba-tool: Display Usage line and list commands alphabetically
[ira/wip.git] / source4 / scripting / python / samba / netcmd / __init__.py
1 #!/usr/bin/env python
2
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
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
25 import sys, traceback
26
27
28 class Option(optparse.Option):
29     pass
30
31
32
33 class Command(object):
34     """A samba-tool command."""
35
36     def _get_description(self):
37         return self.__doc__.splitlines()[0].rstrip("\n")
38
39     def _get_name(self):
40         name = self.__class__.__name__
41         if name.startswith("cmd_"):
42             return name[4:]
43         return name
44
45     name = property(_get_name)
46
47     def usage(self, *args):
48         parser, _ = self._create_parser()
49         parser.print_usage()
50
51     description = property(_get_description)
52
53     def show_command_error(self, e):
54         '''display a command error'''
55         if isinstance(e, CommandError):
56             (etype, evalue, etraceback) = e.exception_info
57             inner_exception = e.inner_exception
58             message = e.message
59             force_traceback = False
60         else:
61             (etype, evalue, etraceback) = sys.exc_info()
62             inner_exception = e
63             message = "uncaught exception"
64             force_traceback = True
65
66         if isinstance(inner_exception, LdbError):
67             (ldb_ecode, ldb_emsg) = inner_exception
68             print >>sys.stderr, "ERROR(ldb): %s - %s" % (message, ldb_emsg)
69         elif isinstance(inner_exception, AssertionError):
70             print >>sys.stderr, "ERROR(assert): %s" % message
71             force_traceback = True
72         elif isinstance(inner_exception, RuntimeError):
73             print >>sys.stderr, "ERROR(runtime): %s - %s" % (message, evalue)
74         elif type(inner_exception) is Exception:
75             print >>sys.stderr, "ERROR(exception): %s - %s" % (message, evalue)
76             force_traceback = True
77         elif inner_exception is None:
78             print >>sys.stderr, "ERROR: %s" % (message)
79         else:
80             print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
81             force_traceback = True
82
83         if force_traceback or samba.get_debug_level() >= 3:
84             traceback.print_tb(etraceback)
85         sys.exit(1)
86
87     outf = sys.stdout
88
89     # synopsis must be defined in all subclasses in order to provide the command usage
90     synopsis = ""
91     takes_args = []
92     takes_options = []
93     takes_optiongroups = {
94         "sambaopts": options.SambaOptions,
95         "credopts": options.CredentialsOptions,
96         "versionopts": options.VersionOptions,
97         }
98
99     def _create_parser(self):
100         parser = optparse.OptionParser(self.synopsis)
101         parser.add_options(self.takes_options)
102         optiongroups = {}
103         for name, optiongroup in self.takes_optiongroups.iteritems():
104             optiongroups[name] = optiongroup(parser)
105             parser.add_option_group(optiongroups[name])
106         return parser, optiongroups
107
108     def message(self, text):
109         print text
110
111     def _run(self, *argv):
112         parser, optiongroups = self._create_parser()
113         opts, args = parser.parse_args(list(argv))
114         # Filter out options from option groups
115         args = args[1:]
116         kwargs = dict(opts.__dict__)
117         for option_group in parser.option_groups:
118             for option in option_group.option_list:
119                 if option.dest is not None:
120                     del kwargs[option.dest]
121         kwargs.update(optiongroups)
122
123         # Check for a min a max number of allowed arguments, whenever possible
124         # The suffix "?" means zero or one occurence
125         # The suffix "+" means at least one occurence
126         min_args = 0
127         max_args = 0
128         undetermined_max_args = False
129         for i, arg in enumerate(self.takes_args):
130             if arg[-1] != "?":
131                min_args += 1
132             if arg[-1] == "+":
133                undetermined_max_args = True
134             else:
135                max_args += 1
136         if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
137             parser.print_usage()
138             return -1
139
140         try:
141             return self.run(*args, **kwargs)
142         except Exception, e:
143             self.show_command_error(e)
144             return -1
145
146     def run(self):
147         """Run the command. This should be overriden by all subclasses."""
148         raise NotImplementedError(self.run)
149
150
151
152 class SuperCommand(Command):
153     """A samba-tool command with subcommands."""
154
155     subcommands = {}
156
157     def _run(self, myname, subcommand=None, *args):
158         if subcommand in self.subcommands:
159             return self.subcommands[subcommand]._run(subcommand, *args)
160         print "Usage: samba-tool %s <subcommand> [options]" % myname
161         print "Available subcommands:"
162         subcmds = self.subcommands.keys()
163         subcmds.sort()
164         for cmd in subcmds:
165             print "    %-20s - %s" % (cmd, self.subcommands[cmd].description)
166         if subcommand in [None]:
167             self.show_command_error("You must specify a subcommand")
168             return -1
169         if subcommand in ['-h', '--help']:
170             print "For more help on a specific subcommand, please type: samba-tool %s <subcommand> (-h|--help)" % myname
171             return 0
172         self.show_command_error("No such subcommand '%s'" % (subcommand))
173
174     def show_command_error(self, msg):
175         '''display a command error'''
176
177         print >>sys.stderr, "ERROR: %s" % (msg)
178         sys.exit(1)
179
180     def usage(self, myname, subcommand=None, *args):
181         if subcommand is None or not subcommand in self.subcommands:
182             print "Usage: samba-tool %s (%s) [options]" % (myname,
183                 " | ".join(self.subcommands.keys()))
184         else:
185             return self.subcommands[subcommand].usage(*args)
186
187
188
189 class CommandError(Exception):
190     '''an exception class for samba-tool cmd errors'''
191     def __init__(self, message, inner_exception=None):
192         self.message = message
193         self.inner_exception = inner_exception
194         self.exception_info = sys.exc_info()
195
196
197
198 commands = {}
199 from samba.netcmd.netacl import cmd_acl
200 commands["acl"] = cmd_acl()
201 from samba.netcmd.fsmo import cmd_fsmo
202 commands["fsmo"] = cmd_fsmo()
203 from samba.netcmd.time import cmd_time
204 commands["time"] = cmd_time()
205 from samba.netcmd.user import cmd_user
206 commands["user"] = cmd_user()
207 from samba.netcmd.vampire import cmd_vampire
208 commands["vampire"] = cmd_vampire()
209 from samba.netcmd.spn import cmd_spn
210 commands["spn"] = cmd_spn()
211 from samba.netcmd.group import cmd_group
212 commands["group"] = cmd_group()
213 from samba.netcmd.rodc import cmd_rodc
214 commands["rodc"] = cmd_rodc()
215 from samba.netcmd.drs import cmd_drs
216 commands["drs"] = cmd_drs()
217 from samba.netcmd.gpo import cmd_gpo
218 commands["gpo2"] = cmd_gpo()
219 from samba.netcmd.ldapcmp import cmd_ldapcmp
220 commands["ldapcmp"] = cmd_ldapcmp()
221 from samba.netcmd.testparm import cmd_testparm
222 commands["testparm"] =  cmd_testparm()
223 from samba.netcmd.dbcheck import cmd_dbcheck
224 commands["dbcheck"] =  cmd_dbcheck()
225 from samba.netcmd.delegation import cmd_delegation
226 commands["delegation"] = cmd_delegation()
227 from samba.netcmd.domain import cmd_domain
228 commands["domain"] = cmd_domain()