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