%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Support for scripts %%%% %%%% main(BeforeCall, IterCall, AfterCall) %%%% %%%% - determines input file from argv, if none supplied it takes stdin %%%% - calls BeforeCall %%%% - for each clause Clause in the input file calls IterCall, with 1st arg %%%% set to the clause %%%% - calls AfterCall %%%% - If the Call arguments have an arity of 1 (BeforeCall, AfterCall) or %%%% 2 (IterCall), the list of options given to the program is passed %%%% in the last argument. An option is indicated by the '-' as first %%%% character. The list of options contains atoms with the options that %%%% are present, with the initial '-' character removed. %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% :- module(script_support, [main/3]). :- use_module('../contrib/pl/swilib/fromonto'). :- use_module('../contrib/pl/swilib/err'). main_argv(BeforeCall, IterCall, AfterCall) :- prompt(_,''), current_prolog_flag(argv, Argv), append(_, [--|Args], Argv), !, get_options(Args, Options, ProperArgs), execute(BeforeCall, Options), ( ProperArgs = [] -> iter_clauses(IterCall, Options) ; ProperArgs = [Filename|_], msg('% Processing file ~w.', [Filename]), iter_clauses(Filename, IterCall, Options) ), execute(AfterCall, Options). get_options([Arg|Args], [Option|Options], ProperArgs) :- sub_atom(Arg, 0, 1, _, '-'), !, sub_atom(Arg, 1, _, 0, Option), get_options(Args, Options, ProperArgs). get_options(Args, [], Args). execute(Call, Options) :- functor(Call, _, N), ( N > 0 -> arg(1, Call, Options) ; true ), call(Call). iter_clauses(File, Call, Options) :- from_file(iter_clauses(Call, Options), File). iter_clauses(Call, Options) :- functor(Call, _, N), ( N > 1 -> arg(2, Call, Options) ; true ), repeat, read_term(T, [double_quotes(atom)]), ( T == end_of_file -> !, true ; arg(1, Call, T), call(Call), fail ). main(BeforeCall, IterCall, AfterCall) :- style_check(-atom), catch(main_argv(BeforeCall, IterCall, AfterCall), E, (print_message(error, E), fail)), halt. main(_, _, _) :- halt(1).