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 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
171 foreach my $entry (@new_missing) {
172 my $other = $existing_lc{lc $entry};
173 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
178 file => "$locales_dir/missing",
179 header => $MISSING_HEADER,
180 data_name => '$missing',
181 data_sub => sub { _print_line($_, '', @_) for @new_missing },
185 # calc and generate lost
186 while (my ($text, $translation) = each %old_texts) {
187 next if ($alllocales{$text});
188 push @lost, { 'text' => $text, 'translation' => $translation };
192 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
194 file => "$locales_dir/lost",
195 header => $LOST_HEADER,
197 data_name => '@lost',
199 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
204 my $trlanguage = slurp("$locales_dir/LANGUAGE");
207 search_unused_htmlfiles() if $opt_c;
209 my $count = scalar keys %alllocales;
210 my $notext = scalar @new_missing;
211 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
212 print "\n$trlanguage - ${per}%";
213 print " - $notext/$count missing" if $notext;
222 # These are all the texts to build the translations files.
223 # The file has the form of 'english text' => 'foreign text',
224 # you can add the translation in this file or in the 'missing' file
225 # run locales.pl from this directory to rebuild the translation files
227 $MISSING_HEADER = <<EOL;
228 # add the missing texts and run locales.pl to rebuild
230 $LOST_HEADER = <<EOL;
231 # The last 50 text strings, that have been removed.
232 # This file has been auto-generated by locales.pl. Please don't edit!
240 'no-custom-files' => \$opt_n,
241 'check-files' => \$opt_c,
242 'verbose' => \$opt_v,
254 pod2usage(-exitstatus => 0, -verbose => 2);
259 my $arg = shift @ARGV;
261 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
262 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
271 print "The locale directory '$arg' could not be found.\n";
275 } elsif (!-f 'all' || !-f 'LANGUAGE') {
276 print "locales.pl was not called from a locale/* subdirectory,\n"
277 . "and no locale directory name was given.\n";
281 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
286 my ($file, $dir) = @_;
287 print "\n$file" if $opt_v;
291 &scanfile("$dir/$file");
293 # scan custom_{module}.pl or {login}_{module}.pl files
294 foreach my $customfile (@customfiles) {
295 if ($customfile =~ /_$file/) {
296 if (-f "$dir/$customfile") {
297 &scanfile("$dir/$customfile");
305 sub extract_text_between_parenthesis {
306 my ($fh, $line) = @_;
307 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
310 if (length($line) <= $pos) {
312 return ($text, "") unless ($line);
316 my $cur_char = substr($line, $pos, 1);
318 if (!$inside_string) {
319 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
320 $inside_string = substr($line, $pos + 2, 1);
323 } elsif ((length($line) >= ($pos + 2)) &&
324 (substr($line, $pos, 1) eq "q")) {
325 $inside_string = substr($line, $pos + 1, 1);
328 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
329 $inside_string = $cur_char;
331 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
332 return ($text, substr($line, $pos + 1));
337 $text .= '\\' unless $cur_char eq "'";
341 } elsif ($cur_char eq '\\') {
344 } elsif ($cur_char eq $inside_string) {
345 undef($inside_string);
358 my $dont_include_subs = shift;
359 my $scanned_files = shift;
364 $scanned_files = {} unless ($scanned_files);
365 return if ($scanned_files->{$file});
366 $scanned_files->{$file} = 1;
368 if (!defined $cached{$file}) {
370 return unless (-f "$file");
372 my $fh = new FileHandle;
373 open $fh, "$file" or die "$! : $file";
375 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
378 last if /^\s*__END__/;
382 # is this another file
383 if (/require\s+\W.*\.pl/) {
385 $newfile =~ s/require\s+\W//;
386 $newfile =~ s|bin/mozilla||;
387 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
388 } elsif (/use\s+SL::([\w:]*)/) {
391 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
394 # Some calls to render() are split over multiple lines. Deal
396 while (/(?:parse_html_template2?|render)\s*\( *$/) {
401 # is this a template call?
402 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
403 my $new_file_base = "$basedir/templates/webpages/$1.";
404 if (/parse_html_template2/) {
405 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
409 foreach my $ext (qw(html js json)) {
410 my $new_file = "${new_file_base}${ext}";
412 $cached{$file}{scanh}{$new_file} = 1;
418 if ($opt_c && !$found_one) {
419 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
428 my ($null, $country) = split(/,/);
429 $country =~ s/^ +[\"\']//;
430 $country =~ s/[\"\'].*//;
436 # is it a submit button before $locale->
437 if (/$submitsearch/) {
439 if ($` !~ /locale->text/) {
441 $sub_line_no = $line_no;
445 my ($found) = / (?: locale->text | \b t8 ) \b .*? \(/x;
450 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
453 # if there is no $ in the string record it
454 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
456 # this guarantees one instance of string
457 $cached{$file}{locale}{$string} = 1;
459 # this one is for all the locales
460 $cached{$file}{all}{$string} = 1;
462 # is it a submit button before $locale->
464 $cached{$file}{submit}{$string} = 1;
467 } elsif ($postmatch =~ />/) {
471 # exit loop if there are no more locales on this line
472 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
474 if ( ($postmatch =~ />/)
475 || (!$found && ($sub_line_no != $line_no) && />/)) {
485 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
486 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
487 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
489 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
490 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
491 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
493 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
499 my $fh = new FileHandle;
500 open $fh, "$file" or die "$! : $file";
502 my @a = grep m/^\[/, <$fh>;
506 grep { s/(\[|\])//g } @a;
508 foreach my $item (@a) {
509 my @b = split /--/, $item;
510 foreach my $string (@b) {
512 $locale{$string} = 1;
513 $alllocales{$string} = 1;
519 sub unescape_template_string {
530 return if defined $cached{$file};
532 my %plugins = ( 'loaded' => { }, 'needed' => { } );
534 if (!open(IN, $file)) {
535 print "E: template file '$file' not found\n";
542 while (my $line = <IN>) {
545 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
546 $plugins{loaded}->{$1} = 1;
549 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
551 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
554 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
556 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
557 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
558 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
559 (.*?) # Der zu übersetzende String ::Parameter $3::
560 (?<!\\)\2 # Ende des zu übersetzenden Strings
561 | # Start von Variante 2: [% '...' | $T8 %]
562 \[\% # Template-Start-Tag
563 [\-~#]? # Whitespace-Unterdrückung
564 \s* # Optional beliebig viele Whitespace
565 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
566 (.*?) # Der zu übersetzende String ::Parameter $5::
567 (?<!\\)\4 # Ende des zu übersetzenden Strings
568 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
569 (\$T8) # Filteraufruf ::Parameter $6::
570 .*? # Optionale Argumente für den Filter
572 [\-~#]? # Whitespace-Unterdrückung
573 \%\] # Template-Ende-Tag
576 my $module = $1 || $6;
577 my $string = $3 || $5;
578 print "Found filter >>>$string<<<\n" if $debug;
579 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
581 $string = unescape_template_string($string);
582 $cached{$file}{all}{$string} = 1;
583 $cached{$file}{html}{$string} = 1;
584 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
585 $plugins{needed}->{T8} = 1 if $module eq '$T8';
586 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
589 while ($line =~ m/\[\% # Template-Start-Tag
590 [\-~#]? # Whitespace-Unterdrückung
591 \s* # Optional beliebig viele Whitespace
592 (?: # Die erkannten Template-Direktiven
597 \s+ # Mindestens ein Whitespace
598 [\'\"]? # Anfang des Dateinamens
599 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
600 \.html # Endung ".html", ansonsten kann es der Name eines Blocks sein
602 my $new_file_name = "$basedir/templates/webpages/$1.html";
603 $cached{$file}{scanh}{$new_file_name} = 1;
604 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
610 foreach my $plugin (keys %{ $plugins{needed} }) {
611 next if ($plugins{loaded}->{$plugin});
612 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
615 # copy back into global arrays
616 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
617 $locale{$_} = 1 for keys %{$cached{$file}{html}};
618 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
620 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
622 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
625 sub scan_javascript_file {
628 open(my $fh, $file) || die('can not open file: '. $file);
630 while( my $line = readline($fh) ) {
641 my $text = unescape_template_string($2);
643 $jslocale{$text} = 1;
644 $alllocales{$text} = 1;
650 sub search_unused_htmlfiles {
651 my @unscanned_dirs = ('../../templates/webpages');
653 while (scalar @unscanned_dirs) {
654 my $dir = shift @unscanned_dirs;
656 foreach my $entry (<$dir/*>) {
658 push @unscanned_dirs, $entry;
660 } elsif (($entry =~ /_master.html$/) && -f $entry && !$referenced_html_files{$entry}) {
661 print "W: unused HTML template: " . strip_base($entry) . "\n";
669 my $s = "$_[0]"; # Create a copy of the string.
672 $s =~ s|templates/webpages/||;
679 $val =~ s/(\'|\\$)/\\$1/g;
680 return "'" . $val . "'";
685 $val =~ s/(\"|\\$)/\\$1/g;
686 return '"'. $val .'"';
690 my $key = _single_quote(shift);
691 my $text = _single_quote(shift);
693 my $template = $params{template} || qq| %-29s => %s,\n|;
694 my $fh = $params{fh} || croak 'need filehandle in _print_line';
696 print $fh sprintf $template, $key, $text;
702 my $file = $params{file} || croak 'need filename in generate_file';
703 my $header = $params{header};
704 my $lines = $params{data_sub};
705 my $data_name = $params{data_name};
706 my @delim = split //, ($params{delim} || '{}');
708 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
710 $charset =~ s/\r?\n//g;
711 my $emacs_charset = lc $charset;
713 print $fh "#!/usr/bin/perl\n# -*- coding: $emacs_charset; -*-\n# vim: fenc=$charset\n\nuse utf8;\n\n";
714 print $fh $header, "\n" if $header;
715 print $fh "$data_name = $delim[0]\n" if $data_name;
719 print $fh qq|$delim[1];\n\n1;\n|;
725 do { local ( @ARGV, $/ ) = $file; <> }
732 locales.pl - Collect strings for translation in kivitendo
736 locales.pl [options] lang_code
739 -n, --no-custom-files Do not process files whose name contains "_"
740 -c, --check-files Run extended checks on HTML files
741 -v, --verbose Be more verbose
742 -h, --help Show this help
748 =item B<-n>, B<--no-custom-files>
750 Do not process files whose name contains "_", e.g. "custom_io.pl".
752 =item B<-c>, B<--check-files>
754 Run extended checks on the usage of templates. This can be used to
755 discover HTML templates that are never used as well as the usage of
756 non-existing HTML templates.
758 =item B<-v>, B<--verbose>
766 This script collects strings from Perl files, the menu.ini file and
767 HTML templates and puts them into the file "all" for translation.