New scripts for translation into Chinese and other languages where English
[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 - Experimental 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( error_normal warn_normal );
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
30 ###############################################################################
31
32 sub find_translation ($) {
33     my($s) = @_;
34     my $key = TmplTokenizer::quote_po($s) if $s =~ /\S/;
35     return defined $href->{$key}
36                 && length Locale::PO->dequote($href->{$key}->msgstr)?
37            Locale::PO->dequote($href->{$key}->msgstr): $s;
38 }
39
40 sub text_replace_tag ($$) {
41     my($t, $attr) = @_;
42     my $it;
43     # value [tag=input], meta
44     my $tag = lc($1) if $t =~ /^<(\S+)/s;
45     my $translated_p = 0;
46     for my $a ('alt', 'content', 'title', 'value') {
47         if ($attr->{$a}) {
48             next if $a eq 'content' && $tag ne 'meta';
49             next if $a eq 'value' && ($tag ne 'input'
50                 || (ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:hidden|radio)$/)); # FIXME
51             my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
52             my($pre, $trimmed, $post) = TmplTokenizer::trim $val;
53             if ($val =~ /\S/s) {
54                 my $s = $pre . find_translation($trimmed) . $post;
55                 if ($attr->{$a}->[1] ne $s) { #FIXME
56                     $attr->{$a}->[1] = $s; # FIXME
57                     $attr->{$a}->[2] = ($s =~ /"/s)? "'$s'": "\"$s\""; #FIXME
58                     $translated_p = 1;
59                 }
60             }
61         }
62     }
63     if ($translated_p) {
64         $it = "<$tag"
65             . join('', map {
66                     sprintf(' %s=%s', $_, $attr->{$_}->[2]) #FIXME
67                 } sort {
68                     $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME
69                 } keys %$attr)
70             . '>';
71     } else {
72         $it = $t;
73     }
74     return $it;
75 }
76
77 sub text_replace (**) {
78     my($h, $output) = @_;
79     for (;;) {
80         my $s = TmplTokenizer::next_token $h;
81     last unless defined $s;
82         my($kind, $t, $attr) = ($s->type, $s->string, $s->attributes);
83         if ($kind eq TmplTokenType::TEXT) {
84             my($pre, $trimmed, $post) = TmplTokenizer::trim $t;
85             print $output $pre, find_translation($trimmed), $post;
86         } elsif ($kind eq TmplTokenType::TEXT_PARAMETRIZED) {
87             my $fmt = find_translation($s->form);
88             print $output TmplTokenizer::parametrize($fmt, map {
89                 my($kind, $t, $attr) = ($_->type, $_->string, $_->attributes);
90                 $kind == TmplTokenType::TAG && %$attr?
91                     text_replace_tag($t, $attr): $t } $s->parameters);
92         } elsif ($kind eq TmplTokenType::TAG && %$attr) {
93             print $output text_replace_tag($t, $attr);
94         } elsif (defined $t) {
95             print $output $t;
96         }
97     }
98 }
99
100 # FIXME: Should we use the GNOME convention of using POTFILES.in instead?
101 sub listfiles ($$) {
102     my($dir, $type) = @_;
103     my @it = ();
104     if (opendir(DIR, $dir)) {
105         my @dirent = readdir DIR;       # because DIR is shared when recursing
106         closedir DIR;
107         for my $dirent (@dirent) {
108             my $path = "$dir/$dirent";
109             if ($dirent =~ /^\./ || $dirent eq 'CVS' || $dirent eq 'RCS'
110             || (defined $exclude_regex && $dirent =~ /^(?:$exclude_regex)$/)) {
111                 ;
112             } elsif (-f $path) {
113                 push @it, $path if !defined $type || $dirent =~ /\.(?:$type)$/;
114             } elsif (-d $path && $recursive_p) {
115                 push @it, listfiles($path, $type);
116             }
117         }
118     } else {
119         warn_normal "$dir: $!", undef;
120     }
121     return @it;
122 }
123
124 ###############################################################################
125
126 sub usage_error (;$) {
127     for my $msg (split(/\n/, $_[0])) {
128         print STDERR "$msg\n";
129     }
130     print STDERR "Try `$0 --help' for more information.\n";
131     exit(-1);
132 }
133
134 ###############################################################################
135
136 GetOptions(
137     'input|i=s'                         => \@in_files,
138     'outputdir|o=s'                     => \$out_dir,
139     'recursive|r'                       => \$recursive_p,
140     'str-file|s=s'                      => \$str_file,
141     'exclude|x=s'                       => \@excludes,
142     'pedantic-warnings|pedantic'        => sub { $pedantic_p = 1 },
143 ) || usage_error;
144
145 VerboseWarnings::set_application_name $0;
146 VerboseWarnings::set_pedantic_mode $pedantic_p;
147
148 my $action = shift or usage_error('You must specify an ACTION.');
149 usage_error('You must at least specify input and string list filenames.')
150     if !@in_files || !defined $str_file;
151
152 # Type match defaults to *.tmpl plus *.inc if not specified
153 $type = "tmpl|inc" if !defined($type);
154
155 # Check the inputs for being files or directories
156 for my $input (@in_files) {
157     usage_error("$input: Input must be a file or directory.\n"
158             . "(Symbolic links are not supported at the moment)")
159         unless -d $input || -f $input;;
160 }
161
162 # Generates the global exclude regular expression
163 $exclude_regex =  '(?:'.join('|', @excludes).')' if @excludes;
164
165 # Generate the list of input files if a directory is specified
166 if (-d $in_files[0]) {
167     die "If you specify a directory as input, you must specify only it.\n"
168             if @in_files > 1;
169
170     # input is a directory, generates list of files to process
171     $in_dir = $in_files[0];
172     $in_dir =~ s/\/$//; # strips the trailing / if any
173     @in_files = listfiles($in_dir, $type);
174 } else {
175     for my $input (@in_files) {
176         die "You cannot specify input files and directories at the same time.\n"
177                 unless -f $input;
178     }
179 }
180
181 if ($action eq 'create')  {
182     # updates the list. As the list is empty, every entry will be added
183     die "$str_file: Output file already exists" if -f $str_file;
184     my($tmph, $tmpfile) = tmpnam();
185     for my $input (@in_files) {
186         print $tmph "$input\n";
187     }
188     close $tmph;
189     system {'./xgettext.pl'} ('xgettext.pl', '-s', '-f', $tmpfile, '-o', $str_file);
190     unlink $tmpfile || warn_normal "$tmpfile: unlink failed: $!\n", undef;
191
192 } elsif ($action eq 'update') {
193     my($tmph1, $tmpfile1) = tmpnam();
194     my($tmph2, $tmpfile2) = tmpnam();
195     close $tmph2; # We just want a name
196     for my $input (@in_files) {
197         print $tmph1 "$input\n";
198     }
199     close $tmph1;
200     system('./xgettext.pl', '-s', '-f', $tmpfile1, '-o', $tmpfile2);
201     system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
202     unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
203     unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
204
205 } elsif ($action eq 'install') {
206     if(!defined($out_dir)) {
207         usage_error("You must specify an output directory when using the install method.");
208     }
209         
210     if ($in_dir eq $out_dir) {
211         warn "You must specify a different input and output directory.\n";
212         exit -1;
213     }
214
215     # Make sure the output directory exists
216     # (It will auto-create it, but for compatibility we should not)
217     -d $out_dir || die "$out_dir: The directory does not exist\n";
218
219     # Try to open the file, because Locale::PO doesn't check :-/
220     open(INPUT, "<$str_file") || die "$str_file: $!\n";
221     close INPUT;
222
223     # restores the string list from file
224     $href = Locale::PO->load_file_ashash($str_file);
225
226     # creates the new tmpl file using the new translation
227     for my $input (@in_files) {
228         die "Assertion failed"
229                 unless substr($input, 0, length($in_dir) + 1) eq "$in_dir/";
230
231         my $h = TmplTokenizer->new( $input );
232         $h->set_allow_cformat( 1 );
233         VerboseWarnings::set_input_file_name $input;
234
235         my $target = $out_dir . substr($input, length($in_dir));
236         my $targetdir = $` if $target =~ /[^\/]+$/s;
237         if (!-d $targetdir) {
238             print STDERR "Making directory $targetdir...";
239             # creates with rwxrwxr-x permissions
240             mkdir($targetdir, 0775) || warn_normal "$targetdir: $!", undef;
241         }
242         print STDERR "Creating $target...\n";
243         open( OUTPUT, ">$target" ) || die "$target: $!\n";
244         text_replace( $h, *OUTPUT );
245         close OUTPUT;
246     }
247
248 } else {
249     usage_error('Unknown action specified.');
250 }
251 exit 0;
252
253 ###############################################################################
254
255 =head1 SYNOPSIS
256
257 ./tmpl_process3.pl [ I<tmpl_process.pl options> ]
258
259 =head1 DESCRIPTION
260
261 This is an experimental version of the tmpl_process.pl script,
262 using standard gettext-style PO files.
263
264 Currently, the create, update, and install actions have all been
265 reimplemented and seem to work.
266
267 The create action calls xgettext.pl to do the actual work;
268 the update action calls xgettext.pl and msgmerge(1) to do the
269 actual work.
270
271 The script can detect <TMPL_VAR> directives embedded inside what
272 appears to be a full sentence (this actual work being done by
273 TmplTokenizer(3)); these larger patterns appear in the translation
274 file as c-format strings with %s.
275
276 =head1 BUGS
277
278 The --help option has not been implemented yet.
279
280 There are probably some real bugs too, since this has not been
281 tested very much.
282
283 xgettext.pl must be present in the current directory; the
284 msgmerge(1) command must also be present in the search path.
285 The script currently does not check carefully whether these
286 dependent commands are present.
287
288 Locale::PO(3) has a lot of bugs. It can neither parse nor
289 generate GNU PO files properly; a couple of workarounds have
290 been written in TmplTokenizer and more is likely to be needed
291 (e.g., to get rid of the "Strange line" warning for #~).
292
293 =head1 SEE ALSO
294
295 xgettext.pl,
296 msgmerge(1),
297 Locale::PO(3),
298 translator_doc.txt
299
300 =cut