# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/01c_utils.script.ipynb.

# %% auto 0
__all__ = ['call_parse', 'test_script']

# %% ../../nbs/01c_utils.script.ipynb 2
from fastcore.all import *
import inspect

# %% ../../nbs/01c_utils.script.ipynb 3
def call_parse(func=None, nested=False):
    """Decorator to create a simple CLI from `func` using `anno_parser`
    Copied from: https://github.com/fastai/fastcore/blob/master/fastcore/script.py with a single change (marked by comment)
    """
    if func is None: return partial(call_parse, nested=nested)

    @functools.wraps(func)
    def _f(*args, **kwargs):
        mod = inspect.getmodule(inspect.currentframe().f_back)
        if not mod: return func(*args, **kwargs)
        if not SCRIPT_INFO.func and mod.__name__=="__main__": SCRIPT_INFO.func = func.__name__
        if len(sys.argv)>1 and sys.argv[1]=='': sys.argv.pop(1)
        p = anno_parser(func)
        if nested: args, sys.argv[1:] = p.parse_known_args()
        else: args = p.parse_args()
        args = args.__dict__
        xtra = otherwise(args.pop('xtra', ''), eq(1), p.prog)
        tfunc = trace(func) if args.pop('pdb', False) else func
        # CHANGED: Uses `print` instead of `return`, so output can be piped in terminal commands
        print(tfunc(**merge(args, args_from_prog(func, xtra)))) 

    mod = inspect.getmodule(inspect.currentframe().f_back)
    if getattr(mod, '__name__', '') =="__main__":
        setattr(mod, func.__name__, _f)
        SCRIPT_INFO.func = func.__name__
        return _f()
        
    else: return _f

# %% ../../nbs/01c_utils.script.ipynb 4
@call_parse
def test_script(msg:Param("The message", str),
                upper:Param("Convert to uppercase?", store_true)=False):
    "Print `msg`, optionally converting to uppercase"
    return msg.upper() if upper else msg
