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 $menufile = "menu.ini";
39 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
40 my $javascript_output_dir = $basedir .'/js';
41 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
46 my %ignore_unused_templates = (
47 map { $_ => 1 } qw(common/help_overlay.html ct/testpage.html generic/autocomplete.html oe/periodic_invoices_email.txt part/testpage.html t/render.html t/render.js)
50 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
51 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
56 my ($top_dir_name) = @_;
63 tie my %dir_h, 'IO::Dir', $dir_name;
65 push @files, grep { -f } map { "${dir_name}/${_}" } keys %dir_h;
66 my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
68 $finder->($_) for @sub_dirs;
71 $finder->($top_dir_name);
77 # overwrite existing entries with the ones from 'missing'
78 $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
80 # try to set missing entries from lost ones
81 my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
82 $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
85 my @bindir_files = find_files($bindir);
86 my @progfiles = map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pl$/ && !/_custom/ } @bindir_files;
87 my @customfiles = grep /_custom/, @bindir_files;
89 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
91 # put customized files into @customfiles
92 my (@menufiles, %dir_h);
96 @menufiles = ($menufile);
98 tie %dir_h, 'IO::Dir', $basedir;
99 @menufiles = map { "$basedir/$_" } grep { /.*?_$menufile$/ } keys %dir_h;
100 unshift @menufiles, "$basedir/$menufile";
104 foreach my $sub_dir ("Pg-upgrade", "Pg-upgrade2", "Pg-upgrade2-auth") {
105 my $dir = "$basedir/sql/$sub_dir";
106 tie %dir_h, 'IO::Dir', $dir;
107 push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
110 # slurp the translations in
111 if (-f "$locales_dir/all") {
112 require "$locales_dir/all";
114 if (-f "$locales_dir/missing") {
115 require "$locales_dir/missing" ;
116 unlink "$locales_dir/missing";
118 if (-f "$locales_dir/lost") {
119 require "$locales_dir/lost";
120 unlink "$locales_dir/lost";
123 my $charset = slurp("$locales_dir/charset") || 'utf-8';
126 my %old_texts = %{ $self->{texts} || {} };
128 handle_file(@{ $_ }) for @progfiles;
129 handle_file(@{ $_ }) for @dbplfiles;
130 scanmenu($_) for @menufiles;
132 for my $file_name (map({find_files($_)} @javascript_dirs)) {
133 scan_javascript_file($file_name);
136 # merge entries to translate with entries from files 'missing' and 'lost'
141 file => "$locales_dir/all",
142 header => $ALL_HEADER,
143 data_name => '$self->{texts}',
144 data_sub => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
147 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
148 print $js_file 'namespace("kivi").setupLocale({';
150 for my $key (sort(keys(%jslocale))) {
151 print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
154 print $js_file ("\n");
155 print $js_file ('});'."\n");
158 foreach my $text (keys %$missing) {
159 if ($locale{$text} || $htmllocale{$text}) {
160 unless ($self->{texts}{$text}) {
161 $self->{texts}{$text} = $missing->{$text};
167 # calc and generate missing
168 my @new_missing = grep { !$self->{texts}{$_} } sort keys %alllocales;
172 my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
173 foreach my $entry (@new_missing) {
174 my $other = $existing_lc{lc $entry};
175 print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
180 file => "$locales_dir/missing",
181 header => $MISSING_HEADER,
182 data_name => '$missing',
183 data_sub => sub { _print_line($_, '', @_) for @new_missing },
187 # calc and generate lost
188 while (my ($text, $translation) = each %old_texts) {
189 next if ($alllocales{$text});
190 push @lost, { 'text' => $text, 'translation' => $translation };
194 splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
196 file => "$locales_dir/lost",
197 header => $LOST_HEADER,
199 data_name => '@lost',
201 _print_line($_->{text}, $_->{translation}, @_, template => " { 'text' => %s, 'translation' => %s },\n") for @lost;
206 my $trlanguage = slurp("$locales_dir/LANGUAGE");
209 search_unused_htmlfiles() if $opt_c;
211 my $count = scalar keys %alllocales;
212 my $notext = scalar @new_missing;
213 my $per = sprintf("%.1f", ($count - $notext) / $count * 100);
214 print "\n$trlanguage - ${per}%";
215 print " - $notext/$count missing" if $notext;
224 # These are all the texts to build the translations files.
225 # The file has the form of 'english text' => 'foreign text',
226 # you can add the translation in this file or in the 'missing' file
227 # run locales.pl from this directory to rebuild the translation files
229 $MISSING_HEADER = <<EOL;
230 # add the missing texts and run locales.pl to rebuild
232 $LOST_HEADER = <<EOL;
233 # The last 50 text strings, that have been removed.
234 # This file has been auto-generated by locales.pl. Please don't edit!
242 'no-custom-files' => \$opt_n,
243 'check-files' => \$opt_c,
244 'verbose' => \$opt_v,
256 pod2usage(-exitstatus => 0, -verbose => 2);
261 my $arg = shift @ARGV;
263 foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
264 next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
273 print "The locale directory '$arg' could not be found.\n";
277 } elsif (!-f 'all' || !-f 'LANGUAGE') {
278 print "locales.pl was not called from a locale/* subdirectory,\n"
279 . "and no locale directory name was given.\n";
283 $locale ||= (grep { $_ } split m:/:, getcwd())[-1];
288 my ($file, $dir) = @_;
289 print "\n$file" if $opt_v;
293 &scanfile("$dir/$file");
295 # scan custom_{module}.pl or {login}_{module}.pl files
296 foreach my $customfile (@customfiles) {
297 if ($customfile =~ /_$file/) {
298 if (-f "$dir/$customfile") {
299 &scanfile("$dir/$customfile");
307 sub extract_text_between_parenthesis {
308 my ($fh, $line) = @_;
309 my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
312 if (length($line) <= $pos) {
314 return ($text, "") unless ($line);
318 my $cur_char = substr($line, $pos, 1);
320 if (!$inside_string) {
321 if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
322 $inside_string = substr($line, $pos + 2, 1);
325 } elsif ((length($line) >= ($pos + 2)) &&
326 (substr($line, $pos, 1) eq "q")) {
327 $inside_string = substr($line, $pos + 1, 1);
330 } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
331 $inside_string = $cur_char;
333 } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
334 return ($text, substr($line, $pos + 1));
339 $text .= '\\' unless $cur_char eq "'";
343 } elsif ($cur_char eq '\\') {
346 } elsif ($cur_char eq $inside_string) {
347 undef($inside_string);
360 my $dont_include_subs = shift;
361 my $scanned_files = shift;
366 $scanned_files = {} unless ($scanned_files);
367 return if ($scanned_files->{$file});
368 $scanned_files->{$file} = 1;
370 if (!defined $cached{$file}) {
372 return unless (-f "$file");
374 my $fh = new FileHandle;
375 open $fh, "$file" or die "$! : $file";
377 my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
380 last if /^\s*__END__/;
384 # is this another file
385 if (/require\s+\W.*\.pl/) {
387 $newfile =~ s/require\s+\W//;
388 $newfile =~ s|bin/mozilla||;
389 $cached{$file}{scan}{"$bindir/$newfile"} = 1;
390 } elsif (/use\s+SL::([\w:]*)/) {
393 $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
396 # Some calls to render() are split over multiple lines. Deal
398 while (/(?:parse_html_template2?|render)\s*\( *$/) {
403 # is this a template call?
404 if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
405 my $new_file_base = "$basedir/templates/webpages/$1.";
406 if (/parse_html_template2/) {
407 print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
411 foreach my $ext (qw(html js json)) {
412 my $new_file = "${new_file_base}${ext}";
414 $cached{$file}{scanh}{$new_file} = 1;
420 if ($opt_c && !$found_one) {
421 print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
430 my ($null, $country) = split(/,/);
431 $country =~ s/^ +[\"\']//;
432 $country =~ s/[\"\'].*//;
438 # is it a submit button before $locale->
439 if (/$submitsearch/) {
441 if ($` !~ /locale->text/) {
443 $sub_line_no = $line_no;
448 if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
455 ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
458 # if there is no $ in the string record it
459 unless (($string =~ /\$\D.*/) || ("" eq $string)) {
461 # this guarantees one instance of string
462 $cached{$file}{locale}{$string} = 1;
464 # this one is for all the locales
465 $cached{$file}{all}{$string} = 1;
467 # is it a submit button before $locale->
469 $cached{$file}{submit}{$string} = 1;
472 } elsif ($postmatch =~ />/) {
476 # exit loop if there are no more locales on this line
477 ($rc) = ($postmatch =~ /locale->text | \b t8/x);
479 if ( ($postmatch =~ />/)
480 || (!$found && ($sub_line_no != $line_no) && />/)) {
490 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
491 $locale{$_} = 1 for keys %{$cached{$file}{locale}};
492 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
494 scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
495 scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
496 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
498 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
504 my $fh = new FileHandle;
505 open $fh, "$file" or die "$! : $file";
507 my @a = grep m/^\[/, <$fh>;
511 grep { s/(\[|\])//g } @a;
513 foreach my $item (@a) {
514 my @b = split /--/, $item;
515 foreach my $string (@b) {
517 $locale{$string} = 1;
518 $alllocales{$string} = 1;
524 sub unescape_template_string {
535 return if defined $cached{$file};
537 my %plugins = ( 'loaded' => { }, 'needed' => { } );
539 if (!open(IN, $file)) {
540 print "E: template file '$file' not found\n";
547 while (my $line = <IN>) {
550 while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
551 $plugins{loaded}->{$1} = 1;
554 while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
556 $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
559 $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
561 while ($line =~ m/(?: # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
562 (LxERP\.t8)\( # LxERP.t8( ::Parameter $1::
563 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $2::
564 (.*?) # Der zu übersetzende String ::Parameter $3::
565 (?<!\\)\2 # Ende des zu übersetzenden Strings
566 | # Start von Variante 2: [% '...' | $T8 %]
567 \[\% # Template-Start-Tag
568 [\-~#]? # Whitespace-Unterdrückung
569 \s* # Optional beliebig viele Whitespace
570 ([\'\"]) # Anfang des zu übersetzenden Strings ::Parameter $4::
571 (.*?) # Der zu übersetzende String ::Parameter $5::
572 (?<!\\)\4 # Ende des zu übersetzenden Strings
573 \s*\|\s* # Pipe-Zeichen mit optionalen Whitespace davor und danach
574 (\$T8) # Filteraufruf ::Parameter $6::
575 .*? # Optionale Argumente für den Filter
577 [\-~#]? # Whitespace-Unterdrückung
578 \%\] # Template-Ende-Tag
581 my $module = $1 || $6;
582 my $string = $3 || $5;
583 print "Found filter >>>$string<<<\n" if $debug;
584 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
586 $string = unescape_template_string($string);
587 $cached{$file}{all}{$string} = 1;
588 $cached{$file}{html}{$string} = 1;
589 $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
590 $plugins{needed}->{T8} = 1 if $module eq '$T8';
591 $plugins{needed}->{LxERP} = 1 if $module eq 'LxERP.t8';
594 while ($line =~ m/\[\% # Template-Start-Tag
595 [\-~#]? # Whitespace-Unterdrückung
596 \s* # Optional beliebig viele Whitespace
597 (?: # Die erkannten Template-Direktiven
602 \s+ # Mindestens ein Whitespace
603 [\'\"]? # Anfang des Dateinamens
604 ([^\s]+) # Beliebig viele Nicht-Whitespaces -- Dateiname
605 \.html # Endung ".html", ansonsten kann es der Name eines Blocks sein
607 my $new_file_name = "$basedir/templates/webpages/$1.html";
608 $cached{$file}{scanh}{$new_file_name} = 1;
609 substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
615 foreach my $plugin (keys %{ $plugins{needed} }) {
616 next if ($plugins{loaded}->{$plugin});
617 print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
620 # copy back into global arrays
621 $alllocales{$_} = 1 for keys %{$cached{$file}{all}};
622 $locale{$_} = 1 for keys %{$cached{$file}{html}};
623 $submit{$_} = 1 for keys %{$cached{$file}{submit}};
625 scanhtmlfile($_) for keys %{$cached{$file}{scanh}};
627 $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
630 sub scan_javascript_file {
633 open(my $fh, $file) || die('can not open file: '. $file);
635 while( my $line = readline($fh) ) {
646 my $text = unescape_template_string($2);
648 $jslocale{$text} = 1;
649 $alllocales{$text} = 1;
655 sub search_unused_htmlfiles {
656 my @unscanned_dirs = ('../../templates/webpages');
658 while (scalar @unscanned_dirs) {
659 my $dir = shift @unscanned_dirs;
661 foreach my $entry (<$dir/*>) {
663 push @unscanned_dirs, $entry;
665 } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
666 print "W: unused HTML template: " . strip_base($entry) . "\n";
674 my $s = "$_[0]"; # Create a copy of the string.
677 $s =~ s|templates/webpages/||;
684 $val =~ s/(\'|\\$)/\\$1/g;
685 return "'" . $val . "'";
690 $val =~ s/(\"|\\$)/\\$1/g;
691 return '"'. $val .'"';
695 my $key = _single_quote(shift);
696 my $text = _single_quote(shift);
698 my $template = $params{template} || qq| %-29s => %s,\n|;
699 my $fh = $params{fh} || croak 'need filehandle in _print_line';
701 print $fh sprintf $template, $key, $text;
707 my $file = $params{file} || croak 'need filename in generate_file';
708 my $header = $params{header};
709 my $lines = $params{data_sub};
710 my $data_name = $params{data_name};
711 my @delim = split //, ($params{delim} || '{}');
713 open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
715 $charset =~ s/\r?\n//g;
716 my $emacs_charset = lc $charset;
718 print $fh "#!/usr/bin/perl\n# -*- coding: $emacs_charset; -*-\n# vim: fenc=$charset\n\nuse utf8;\n\n";
719 print $fh $header, "\n" if $header;
720 print $fh "$data_name = $delim[0]\n" if $data_name;
724 print $fh qq|$delim[1];\n\n1;\n|;
730 do { local ( @ARGV, $/ ) = $file; <> }
737 locales.pl - Collect strings for translation in kivitendo
741 locales.pl [options] lang_code
744 -n, --no-custom-files Do not process files whose name contains "_"
745 -c, --check-files Run extended checks on HTML files
746 -v, --verbose Be more verbose
747 -h, --help Show this help
753 =item B<-n>, B<--no-custom-files>
755 Do not process files whose name contains "_", e.g. "custom_io.pl".
757 =item B<-c>, B<--check-files>
759 Run extended checks on the usage of templates. This can be used to
760 discover HTML templates that are never used as well as the usage of
761 non-existing HTML templates.
763 =item B<-v>, B<--verbose>
771 This script collects strings from Perl files, the menu.ini file and
772 HTML templates and puts them into the file "all" for translation.