Commit 0ad54e31 authored by Lucas Bourneuf's avatar Lucas Bourneuf
Browse files

export slowly starts toward a working poc

parent 20894dbb
......@@ -45,28 +45,59 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
verbosity -- verbosity of the standalone program itself.
"""
option_names = {(idx, name): final_name for idx, (_, name, final_name) in enumerate(option_names_from_options(scripts), 1)}
option_names = {(idx, name): final_name for idx, (_, name, final_name) in enumerate(option_names_from_options(scripts))}
print('OPTIONS NAMES:', option_names)
print('RECOGNIZED OPTIONS:', options)
options_used = tuple(
(idx, final_name) for idx, final_name in option_names.items()
((idx, name), final_name) for (idx, name), final_name in option_names.items()
if options.get(final_name)
)
print('OPTIONS USED:', options_used)
yield '"""Standalone script generated by biseau ' + str(__version__) + ', ' + str(datetime.datetime.now()) + '"""\n'
yield 'import os'
yield 'import argparse'
yield 'import clitogui'
yield 'from clitogui import clitogui'
yield 'import clyngor'
yield ''
if options:
yield '@clitogui'
if options_used:
yield '@clitogui.clitogui'
yield 'def cli():'
yield ' parser = argparse.ArgumentParser()'
yield ' def existing_file(filepath:str) -> str:'
yield ' """Argparse type, raising an error if given file does not exists"""'
yield ' if not os.path.exists(filepath):'
yield ' raise argparse.ArgumentTypeError("file {} doesn\'t exists".format(filepath))'
yield ' return filepath'
yield ' def writable_file(filepath:str) -> str:'
yield ' """Argparse type, raising an error if given file is not writable.'
yield ' Will delete the file !"""'
yield ' try:'
yield ' with open(filepath, "w") as fd:'
yield ' pass'
yield ' os.remove(filepath)'
yield ' return filepath'
yield ' except (PermissionError, IOError):'
yield ' raise argparse.ArgumentTypeError("file {} is not writable.".format(filepath))'
yield ' parser = argparse.ArgumentParser(description=__doc__)'
yield ' def elem_in_list(elements:iter):'
yield ' def valid_element(element:str) -> str:'
yield ' """Argparse type, raising an error if given value is not expected"""'
yield ' if element not in elements:'
yield ' raise argparse.ArgumentTypeError(f"Value {element} is unexpected. Valid inputs: " + ", ".join(map(str, elements)))'
yield ' return element'
yield ' return valid_element'
for (idx, name), final_name in options_used:
option = scripts[idx-1].options
option = scripts[idx].options[name]
print(option)
yield f' parser.addArgument({final_name})'
yield ' ...'
def as_dict(opts):
return {name: vals for name, *vals in opts}
option = as_dict(scripts[idx].options)[final_name]
func, args = argparse_addarg_args_from_option(final_name, option)
yield f' parser.{func}({", ".join(args)})'
print('MAKE ARG:', f' parser.{func}({", ".join(args)})')
yield ' return parser'
yield ''
else:
yield 'def cli():'
yield ' parser = argparse.ArgumentParser(description=__doc__)'
yield ' return parser'
# add a run_on function for each script
runons = []
for script in scripts:
......@@ -82,21 +113,24 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
elif script.language == 'asp':
yield ' context += """\\n' + script.source_code + '"""'
elif script.language == 'asp file':
yield ' with open({script.source_code}) as fd:'
yield ' context += "\\n" + fd.read().strip()'
yield f' def run_on(context):'
yield f' with open("{script.source_code}") as fd:'
yield ' return context + "\\n" + fd.read().strip()'
else:
raise ValueError(f"unhandled export of language '{script.language}'")
runon_args = ', '.join(f"{name}={name}" for name, *_ in script.options)
yield f' return \'\'.join(run_on(context, {runon_args}))'
yield 'def run_on(context:str, ' '):'
yield 'def run_on(context:str, args):'
for runon, script in runons:
args = ', '.join(f"{name}=args.{name}" for name, *_ in script.options)
target_idx = scripts.index(script)
options = ((name, final_name) for (idx, name), final_name in options_used if idx == target_idx)
args = ', '.join(f"{name}=args.{final_name}" for name, final_name in options)
yield f' context = {runon}(context, {args})'
yield ' print(context)'
yield 'if __name__ == "__main__":'
yield ' args = cli()'
yield ' args = cli().parse_args()'
yield ' context = ' + repr(default_context)
yield ' run_on(context)'
yield ' run_on(context, args)'
def option_names_from_options(scripts:[Script]) -> [(str, str, str)]:
......@@ -129,3 +163,21 @@ def option_names_from_options(scripts:[Script]) -> [(str, str, str)]:
if name in conflicting_names:
final_name = f'{script_name}_{name}'
yield script_name, name, final_name
def argparse_addarg_args_from_option(name:str, option) -> [str]:
print('creating argparse arguments:', name, option)
argtype, default, description = option
if argtype is open:
ctype = 'existing_file'
elif isinstance(argtype, tuple) and len(argtype) == 2 and argtype[0] is open:
mode = argtype[1]
if mode == 'r':
ctype = 'existing_file'
elif mode == 'w':
ctype = 'writable_file'
elif isinstance(argtype, (list, tuple)):
ctype = 'elem_in_list((' + ', '.join(map(repr, argtype)) + '))'
elif isinstance(argtype, str):
ctype = 'str'
return 'add_argument', (f"'{name}'", f'type={ctype}', f'default={repr(default)}', f'help="{description}"')
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment