| 1 |
# Copyright 2014-2015 Nathan West |
| 2 |
# |
| 3 |
# This file is part of autocommand. |
| 4 |
# |
| 5 |
# autocommand is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU Lesser General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# autocommand is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU Lesser General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU Lesser General Public License |
| 16 |
# along with autocommand. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
from .autoparse import autoparse |
| 19 |
from .automain import automain |
| 20 |
try: |
| 21 |
from .autoasync import autoasync |
| 22 |
except ImportError: # pragma: no cover |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
def autocommand( |
| 27 |
module, *, |
| 28 |
description=None, |
| 29 |
epilog=None, |
| 30 |
add_nos=False, |
| 31 |
parser=None, |
| 32 |
loop=None, |
| 33 |
forever=False, |
| 34 |
pass_loop=False): |
| 35 |
|
| 36 |
if callable(module): |
| 37 |
raise TypeError('autocommand requires a module name argument') |
| 38 |
|
| 39 |
def autocommand_decorator(func): |
| 40 |
# Step 1: if requested, run it all in an asyncio event loop. autoasync |
| 41 |
# patches the __signature__ of the decorated function, so that in the |
| 42 |
# event that pass_loop is True, the `loop` parameter of the original |
| 43 |
# function will *not* be interpreted as a command-line argument by |
| 44 |
# autoparse |
| 45 |
if loop is not None or forever or pass_loop: |
| 46 |
func = autoasync( |
| 47 |
func, |
| 48 |
loop=None if loop is True else loop, |
| 49 |
pass_loop=pass_loop, |
| 50 |
forever=forever) |
| 51 |
|
| 52 |
# Step 2: create parser. We do this second so that the arguments are |
| 53 |
# parsed and passed *before* entering the asyncio event loop, if it |
| 54 |
# exists. This simplifies the stack trace and ensures errors are |
| 55 |
# reported earlier. It also ensures that errors raised during parsing & |
| 56 |
# passing are still raised if `forever` is True. |
| 57 |
func = autoparse( |
| 58 |
func, |
| 59 |
description=description, |
| 60 |
epilog=epilog, |
| 61 |
add_nos=add_nos, |
| 62 |
parser=parser) |
| 63 |
|
| 64 |
# Step 3: call the function automatically if __name__ == '__main__' (or |
| 65 |
# if True was provided) |
| 66 |
func = automain(module)(func) |
| 67 |
|
| 68 |
return func |
| 69 |
|
| 70 |
return autocommand_decorator |