Decorator to add an option to the optparser argument of a Cmdln
    subcommand

    To add a toplevel option, apply the decorator on the class itself. (see
    p4.py for an example)
    
    Example:
        @cmdln.option("-E", dest="environment_path")
        class MyShell(cmdln.Cmdln):
            @cmdln.option("-f", "--force", help="force removal")
            def do_remove(self, subcmd, opts, *args):
                #...

def option(*args, **kwargs):
    """Decorator to add an option to the optparser argument of a Cmdln
    subcommand

    To add a toplevel option, apply the decorator on the class itself. (see
    p4.py for an example)
    
    Example:
        @cmdln.option("-E", dest="environment_path")
        class MyShell(cmdln.Cmdln):
            @cmdln.option("-f", "--force", help="force removal")
            def do_remove(self, subcmd, opts, *args):
                #...
    """
    def decorate_sub_command(method):
        """create and add sub-command options"""
        if not hasattr(method, "optparser"):
            method.optparser = SubCmdOptionParser()
        method.optparser.add_option(*args, **kwargs)
        return method
    def decorate_class(klass):
        """store toplevel options"""
        assert _forgiving_issubclass(klass, Cmdln)
        _inherit_attr(klass, "toplevel_optparser_options", [], cp=lambda l: l[:])
        klass.toplevel_optparser_options.append( (args, kwargs) )
        return klass
        
    #XXX Is there a possible optimization for many options to not have a
    #    large stack depth here?
    def decorate(obj):
        if _forgiving_issubclass(obj, Cmdln):
            return decorate_class(obj)
        else:
            return decorate_sub_command(obj)
    return decorate