Created
March 26, 2010 10:23
-
-
Save esamattis/344746 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def expose_as(cmd_name="", *alternatives): | |
| """Decorator for exposing functions as subssh commands""" | |
| def expose_function(f): | |
| def check_args_wrapper(*function_args): | |
| """ | |
| Check that input f gets called with right amount of | |
| arguments. Makes it raise InvalidArguments instead of TypeError when | |
| it is supplied invalid amount of arguments. | |
| This is used to distinguish user error from internal app error. | |
| """ | |
| if len(function_args) != f.func_code.co_argcount: | |
| if len(function_args) < f.func_code.co_argcount: | |
| raise InvalidArguments("Too few arguments") | |
| # If last arguments does not start with *args | |
| if f.func_code.co_nlocals - f.func_code.co_argcount != 1: | |
| raise InvalidArguments("Too many arguments") | |
| # Correct arguments. Execute the original function. | |
| # This should not ever raise TypeError. | |
| return f(*function_args) | |
| # Make check_args_wrapper to look like the original function. | |
| check_args_wrapper.__name__ = f.__name__ | |
| check_args_wrapper.__doc__ = f.__doc__ | |
| check_args_wrapper.__dict__ = f.__dict__ | |
| if not cmd_name: | |
| # Use name of the function if no name is supplied | |
| name = f.__name__.replace("_", "-") | |
| else: | |
| name = cmd_name | |
| # When f is run from apploader, wrap it with arguments | |
| # checker function which | |
| active.cmds[name] = check_args_wrapper | |
| for alt_name in alternatives: | |
| active.cmds[alt_name] = check_args_wrapper | |
| # Calling code gets the real function. | |
| return f | |
| return expose_function | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment