3 # -n do not include custom_ scripts
4 # -v verbose mode, shows progress stuff
6 # this version of locles processes not only all required .pl files
7 # but also all parse_html_templated files.
16 use File::Slurp qw(slurp);
20 use List::Util qw(first);
24 $OUTPUT_AUTOFLUSH = 1;
34 my $basedir = "../..";
35 my $locales_dir = ".";
36 my $bindir = "$basedir/bin/mozilla";
37 my @progdirs = ( "$basedir/SL" );
38 my $dbupdir = "$basedir/sql/Pg-upgrade";
39 my $dbupdir2 = "$basedir/sql/Pg-upgrade2";
40 my $menufile = "menu.ini";
41 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
42 my $javascript_output_dir = $basedir .'/js';
43 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
48 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
49 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
54 my ($top_dir_name) = @_;
61 tie my %dir_h, 'IO::Dir', $dir_name;
63 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
64 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
66 $finder->($_) for @sub_dirs;
69 $finder->($top_dir_name);
75 # overwrite existing entries with the ones from 'missing'
76 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
78 # try to set missing entries from lost ones
79 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
80 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
83 my @bindir_files = find_files($bindir);
84 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
85 my @customfiles = grep /_custom/, @bindir_files;
87 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
89 # put customized files into @customfiles
90 my (@menufiles, %dir_h);
94 @menufiles = ($menufile);
96 tie %dir_h, 'IO::Dir', $basedir;
97 @menufiles = map { "$basedir/$_" } grep { /.*?_$menufile$/ } keys %dir_h;
98 unshift @menufiles, "$basedir/$menufile";
101 tie %dir_h, 'IO::Dir', $dbupdir;
102 my @dbplfiles = grep { /\.pl$/ } keys %dir_h;
104 tie %dir_h, 'IO::Dir', $dbupdir2;
105 my @dbplfiles2 = grep { /\.pl$/ } keys %dir_h;
107 # slurp the translations in
108 if (-f "$locales_dir/all") {
109 require "$locales_dir/all";
111 if (-f "$locales_dir/missing") {
112 require "$locales_dir/missing" ;
113 unlink "$locales_dir/missing";
115 if (-f "$locales_dir/lost") {
116 require "$locales_dir/lost";
117 unlink "$locales_dir/lost";
120 my $charset = slurp("$locales_dir/charset") || 'utf-8';
123 my %old_texts = %{ $self->{texts} || {} };
125 handle_file(@{ $_ }) for @progfiles;
126 handle_file($_, $dbupdir) for @dbplfiles;
127 handle_file($_, $dbupdir2) for @dbplfiles2;
128 scanmenu($_) for @menufiles;
130 for my $file_name (map({find_files($_)} @javascript_dirs)) {
131 scan_javascript_file($file_name);
134 # merge entries to translate with entries from files 'missing' and 'lost'
139 file => "$locales_dir/all",
140 header => $ALL_HEADER,
141 data_name => '$self->{texts}',
142 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
145 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
146 print $js_file 'namespace("kivi").setupLocale({';
148 for my $key (sort(keys(%jslocale))) {
149 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
152 print $js_file ("\n");
153 print $js_file ('});'."\n");
156 foreach my $text (keys %$missing) {
157 if ($locale{$text} || $htmllocale{$text}) {
158 unless ($self->{texts}{$text}) {
159 $self->{texts}{$text} = $missing->{$text};
165 # calc and generate missing
166 my @new_missing = grep { !$self->{texts}{$_} } sort keys %alllocales;
170 file => "$locales_dir/missing",
171 header => $MISSING_HEADER,
172 data_name => '$missing',
173 data_sub => sub { _print_line($_, '', @_) for @new_missing },
177 # calc and generate lost
178 while (my ($text, $translation) = each %old_texts) {
179 next if ($alllocales{$text});
180 push @lost, { 'text' => $text, 'translation' => $translation };
184 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
186 file => "$locales_dir/lost",
187 header => $LOST_HEADER,
189 data_name => '@lost',
191 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
196 my $trlanguage = slurp("$locales_dir/LANGUAGE");
199 search_unused_htmlfiles() if $opt_c;
201 my $count = scalar keys %alllocales;
202 my $notext = scalar @new_missing;
203 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
204 print "\n$trlanguage - ${per}%";
205 print " - $notext/$count missing" if $notext;
214 # These are all the texts to build the translations files.
215 # The file has the form of 'english text' => 'foreign text',
216 # you can add the translation in this file or in the 'missing' file
217 # run locales.pl from this directory to rebuild the translation files
219 $MISSING_HEADER = <<EOL;
220 # add the missing texts and run locales.pl to rebuild
222 $LOST_HEADER = <<EOL;
223 # The last 50 text strings, that have been removed.
224 # This file has been auto-generated by locales.pl. Please don't edit!
232 'no-custom-files' => \$opt_n,
233 'check-files' => \$opt_c,
234 'verbose' => \$opt_v,
246 pod2usage(-exitstatus => 0, -verbose => 2);
251 my $arg = shift @ARGV;
253 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
254 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
263 print "The locale directory '$arg' could not be found.\n";
267 } elsif (!-f 'all' || !-f 'LANGUAGE') {
268 print "locales.pl was not called from a locale/* subdirectory,\n"
269 . "and no locale directory name was given.\n";
273 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
278 my ($file, $dir) = @_;
279 print "\n$file" if $opt_v;
283 &scanfile("$dir/$file");
285 # scan custom_{module}.pl or {login}_{module}.pl files
286 foreach my $customfile (@customfiles) {
287 if ($customfile =~ /_$file/) {
288 if (-f "$dir/$customfile") {
289 &scanfile("$dir/$customfile");
297 sub extract_text_between_parenthesis {
298 my ($fh, $line) = @_;
299 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
302 if (length($line) <= $pos) {
304 return ($text, "") unless ($line);
308 my $cur_char = substr($line, $pos, 1);
310 if (!$inside_string) {
311 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
312 $inside_string = substr($line, $pos + 2, 1);
315 } elsif ((length($line) >= ($pos + 2)) &&
316 (substr($line, $pos, 1) eq "q")) {
317 $inside_string = substr($line, $pos + 1, 1);
320 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
321 $inside_string = $cur_char;
323 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
324 return ($text, substr($line, $pos + 1));
329 $text .= '\\' unless $cur_char eq "'";
333 } elsif ($cur_char eq '\\') {
336 } elsif ($cur_char eq $inside_string) {
337 undef($inside_string);
350 my $dont_include_subs = shift;
351 my $scanned_files = shift;
356 $scanned_files = {} unless ($scanned_files);
357 return if ($scanned_files->{$file});
358 $scanned_files->{$file} = 1;
360 if (!defined $cached{$file}) {
362 return unless (-f "$file");
364 my $fh = new FileHandle;
365 open $fh, "$file" or die "$! : $file";
367 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
370 last if /^\s*__END__/;
374 # is this another file
375 if (/require\s+\W.*\.pl/) {
377 $newfile =~ s/require\s+\W//;
378 $newfile =~ s|bin/mozilla||;
379 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
380 } elsif (/use\s+SL::([\w:]*)/) {
383 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
386 # Some calls to render() are split over multiple lines. Deal
388 while (/(?:parse_html_template2?|render)\s*\( *$/) {
393 # is this a template call?
394 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
395 my $new_file_base = "$basedir/templates/webpages/$1.";
396 if (/parse_html_template2/) {
397 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
401 foreach my $ext (qw(html js json)) {
402 my $new_file = "${new_file_base}${ext}";
404 $cached{$file}{scanh}{$new_file} = 1;
410 if ($opt_c && !$found_one) {
411 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
420 my ($null, $country) = split(/,/);
421 $country =~ s/^ +[\"\']//;
422 $country =~ s/[\"\'].*//;
428 # is it a submit button before $locale->
429 if (/$submitsearch/) {
431 if ($` !~ /locale->text/) {
433 $sub_line_no = $line_no;
437 my ($found) = / (?: locale->text | \b t8 ) \b .*? \(/x;
442 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
445 # if there is no $ in the string record it
446 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
448 # this guarantees one instance of string
449 $cached{$file}{locale}{$string} = 1;
451 # this one is for all the locales
452 $cached{$file}{all}{$string} = 1;
454 # is it a submit button before $locale->
456 $cached{$file}{submit}{$string} = 1;
459 } elsif ($postmatch =~ />/) {
463 # exit loop if there are no more locales on this line
464 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
466 if ( ($postmatch =~ />/)
467 || (!$found && ($sub_line_no != $line_no) && />/)) {
477 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
478 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
479 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
481 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
482 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
483 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
485 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
491 my $fh = new FileHandle;
492 open $fh, "$file" or die "$! : $file";
494 my @a = grep m/^\[/, <$fh>;
498 grep { s/(\[|\])//g } @a;
500 foreach my $item (@a) {
501 my @b = split /--/, $item;
502 foreach my $string (@b) {
504 $locale{$string} = 1;
505 $alllocales{$string} = 1;
511 sub unescape_template_string {
522 return if defined $cached{$file};
524 my %plugins = ( 'loaded' => { }, 'needed' => { } );
526 if (!open(IN, $file)) {
527 print "E: template file '$file' not found\n";
534 while (my $line = <IN>) {
537 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
538 $plugins{loaded}->{$1} = 1;
541 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
543 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
546 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
548 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
549 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
550 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
551 (.*?) # Der zu übersetzende String ::Parameter $3::
552 (?<!\\)\2 # Ende des zu übersetzenden Strings
553 | # Start von Variante 2: [% '...' | $T8 %]
554 \[\% # Template-Start-Tag
555 [\-~#]? # Whitespace-Unterdrückung
556 \s* # Optional beliebig viele Whitespace
557 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
558 (.*?) # Der zu übersetzende String ::Parameter $5::
559 (?<!\\)\4 # Ende des zu übersetzenden Strings
560 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
561 (\$T8) # Filteraufruf ::Parameter $6::
562 .*? # Optionale Argumente für den Filter
564 [\-~#]? # Whitespace-Unterdrückung
565 \%\] # Template-Ende-Tag
568 my $module = $1 || $6;
569 my $string = $3 || $5;
570 print "Found filter >>>$string<<<\n" if $debug;
571 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
573 $string = unescape_template_string($string);
574 $cached{$file}{all}{$string} = 1;
575 $cached{$file}{html}{$string} = 1;
576 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
577 $plugins{needed}->{T8} = 1 if $module eq '$T8';
578 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
581 while ($line =~ m/\[\% # Template-Start-Tag
582 [\-~#]? # Whitespace-Unterdrückung
583 \s* # Optional beliebig viele Whitespace
584 (?: # Die erkannten Template-Direktiven
589 \s+ # Mindestens ein Whitespace
590 [\'\"]? # Anfang des Dateinamens
591 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
592 \.html # Endung ".html", ansonsten kann es der Name eines Blocks sein
594 my $new_file_name = "$basedir/templates/webpages/$1.html";
595 $cached{$file}{scanh}{$new_file_name} = 1;
596 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
602 foreach my $plugin (keys %{ $plugins{needed} }) {
603 next if ($plugins{loaded}->{$plugin});
604 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
607 # copy back into global arrays
608 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
609 $locale{$_} = 1 for keys %{$cached{$file}{html}};
610 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
612 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
614 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
617 sub scan_javascript_file {
620 open(my $fh, $file) || die('can not open file: '. $file);
622 while( my $line = readline($fh) ) {
633 my $text = unescape_template_string($2);
635 $jslocale{$text} = 1;
636 $alllocales{$text} = 1;
642 sub search_unused_htmlfiles {
643 my @unscanned_dirs = ('../../templates/webpages');
645 while (scalar @unscanned_dirs) {
646 my $dir = shift @unscanned_dirs;
648 foreach my $entry (<$dir/*>) {
650 push @unscanned_dirs, $entry;
652 } elsif (($entry =~ /_master.html$/) && -f $entry && !$referenced_html_files{$entry}) {
653 print "W: unused HTML template: " . strip_base($entry) . "\n";
661 my $s = "$_[0]"; # Create a copy of the string.
664 $s =~ s|templates/webpages/||;
671 $val =~ s/(\'|\\$)/\\$1/g;
672 return "'" . $val . "'";
677 $val =~ s/(\"|\\$)/\\$1/g;
678 return '"'. $val .'"';
682 my $key = _single_quote(shift);
683 my $text = _single_quote(shift);
685 my $template = $params{template} || qq| %-29s => %s,\n|;
686 my $fh = $params{fh} || croak 'need filehandle in _print_line';
688 print $fh sprintf $template, $key, $text;
694 my $file = $params{file} || croak 'need filename in generate_file';
695 my $header = $params{header};
696 my $lines = $params{data_sub};
697 my $data_name = $params{data_name};
698 my @delim = split //, ($params{delim} || '{}');
700 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
702 $charset =~ s/\r?\n//g;
703 my $emacs_charset = lc $charset;
705 print $fh "#!/usr/bin/perl\n# -*- coding: $emacs_charset; -*-\n# vim: fenc=$charset\n\nuse utf8;\n\n";
706 print $fh $header, "\n" if $header;
707 print $fh "$data_name = $delim[0]\n" if $data_name;
711 print $fh qq|$delim[1];\n\n1;\n|;
717 do { local ( @ARGV, $/ ) = $file; <> }
724 locales.pl - Collect strings for translation in kivitendo
728 locales.pl [options] lang_code
731 -n, --no-custom-files Do not process files whose name contains "_"
732 -c, --check-files Run extended checks on HTML files
733 -v, --verbose Be more verbose
734 -h, --help Show this help
740 =item B<-n>, B<--no-custom-files>
742 Do not process files whose name contains "_", e.g. "custom_io.pl".
744 =item B<-c>, B<--check-files>
746 Run extended checks on the usage of templates. This can be used to
747 discover HTML templates that are never used as well as the usage of
748 non-existing HTML templates.
750 =item B<-v>, B<--verbose>
758 This script collects strings from Perl files, the menu.ini file and
759 HTML templates and puts them into the file "all" for translation.