Commit 399af07b authored by Aluriak's avatar Aluriak

Merge branch 'master' of gitlab.inria.fr:lbourneu/biseau

parents a11e6be6 c7e2cd61
......@@ -57,6 +57,11 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
)
def options_as_dict(opts):
return {name: vals for name, *vals in opts}
options_def = { # final_name: type
final_name: options_as_dict(scripts[idx].options)[name]
for (idx, name), final_name in option_names.items()
if options.get(final_name)
}
# print('OPTIONS USED:', options_used)
yield f'"""{name}'
......@@ -64,12 +69,19 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
yield '\n"""\n'
yield 'import os'
yield 'import argparse'
if metarg_withgui: yield 'from clitogui import clitogui'
if metarg_withgui: yield 'import clitogui'
yield 'import clyngor'
yield 'import biseau'
yield ''
if metarg_withgui:
args = ', '.join(f"{final_name}=args.{final_name}"
for (idx, name), final_name in options_used)
yield 'def run_program_from_args(args):'
yield f' context = run_on("", {args})'
yield f' image = biseau.compile_to_single_image(context, return_image=True, outfile={repr(metarg_outfile)}, dotfile={repr(metarg_dotfile)}, dot_prog={repr(metarg_dot_prog)}, verbosity={repr(verbosity)})'
yield ' return image'
if options_used:
if metarg_withgui: yield '@clitogui.clitogui'
if metarg_withgui: yield '@clitogui.interactive(run_program_from_args, autorun=True, tabulate=True)'
yield 'def cli():'
yield ' def existing_file(filepath:str) -> str:'
yield ' """Argparse type, raising an error if given file does not exists"""'
......@@ -87,22 +99,16 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
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'
yield f" parser.add_argument('--version', action='version', version=f'{name}')"
for (idx, name), final_name in options_used:
option = options_as_dict(scripts[idx].options)[final_name]
option = options_def[final_name]
func, args = argparse_addarg_args_from_option(final_name, option, explicit_value=scripts[idx].options_values.get(name))
yield f' parser.{func}({", ".join(args)})'
# print('MAKE ARG:', f' parser.{func}({", ".join(args)})')
yield ' return parser'
yield ''
else:
if metarg_withgui: yield '@clitogui.clitogui'
if metarg_withgui: yield '@clitogui.interactive(run_program_from_args)'
yield 'def cli():'
yield ' parser = argparse.ArgumentParser(description=__doc__)'
yield ' return parser'
......@@ -113,7 +119,7 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
runon_name = f"run_on_{bs.utils.name_to_identifier(script.name)}"
runons.append((runon_name, script))
for runon_name, script in runons:
params = ', '.join(f"{name}:{valtype.__name__ if type(valtype) in {type(open), type(bool)} else str(valtype)}={repr(default)}" for name, valtype, default, _ in script.options)
params = ', '.join(f"{name}:{repr_argument_type(valtype)}={repr(default)}" for name, valtype, default, _ in script.options)
yield f'def {runon_name}(context, {params}):'
if script.language == 'python':
for line in script.source_code.splitlines(False):
......@@ -134,7 +140,7 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
yield f' return {new_context}'
# informations about the script, for biseau
yield f'NAME = {name}'
yield f'NAME = "{name}"'
yield f'TAGS = {repr(set.union(*(script.tags for script in scripts)))}'
outputs = set.union(*(set(script.outputs()) for script in scripts))
inputs = set.union(*(set(script.inputs()) for script in scripts))
......@@ -147,7 +153,8 @@ def _standalone_export_pipeline(scripts:[Script], options:dict={}, default_conte
ctype, default, help = options_as_dict(scripts[idx].options)[name]
main_args.append(f"{final_name}:{repr_argument_type(ctype)}={repr(default)}")
main_args = ', '.join(main_args)
yield f'def run_on(context:str, *, {main_args}):'
if main_args: main_args = ', *, ' + main_args
yield f'def run_on(context:str{main_args}):'
# call each *_run_on inside the run_on, taking care to provide its arguments
for runon, script in runons:
......@@ -203,6 +210,7 @@ def option_names_from_options(scripts:[Script]) -> [(int, str, str)]:
def argparse_addarg_args_from_option(name:str, option, *, explicit_value=None) -> [str]:
# print('creating argparse arguments:', name, option)
argtype, default, description = option
others = [] # other options to add to default ones
if explicit_value is not None: default = explicit_value # override default
if argtype is open:
ctype = 'existing_file'
......@@ -213,7 +221,8 @@ def argparse_addarg_args_from_option(name:str, option, *, explicit_value=None) -
elif mode == 'w':
ctype = 'writable_file'
elif isinstance(argtype, (list, tuple)):
ctype = 'elem_in_list((' + ', '.join(map(repr, argtype)) + '))'
ctype = repr_argument_type(type(argtype[0]))
others = ['choices=({})'.format(', '.join(map(repr_argument_type, argtype)))]
elif argtype is str:
ctype = 'str'
elif argtype is bool:
......@@ -226,7 +235,7 @@ def argparse_addarg_args_from_option(name:str, option, *, explicit_value=None) -
ctype = 'float'
else:
raise NotImplementedError(f"Option of type {argtype} cannot be transcripted as widget")
return 'add_argument', (f"'{name}'", f'type={ctype}', f'default={repr(default)}', f'help="{description}"')
return 'add_argument', (f"'{name}'", f'type={ctype}', f'default={repr(default)}', f'help="{description}"', *others)
@wraps(_standalone_export_pipeline)
......
......@@ -2,8 +2,6 @@
"""Load lp file knowing its path.
"""
import tkinter as tk
import tkinter.filedialog
from functools import partial
NAME = 'Open lp file'
......@@ -13,10 +11,7 @@ TAGS = {'ASP', 'utils'}
INPUTS = {}
OUTPUTS = {} # in fact, we do not know. Sorry.
OPEN_LP_FILE = partial(tk.filedialog.askopenfilename, defaultextension='.lp')
def run_on(context:str, *, file:OPEN_LP_FILE=None):
def run_on(context:str, *, file:open=None):
"""
file -- the lp file to open. Must contains valid ASP.
"""
......
......@@ -21,8 +21,9 @@ zip_safe = False
include_package_data = True
packages = biseau
install_requires =
clyngor>=0.3.20
Pillow==5.3.0
clitogui>=0.1.1
clyngor>=0.3.20
pydot>=1.2.4
pytest>=3.9.2
......
......@@ -41,9 +41,12 @@ def test_standalone_export_pipeline_with_different_script_format():
}),
*build_scripts_from_asp_code('link(X,Y) :- node(X) ; node(Y) ; X<Y.'),
))
assert scripts[0].options == (('nodename', str, 'b', ''),)
assert 'nodename' not in scripts[0].options_values
scripts[0].options_values['nodename'] = 'bb'
final_context = biseau.run(scripts)
print('FINAL CONTEXT:', final_context)
code = standalone_export_pipeline.without_formatting(scripts)
code = standalone_export_pipeline.without_formatting(scripts, options={'nodename': True})
print('\nCODE:', code)
env = {}
module = exec(code, env)
......@@ -51,7 +54,7 @@ def test_standalone_export_pipeline_with_different_script_format():
assert callable(env['run_on'])
assert callable(env['cli'])
assert biseau.__version__ in env['__doc__']
found_context = env['run_on']('', args=None)
found_context = env['run_on']('', nodename='bb')
print('FOUND CONTEXT:', found_context)
assert found_context == final_context
os.unlink(pyfile)
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