Some changes from rel_2_2:
[koha.git] / misc / translator / tmpl_process3.pl
1 #!/usr/bin/perl
2 # This file is part of Koha
3 # Parts copyright 2003-2004 Paul Poulain
4 # Parts copyright 2003-2004 Jerome Vizcaino
5 # Parts copyright 2004 Ambrose Li
6
7 =head1 NAME
8
9 tmpl_process3.pl - Alternative version of tmpl_process.pl
10 using gettext-compatible translation files
11
12 =cut
13
14 use strict;
15 use Getopt::Long;
16 use Locale::PO;
17 use File::Temp qw( :POSIX );
18 use TmplTokenizer;
19 use VerboseWarnings qw( :warn :die );
20
21 ###############################################################################
22
23 use vars qw( @in_files $in_dir $str_file $out_dir );
24 use vars qw( @excludes $exclude_regex );
25 use vars qw( $recursive_p );
26 use vars qw( $pedantic_p );
27 use vars qw( $href );
28 use vars qw( $type );   # file extension (DOS form without the dot) to match
29 use vars qw( $charset_in $charset_out );
30
31 ###############################################################################
32
33 sub find_translation ($) {
34     my($s) = @_;
35     my $key = $s;
36     if ($s =~ /\S/s) {
37         $key = TmplTokenizer::string_canon($key);
38         $key = TmplTokenizer::charset_convert($key, $charset_in, $charset_out);
39         $key = TmplTokenizer::quote_po($key);
40     }
41     return defined $href->{$key}
42                 && !$href->{$key}->fuzzy
43                 && length Locale::PO->dequote($href->{$key}->msgstr)?
44            Locale::PO->dequote($href->{$key}->msgstr): $s;
45 }
46
47 sub text_replace_tag ($$) {
48     my($t, $attr) = @_;
49     my $it;
50     # value [tag=input], meta
51     my $tag = lc($1) if $t =~ /^<(\S+)/s;
52     my $translated_p = 0;
53     for my $a ('alt', 'content', 'title', 'value') {
54         if ($attr->{$a}) {
55             next if $a eq 'content' && $tag ne 'meta';
56             next if $a eq 'value' && ($tag ne 'input'
57                 || (ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:hidden|radio|text)$/)); # FIXME
58             my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
59             if ($val =~ /\S/s) {
60                 my $s = find_translation($val);
61                 if ($attr->{$a}->[1] ne $s) { #FIXME
62                     $attr->{$a}->[1] = $s; # FIXME
63                     $attr->{$a}->[2] = ($s =~ /"/s)? "'$s'": "\"$s\""; #FIXME
64                     $translated_p = 1;
65                 }
66             }
67         }
68     }
69     if ($translated_p) {
70         $it = "<$tag"
71             . join('', map {
72                     sprintf(' %s=%s', $_, $attr->{$_}->[2]) #FIXME
73                 } sort {
74                     $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME
75                 } keys %$attr)
76             . '>';
77     } else {
78         $it = $t;
79     }
80     return $it;
81 }
82
83 sub text_replace (**) {
84     my($h, $output) = @_;
85     for (;;) {
86         my $s = TmplTokenizer::next_token $h;
87     last unless defined $s;
88         my($kind, $t, $attr) = ($s->type, $s->string, $s->attributes);
89         if ($kind eq TmplTokenType::TEXT) {
90             print $output find_translation($t);
91         } elsif ($kind eq TmplTokenType::TEXT_PARAMETRIZED) {
92             my $fmt = find_translation($s->form);
93             print $output TmplTokenizer::parametrize($fmt, 1, $s, sub {
94                 $_ = $_[0];
95                 my($kind, $t, $attr) = ($_->type, $_->string, $_->attributes);
96                 $kind == TmplTokenType::TAG && %$attr?
97                     text_replace_tag($t, $attr): $t });
98         } elsif ($kind eq TmplTokenType::TAG && %$attr) {
99             print $output text_replace_tag($t, $attr);
100         } elsif ($s->has_js_data) {
101             for my $t (@{$s->js_data}) {
102                 # FIXME for this whole block
103                 if ($t->[0]) {
104                     printf $output "%s%s%s", $t->[2], find_translation $t->[3],
105                             $t->[2];
106                 } else {
107                     print $output $t->[1];
108                 }
109             }
110         } elsif (defined $t) {
111             print $output $t;
112         }
113     }
114 }
115
116 sub listfiles ($$) {
117     my($dir, $type) = @_;
118     my @it = ();
119     if (opendir(DIR, $dir)) {
120         my @dirent = readdir DIR;       # because DIR is shared when recursing
121         closedir DIR;
122         for my $dirent (@dirent) {
123             my $path = "$dir/$dirent";
124             if ($dirent =~ /^\./ || $dirent eq 'CVS' || $dirent eq 'RCS'
125             || (defined $exclude_regex && $dirent =~ /^(?:$exclude_regex)$/)) {
126                 ;
127             } elsif (-f $path) {
128                 push @it, $path if !defined $type || $dirent =~ /\.(?:$type)$/;
129             } elsif (-d $path && $recursive_p) {
130                 push @it, listfiles($path, $type);
131             }
132         }
133     } else {
134         warn_normal "$dir: $!", undef;
135     }
136     return @it;
137 }
138
139 ###############################################################################
140
141 sub mkdir_recursive ($) {
142     my($dir) = @_;
143     local($`, $&, $', $1);
144     $dir = $` if $dir ne /^\/+$/ && $dir =~ /\/+$/;
145     my ($prefix, $basename) = ($dir =~ /\/([^\/]+)$/s)? ($`, $1): ('.', $dir);
146     mkdir_recursive($prefix) if $prefix ne '.' && !-d $prefix;
147     if (!-d $dir) {
148         print STDERR "Making directory $dir...";
149         # creates with rwxrwxr-x permissions
150         mkdir($dir, 0775) || warn_normal "$dir: $!", undef;
151     }
152 }
153
154 ###############################################################################
155
156 sub usage ($) {
157     my($exitcode) = @_;
158     my $h = $exitcode? *STDERR: *STDOUT;
159     print $h <<EOF;
160 Usage: $0 create [OPTION]
161   or:  $0 update [OPTION]
162   or:  $0 install [OPTION]
163   or:  $0 --help
164 Create or update PO files from templates, or install translated templates.
165
166   -i, --input=SOURCE          Get or update strings from SOURCE file.
167                               SOURCE is a directory if -r is also specified.
168   -o, --outputdir=DIRECTORY   Install translation(s) to specified DIRECTORY
169       --pedantic-warnings     Issue warnings even for detected problems
170                               which are likely to be harmless
171   -r, --recursive             SOURCE in the -i option is a directory
172   -s, --str-file=FILE         Specify FILE as the translation (po) file
173                               for input (install) or output (create, update)
174   -x, --exclude=REGEXP        Exclude files matching the given REGEXP
175       --help                  Display this help and exit
176
177 The -o option is ignored for the "create" and "update" actions.
178 Try `perldoc $0' for perhaps more information.
179 EOF
180     exit($exitcode);
181 }
182
183 ###############################################################################
184
185 sub usage_error (;$) {
186     for my $msg (split(/\n/, $_[0])) {
187         print STDERR "$msg\n";
188     }
189     print STDERR "Try `$0 --help' for more information.\n";
190     exit(-1);
191 }
192
193 ###############################################################################
194
195 GetOptions(
196     'input|i=s'                         => \@in_files,
197     'outputdir|o=s'                     => \$out_dir,
198     'recursive|r'                       => \$recursive_p,
199     'str-file|s=s'                      => \$str_file,
200     'exclude|x=s'                       => \@excludes,
201     'pedantic-warnings|pedantic'        => sub { $pedantic_p = 1 },
202     'help'                              => \&usage,
203 ) || usage_error;
204
205 VerboseWarnings::set_application_name $0;
206 VerboseWarnings::set_pedantic_mode $pedantic_p;
207
208 # keep the buggy Locale::PO quiet if it says stupid things
209 $SIG{__WARN__} = sub {
210         my($s) = @_;
211         print STDERR $s unless $s =~ /^Strange line in [^:]+: #~/s
212     };
213
214 my $action = shift or usage_error('You must specify an ACTION.');
215 usage_error('You must at least specify input and string list filenames.')
216     if !@in_files || !defined $str_file;
217
218 # Type match defaults to *.tmpl plus *.inc if not specified
219 $type = "tmpl|inc" if !defined($type);
220
221 # Check the inputs for being files or directories
222 for my $input (@in_files) {
223     usage_error("$input: Input must be a file or directory.\n"
224             . "(Symbolic links are not supported at the moment)")
225         unless -d $input || -f $input;;
226 }
227
228 # Generates the global exclude regular expression
229 $exclude_regex =  '(?:'.join('|', @excludes).')' if @excludes;
230
231 # Generate the list of input files if a directory is specified
232 if (-d $in_files[0]) {
233     die "If you specify a directory as input, you must specify only it.\n"
234             if @in_files > 1;
235
236     # input is a directory, generates list of files to process
237     $in_dir = $in_files[0];
238     $in_dir =~ s/\/$//; # strips the trailing / if any
239     @in_files = listfiles($in_dir, $type);
240 } else {
241     for my $input (@in_files) {
242         die "You cannot specify input files and directories at the same time.\n"
243                 unless -f $input;
244     }
245 }
246
247 # restores the string list from file
248 $href = Locale::PO->load_file_ashash($str_file);
249
250 # guess the charsets. HTML::Templates defaults to iso-8859-1
251 if (defined $href) {
252     die "$str_file: PO file is corrupted, or not a PO file\n"
253             unless defined $href->{'""'};
254     $charset_out = TmplTokenizer::charset_canon $2
255             if $href->{'""'}->msgstr =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/;
256     for my $msgid (keys %$href) {
257         if ($msgid =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/) {
258             my $candidate = TmplTokenizer::charset_canon $2;
259             die "Conflicting charsets in msgid: $charset_in vs $candidate\n"
260                     if defined $charset_in && $charset_in ne $candidate;
261             $charset_in = $candidate;
262         }
263     }
264 }
265 if (!defined $charset_in) {
266     $charset_in = TmplTokenizer::charset_canon 'iso8859-1';
267     warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n";
268 }
269
270 my $xgettext = './xgettext.pl'; # actual text extractor script
271 my $st;
272
273 if ($action eq 'create')  {
274     # updates the list. As the list is empty, every entry will be added
275     if (!-s $str_file) {
276         warn "Removing empty file $str_file\n";
277         unlink $str_file || die "$str_file: $!\n";
278     }
279     die "$str_file: Output file already exists\n" if -f $str_file;
280     my($tmph1, $tmpfile1) = tmpnam();
281     my($tmph2, $tmpfile2) = tmpnam();
282     close $tmph2; # We just want a name
283     # Generate the temporary file that acts as <MODULE>/POTFILES.in
284     for my $input (@in_files) {
285         print $tmph1 "$input\n";
286     }
287     close $tmph1;
288     # Generate the specified po file ($str_file)
289     $st = system ($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2);
290     # Run msgmerge so that the pot file looks like a real pot file
291     # We need to help msgmerge a bit by pre-creating a dummy po file that has
292     # the headers and the "" msgid & msgstr. It will fill in the rest.
293     if ($st == 0) {
294         # Merge the temporary "pot file" with the specified po file ($str_file)
295         # FIXME: msgmerge(1) is a Unix dependency
296         # FIXME: need to check the return value
297         unless (-f $str_file) {
298             local(*INPUT, *OUTPUT);
299             open(INPUT, "<$tmpfile2");
300             open(OUTPUT, ">$str_file");
301             while (<INPUT>) {
302                 print OUTPUT;
303             last if /^\n/s;
304             }
305             close INPUT;
306             close OUTPUT;
307         }
308         $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
309     } else {
310         error_normal "Text extraction failed: $xgettext: $!\n", undef;
311         error_additional "Will not run msgmerge\n", undef;
312     }
313 #   unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
314 #   unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
315
316 } elsif ($action eq 'update') {
317     my($tmph1, $tmpfile1) = tmpnam();
318     my($tmph2, $tmpfile2) = tmpnam();
319     close $tmph2; # We just want a name
320     # Generate the temporary file that acts as <MODULE>/POTFILES.in
321     for my $input (@in_files) {
322         print $tmph1 "$input\n";
323     }
324     close $tmph1;
325     # Generate the temporary file that acts as <MODULE>/<LANG>.pot
326     $st = system($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2,
327             '--po-mode',
328             (defined $charset_in? ('-I', $charset_in): ()),
329             (defined $charset_out? ('-O', $charset_out): ()));
330     if ($st == 0) {
331         # Merge the temporary "pot file" with the specified po file ($str_file)
332         # FIXME: msgmerge(1) is a Unix dependency
333         # FIXME: need to check the return value
334         $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
335     } else {
336         error_normal "Text extraction failed: $xgettext: $!\n", undef;
337         error_additional "Will not run msgmerge\n", undef;
338     }
339 #   unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
340 #   unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
341
342 } elsif ($action eq 'install') {
343     if(!defined($out_dir)) {
344         usage_error("You must specify an output directory when using the install method.");
345     }
346         
347     if ($in_dir eq $out_dir) {
348         warn "You must specify a different input and output directory.\n";
349         exit -1;
350     }
351
352     # Make sure the output directory exists
353     # (It will auto-create it, but for compatibility we should not)
354     -d $out_dir || die "$out_dir: The directory does not exist\n";
355
356     # Try to open the file, because Locale::PO doesn't check :-/
357     open(INPUT, "<$str_file") || die "$str_file: $!\n";
358     close INPUT;
359
360     # creates the new tmpl file using the new translation
361     for my $input (@in_files) {
362         die "Assertion failed"
363                 unless substr($input, 0, length($in_dir) + 1) eq "$in_dir/";
364
365         my $h = TmplTokenizer->new( $input );
366         $h->set_allow_cformat( 1 );
367         VerboseWarnings::set_input_file_name $input;
368
369         my $target = $out_dir . substr($input, length($in_dir));
370         my $targetdir = $` if $target =~ /[^\/]+$/s;
371         mkdir_recursive($targetdir) unless -d $targetdir;
372         print STDERR "Creating $target...\n";
373         open( OUTPUT, ">$target" ) || die "$target: $!\n";
374         text_replace( $h, *OUTPUT );
375         close OUTPUT;
376     }
377
378 } else {
379     usage_error('Unknown action specified.');
380 }
381
382 if ($st == 0) {
383     printf "The %s seems to be successful.\n", $action;
384 } else {
385     printf "%s FAILED.\n", "\u$action";
386 }
387 exit 0;
388
389 ###############################################################################
390
391 =head1 SYNOPSIS
392
393 ./tmpl_process3.pl [ I<tmpl_process.pl options> ]
394
395 =head1 DESCRIPTION
396
397 This is an alternative version of the tmpl_process.pl script,
398 using standard gettext-style PO files.  While there still might
399 be changes made to the way it extracts strings, at this moment
400 it should be stable enough for general use; it is already being
401 used for the Chinese and Polish translations.
402
403 Currently, the create, update, and install actions have all been
404 reimplemented and seem to work.
405
406 =head2 Features
407
408 =over
409
410 =item -
411
412 Translation files in standard Uniforum PO format.
413 All standard tools including all gettext tools,
414 plus PO file editors like kbabel(1) etc.
415 can be used.
416
417 =item -
418
419 Minor changes in whitespace in source templates
420 do not generally require strings to be re-translated.
421
422 =item -
423
424 Able to handle <TMPL_VAR> variables in the templates;
425 <TMPL_VAR> variables are usually extracted in proper context,
426 represented by a short %s placeholder.
427
428 =item -
429
430 Able to handle text input and radio button INPUT elements
431 in the templates; these INPUT elements are also usually
432 extracted in proper context,
433 represented by a short %S or %p placeholder.
434
435 =item -
436
437 Automatic comments in the generated PO files to provide
438 even more context (line numbers, and the names and types
439 of the variables).
440
441 =item -
442
443 The %I<n>$s (or %I<n>$p, etc.) notation can be used
444 for change the ordering of the variables,
445 if such a reordering is required for correct translation.
446
447 =item -
448
449 If a particular <TMPL_VAR> should not appear in the
450 translation, it can be suppressed with the %0.0s notation.
451
452 =item -
453
454 Using the PO format also means translators can add their
455 own comments in the translation files, if necessary.
456
457 =item -
458
459 Create, update, and install actions are all based on the
460 same scanner module. This ensures that update and install
461 have the same idea of what is a translatable string;
462 attribute names in tags, for example, will not be
463 accidentally translated.
464
465 =back
466
467 =head1 NOTES
468
469 Anchors are represented by an <AI<n>> notation.
470 The meaning of this non-standard notation might not be obvious.
471
472 The create action calls xgettext.pl to do the actual work;
473 the update action calls xgettext.pl and msgmerge(1) to do the
474 actual work.
475
476 =head1 BUGS
477
478 xgettext.pl must be present in the current directory; the
479 msgmerge(1) command must also be present in the search path.
480 The script currently does not check carefully whether these
481 dependent commands are present.
482
483 Locale::PO(3) has a lot of bugs. It can neither parse nor
484 generate GNU PO files properly; a couple of workarounds have
485 been written in TmplTokenizer and more is likely to be needed
486 (e.g., to get rid of the "Strange line" warning for #~).
487
488 This script may not work in Windows.
489
490 There are probably some other bugs too, since this has not been
491 tested very much.
492
493 =head1 SEE ALSO
494
495 xgettext.pl,
496 TmplTokenizer.pm,
497 msgmerge(1),
498 Locale::PO(3),
499 translator_doc.txt
500
501 http://www.saas.nsw.edu.au/koha_wiki/index.php?page=DifficultTerms
502
503 =cut