epic-s6ts
[kivitendo-erp.git] / scripts / generate_client_js_actions.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use File::Slurp;
7 use FindBin;
8 use List::Util qw(first max);
9 use Template;
10
11 my $rel_dir = $FindBin::Bin . '/..';
12 my @actions;
13
14 foreach (read_file("${rel_dir}/SL/ClientJS.pm")) {
15   chomp;
16
17   next unless (m/^my \%supported_methods/ .. m/^\);/);
18
19   push @actions, [ 'action',  $1, $2, $3 ] if m/^ \s+ '? ([a-zA-Z_:]+) '? \s*=>\s* (-? \d+) , (?: \s* \# \s+ (.+))? $/x;
20   push @actions, [ 'comment', $1, $2     ] if m/^ \s+\# \s+ (.+?) (?: \s* pattern: \s+ (.+))? $/x;
21 }
22
23 my $longest         = max map { length($_->[1]) } grep { $_->[0] eq 'action' } @actions;
24 my $first           = 1;
25 my $default_pattern = '$(<TARGET>).<FUNCTION>(<ARGS>)';
26 my $pattern         = $default_pattern;
27 my $output          = '';
28
29 foreach my $action (@actions) {
30   if ($action->[0] eq 'comment') {
31     $output .= "\n" unless $first;
32     $output .= "      // " . $action->[1] . "\n";
33
34     $pattern = $action->[2] eq '<DEFAULT>' ? $default_pattern : $action->[2] if $action->[2];
35
36   } else {
37     my $args = $action->[2] == 1 ? ''
38              : $action->[2] <  0 ? 'action.slice(2, action.length)'
39              :                     join(', ', map { "action[$_]" } (2..$action->[2]));
40
41     $output .= sprintf('      %s if (action[0] == \'%s\')%s ',
42                        $first ? '    ' : 'else',
43                        $action->[1],
44                        ' ' x ($longest - length($action->[1])));
45
46     my $function =  $action->[1];
47     $function    =~ s/.*://;
48
49     my $call     =  $action->[3] || $pattern;
50     $call        =~ s/<TARGET>/'action[1]'/eg;
51     $call        =~ s/<FUNCTION>/$function/eg;
52     $call        =~ s/<ARGS>/$args/eg;
53     $call        =~ s/<ARG(\d+)>/'action[' . ($1 + 1) . ']'/eg;
54
55     $output .= $call . ";\n";
56     $first   = 0;
57   }
58 }
59
60 $output .= sprintf "\n      else\%sconsole.log('Unknown action: ' + action[0]);\n", ' ' x (4 + 2 + 6 + 3 + 4 + 2 + $longest + 1);
61
62 my $template = Template->new({ ABSOLUTE => 1 });
63 $template->process($rel_dir . '/scripts/generate_client_js_actions.tpl', { actions => $output }, $rel_dir . '/js/client_js.js') || die $template->error(), "\n";
64 print "js/client_js.js generated automatically.\n";