#!/usr/bin/env python
#******************************************************************************\
#* Copyright (c) 2003-2004, Martin Blais
#* All rights reserved.
#* 
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions are
#* met:
#* 
#* * Redistributions of source code must retain the above copyright
#*   notice, this list of conditions and the following disclaimer.
#* 
#* * Redistributions in binary form must reproduce the above copyright
#*   notice, this list of conditions and the following disclaimer in the
#*   documentation and/or other materials provided with the distribution.
#* 
#* * Neither the name of the Martin Blais, Furius, nor the names of its
#*   contributors may be used to endorse or promote products derived from
#*   this software without specific prior written permission.
#* 
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#******************************************************************************\

"""optparse-commands [<global-opts>] command [<cmd-opts>] [<cmd-args> ...]

Example for implementing programs with command-line interfaces with many
commands, with separate global options and command options.

This script is my template when I create new scripts like that require this
interface.  All of the mechanics are implemented using the standard optparse
module that comes with Python >=2.3.

"""

__moredoc__ = """
Each command consists of a class, which has the following properties:

- Must have a class member 'names' which is a list of the names for the command;

- Can optionally have a addopts(self, parser) method which adds options to the
  given parser. This defines command options.
"""

__version__ = "$Revision: 1.7 $"
__author__ = "Martin Blais <blais@furius.ca>"
__depends__ = ['Python-2.3']

#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================

import sys, os
from os.path import *
import re
from pprint import pprint, pformat

#===============================================================================
# LOCAL DECLARATIONS
#===============================================================================

#===============================================================================
# CLASS CmdSimplest
#===============================================================================

class CmdSimplest:

    """Description of simplest command."""

    names = ['simplest']

    def execute( self, args ):
        print 'Doing something simple.'


#===============================================================================
# CLASS CmdFoo
#===============================================================================

class CmdFoo:

    """Foo command description."""

    names = ['foo', 'goo']

    def addopts( self, parser ):
        parser.add_option('-l', '--local', action='store_true',
                          help="Some local option.")

    def execute( self, args ):
        print 'Executing CmdFoo'
        pprint(args)
        pprint(self.gopts)
        pprint(self.opts)

#===============================================================================
# CLASS CmdBar
#===============================================================================

class CmdBar(CmdFoo):

    """Bar command description, derived from foo."""

    names = ['bar', 'gore']

    def addopts( self, parser ):
        CmdFoo.addopts(self, parser)
        parser.add_option('-L', '--local-other', action='store_true',
                          help="Some other local option.")

    def execute( self, args ):
        print 'Executing CmdBar'
        pprint(args)
        pprint(self.gopts)
        pprint(self.opts)

#===============================================================================
# CLASS CmdHelp
#===============================================================================

class CmdHelp:

    """Help as a command. This is not really necessary."""

    names =['help', 'man']

    def execute( self, args ):
        import optparse
        if args:
            cmdname = args[0]
            try:
                sc = subcmds_map[cmdname]
                lparser = optparse.OptionParser(sc.__doc__.strip())
                if hasattr(sc, 'addopts'):
                    sc.addopts(lparser)
                lparser.print_help()
            except KeyError:
                raise SystemExit("Error: invalid command '%s'" % cmdname)
        else:
            gparser.parse_args(['--help'])

#-------------------------------------------------------------------------------
#
def parse_subcommands( gparser, subcmds ):

    """Parse given global arguments, find subcommand from given list of
    subcommand objects, parse local arguments and return a tuple of global
    options, selected command object, command options, and command arguments.
    Call execute() on the command object to run. The command object has members
    'gopts' and 'opts' set for global and command options respectively, you
    don't need to call execute with those but you could if you wanted to."""

    import optparse
    global subcmds_map # needed for help command only.

    # Build map of name -> command and docstring.
    subcmds_map = {}
    gparser.usage += '\n\nAvailable Subcommands\n\n'
    for sc in subcmds:
        gparser.usage += '- %s: %s\n' % (', '.join(sc.names),
                                       sc.__doc__.splitlines()[0])
        for n in sc.names:
            assert n not in subcmds_map
            subcmds_map[n] = sc

    # Declare and parse global options.
    gparser.disable_interspersed_args()

    gopts, args = gparser.parse_args()
    if not args:
        gparser.print_help()
        raise SystemExit("Error: you must specify a command to use.")
    subcmdname, subargs = args[0], args[1:]

    # Parse command arguments and invoke command.
    try:
        sc = subcmds_map[subcmdname]
        lparser = optparse.OptionParser(sc.__doc__.strip())
        if hasattr(sc, 'addopts'):
            sc.addopts(lparser)
        sc.gopts = gopts
        sc.opts, subsubargs = lparser.parse_args(subargs)
    except KeyError:
        raise SystemExit("Error: invalid command '%s'" % subcmdname)

    return sc.gopts, sc, sc.opts, subsubargs

#===============================================================================
# MAIN
#===============================================================================

def main():

    # Create global options parser.
    global gparser # only need for 'help' command (optional)
    import optparse
    gparser = optparse.OptionParser(__doc__.strip(), version=__version__)
    gparser.add_option('-v', '--verbose', action='store_true',
                      help="Verbose mode.")
    gparser.add_option('-g', '--global', action='store_true',
                      help="Some global option.")

    # Declare subcommands.
    subcmds = [
        CmdSimplest(),
        CmdFoo(),
        CmdBar(),
        CmdHelp(),
    ]

    gopts, sc, opts, args = parse_subcommands(gparser, subcmds)
    sc.execute(args)


#===============================================================================
# TEST
#===============================================================================

def test():
    tests = [
        '',
        '--help',
        'help',
        'help foo',
        'help goo',
        'foo',
        'goo',
        'foo --help',
        'bar',
        'bar --help',
        'bar arg1 arg2',
        'bar arg1 --local arg2',
        ]
    print '#!/bin/sh'
    for s in tests:
        cmd = '%s %s' % (sys.argv[0], s)
        print 'clear ; ( echo "%s" ; %s 2>&1 ) | /usr/bin/less' % (cmd, cmd)

# Run as main, otherwise run tests.
if os.environ.has_key('optparse_commands_test'):
    test()
elif __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print "Interrupted, exiting."
