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
9 tmpl_process3.pl - Alternative version of tmpl_process.pl
10 using gettext-compatible translation files
17 use File::Temp qw( :POSIX );
19 use VerboseWarnings qw( :warn :die );
21 ###############################################################################
23 use vars qw( @in_files $in_dir $str_file $out_dir $quiet );
24 use vars qw( @excludes $exclude_regex );
25 use vars qw( $recursive_p );
26 use vars qw( $pedantic_p );
28 use vars qw( $type ); # file extension (DOS form without the dot) to match
29 use vars qw( $charset_in $charset_out );
31 ###############################################################################
33 sub find_translation ($) {
37 $key = TmplTokenizer::string_canon($key);
38 $key = TmplTokenizer::charset_convert($key, $charset_in, $charset_out);
39 $key = TmplTokenizer::quote_po($key);
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;
47 sub text_replace_tag ($$) {
50 # value [tag=input], meta
51 my $tag = lc($1) if $t =~ /^<(\S+)/s;
53 for my $a ('alt', 'content', 'title', 'value') {
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
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
72 sprintf(' %s=%s', $_, $attr->{$_}->[2]) #FIXME
74 $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME
83 sub text_replace (**) {
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 {
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
104 printf $output "%s%s%s", $t->[2], find_translation $t->[3],
107 print $output $t->[1];
110 } elsif (defined $t) {
116 sub listfiles ($$$) {
117 my($dir, $type, $action) = @_;
119 if (opendir(DIR, $dir)) {
120 my @dirent = readdir DIR; # because DIR is shared when recursing
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)$/)) {
128 push @it, $path if (!defined $type || $dirent =~ /\.(?:$type)$/) || $action eq 'install';
129 } elsif (-d $path && $recursive_p) {
130 push @it, listfiles($path, $type, $action);
134 warn_normal "$dir: $!", undef;
139 ###############################################################################
141 sub mkdir_recursive ($) {
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;
148 print STDERR "Making directory $dir..." unless $quiet;
149 # creates with rwxrwxr-x permissions
150 mkdir($dir, 0775) || warn_normal "$dir: $!", undef;
154 ###############################################################################
158 my $h = $exitcode? *STDERR: *STDOUT;
160 Usage: $0 create [OPTION]
161 or: $0 update [OPTION]
162 or: $0 install [OPTION]
164 Create or update PO files from templates, or install translated templates.
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 -q, --quiet no output to screen (except for errors)
178 The -o option is ignored for the "create" and "update" actions.
179 Try `perldoc $0 for perhaps more information.
184 ###############################################################################
186 sub usage_error (;$) {
187 for my $msg (split(/\n/, $_[0])) {
188 print STDERR "$msg\n";
190 print STDERR "Try `$0 --help for more information.\n";
194 ###############################################################################
197 'input|i=s' => \@in_files,
198 'outputdir|o=s' => \$out_dir,
199 'recursive|r' => \$recursive_p,
200 'str-file|s=s' => \$str_file,
201 'exclude|x=s' => \@excludes,
202 'quiet|q' => \$quiet,
203 'pedantic-warnings|pedantic' => sub { $pedantic_p = 1 },
207 VerboseWarnings::set_application_name $0;
208 VerboseWarnings::set_pedantic_mode $pedantic_p;
210 # keep the buggy Locale::PO quiet if it says stupid things
211 $SIG{__WARN__} = sub {
213 print STDERR $s unless $s =~ /^Strange line in [^:]+: #~/s
216 my $action = shift or usage_error('You must specify an ACTION.');
217 usage_error('You must at least specify input and string list filenames.')
218 if !@in_files || !defined $str_file;
220 # Type match defaults to *.tmpl plus *.inc if not specified
221 $type = "tmpl|inc" if !defined($type);
223 # Check the inputs for being files or directories
224 for my $input (@in_files) {
225 usage_error("$input: Input must be a file or directory.\n"
226 . "(Symbolic links are not supported at the moment)")
227 unless -d $input || -f $input;;
230 # Generates the global exclude regular expression
231 $exclude_regex = '(?:'.join('|', @excludes).')' if @excludes;
233 # Generate the list of input files if a directory is specified
234 if (-d $in_files[0]) {
235 die "If you specify a directory as input, you must specify only it.\n"
238 # input is a directory, generates list of files to process
239 $in_dir = $in_files[0];
240 $in_dir =~ s/\/$//; # strips the trailing / if any
241 @in_files = listfiles($in_dir, $type, $action);
243 for my $input (@in_files) {
244 die "You cannot specify input files and directories at the same time.\n"
249 # restores the string list from file
250 $href = Locale::PO->load_file_ashash($str_file);
252 # guess the charsets. HTML::Templates defaults to iso-8859-1
254 die "$str_file: PO file is corrupted, or not a PO file\n"
255 unless defined $href->{'""'};
256 $charset_out = TmplTokenizer::charset_canon $2
257 if $href->{'""'}->msgstr =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/;
258 for my $msgid (keys %$href) {
259 if ($msgid =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/) {
260 my $candidate = TmplTokenizer::charset_canon $2;
261 die "Conflicting charsets in msgid: $charset_in vs $candidate\n"
262 if defined $charset_in && $charset_in ne $candidate;
263 $charset_in = $candidate;
267 if (!defined $charset_in) {
268 $charset_in = TmplTokenizer::charset_canon 'iso8859-1';
269 warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n";
272 my $xgettext = './xgettext.pl'; # actual text extractor script
275 if ($action eq 'create') {
276 # updates the list. As the list is empty, every entry will be added
278 warn "Removing empty file $str_file\n";
279 unlink $str_file || die "$str_file: $!\n";
281 die "$str_file: Output file already exists\n" if -f $str_file;
282 my($tmph1, $tmpfile1) = tmpnam();
283 my($tmph2, $tmpfile2) = tmpnam();
284 close $tmph2; # We just want a name
285 # Generate the temporary file that acts as <MODULE>/POTFILES.in
286 for my $input (@in_files) {
287 print $tmph1 "$input\n";
290 # Generate the specified po file ($str_file)
291 $st = system ($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2);
292 # Run msgmerge so that the pot file looks like a real pot file
293 # We need to help msgmerge a bit by pre-creating a dummy po file that has
294 # the headers and the "" msgid & msgstr. It will fill in the rest.
296 # Merge the temporary "pot file" with the specified po file ($str_file)
297 # FIXME: msgmerge(1) is a Unix dependency
298 # FIXME: need to check the return value
299 unless (-f $str_file) {
300 local(*INPUT, *OUTPUT);
301 open(INPUT, "<$tmpfile2");
302 open(OUTPUT, ">$str_file");
310 $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
312 error_normal "Text extraction failed: $xgettext: $!\n", undef;
313 error_additional "Will not run msgmerge\n", undef;
315 # unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
316 # unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
318 } elsif ($action eq 'update') {
319 my($tmph1, $tmpfile1) = tmpnam();
320 my($tmph2, $tmpfile2) = tmpnam();
321 close $tmph2; # We just want a name
322 # Generate the temporary file that acts as <MODULE>/POTFILES.in
323 for my $input (@in_files) {
324 print $tmph1 "$input\n";
327 # Generate the temporary file that acts as <MODULE>/<LANG>.pot
328 $st = system($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2,
330 (defined $charset_in? ('-I', $charset_in): ()),
331 (defined $charset_out? ('-O', $charset_out): ()));
333 # Merge the temporary "pot file" with the specified po file ($str_file)
334 # FIXME: msgmerge(1) is a Unix dependency
335 # FIXME: need to check the return value
336 $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
338 error_normal "Text extraction failed: $xgettext: $!\n", undef;
339 error_additional "Will not run msgmerge\n", undef;
341 # unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
342 # unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
344 } elsif ($action eq 'install') {
345 if(!defined($out_dir)) {
346 usage_error("You must specify an output directory when using the install method.");
349 if ($in_dir eq $out_dir) {
350 warn "You must specify a different input and output directory.\n";
354 # Make sure the output directory exists
355 # (It will auto-create it, but for compatibility we should not)
356 -d $out_dir || die "$out_dir: The directory does not exist\n";
358 # Try to open the file, because Locale::PO doesn't check :-/
359 open(INPUT, "<$str_file") || die "$str_file: $!\n";
362 # creates the new tmpl file using the new translation
363 for my $input (@in_files) {
364 die "Assertion failed"
365 unless substr($input, 0, length($in_dir) + 1) eq "$in_dir/";
366 # print "$input / $type\n";
367 if (!defined $type || $input =~ /\.(?:$type)$/) {
368 my $h = TmplTokenizer->new( $input );
369 $h->set_allow_cformat( 1 );
370 VerboseWarnings::set_input_file_name $input;
372 my $target = $out_dir . substr($input, length($in_dir));
373 my $targetdir = $` if $target =~ /[^\/]+$/s;
374 mkdir_recursive($targetdir) unless -d $targetdir;
375 print STDERR "Creating $target...\n" unless $quiet;
376 open( OUTPUT, ">$target" ) || die "$target: $!\n";
377 text_replace( $h, *OUTPUT );
380 # just copying the file
381 my $target = $out_dir . substr($input, length($in_dir));
382 my $targetdir = $` if $target =~ /[^\/]+$/s;
383 mkdir_recursive($targetdir) unless -d $targetdir;
384 system("cp -f $input $target");
385 print STDERR "Copying $input...\n" unless $quiet;
390 usage_error('Unknown action specified.');
394 printf "The %s seems to be successful.\n", $action unless $quiet;
396 printf "%s FAILED.\n", "\u$action" unless $quiet;
400 ###############################################################################
404 ./tmpl_process3.pl [ I<tmpl_process.pl options> ]
408 This is an alternative version of the tmpl_process.pl script,
409 using standard gettext-style PO files. While there still might
410 be changes made to the way it extracts strings, at this moment
411 it should be stable enough for general use; it is already being
412 used for the Chinese and Polish translations.
414 Currently, the create, update, and install actions have all been
415 reimplemented and seem to work.
423 Translation files in standard Uniforum PO format.
424 All standard tools including all gettext tools,
425 plus PO file editors like kbabel(1) etc.
430 Minor changes in whitespace in source templates
431 do not generally require strings to be re-translated.
435 Able to handle <TMPL_VAR> variables in the templates;
436 <TMPL_VAR> variables are usually extracted in proper context,
437 represented by a short %s placeholder.
441 Able to handle text input and radio button INPUT elements
442 in the templates; these INPUT elements are also usually
443 extracted in proper context,
444 represented by a short %S or %p placeholder.
448 Automatic comments in the generated PO files to provide
449 even more context (line numbers, and the names and types
454 The %I<n>$s (or %I<n>$p, etc.) notation can be used
455 for change the ordering of the variables,
456 if such a reordering is required for correct translation.
460 If a particular <TMPL_VAR> should not appear in the
461 translation, it can be suppressed with the %0.0s notation.
465 Using the PO format also means translators can add their
466 own comments in the translation files, if necessary.
470 Create, update, and install actions are all based on the
471 same scanner module. This ensures that update and install
472 have the same idea of what is a translatable string;
473 attribute names in tags, for example, will not be
474 accidentally translated.
480 Anchors are represented by an <AI<n>> notation.
481 The meaning of this non-standard notation might not be obvious.
483 The create action calls xgettext.pl to do the actual work;
484 the update action calls xgettext.pl and msgmerge(1) to do the
489 xgettext.pl must be present in the current directory; the
490 msgmerge(1) command must also be present in the search path.
491 The script currently does not check carefully whether these
492 dependent commands are present.
494 Locale::PO(3) has a lot of bugs. It can neither parse nor
495 generate GNU PO files properly; a couple of workarounds have
496 been written in TmplTokenizer and more is likely to be needed
497 (e.g., to get rid of the "Strange line" warning for #~).
499 This script may not work in Windows.
501 There are probably some other bugs too, since this has not been
512 http://www.saas.nsw.edu.au/koha_wiki/index.php?page=DifficultTerms