1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
|
#!/usr/bin/perl -w
require Exporter;
package Locale::Po4a::TransTractor;
use DynaLoader;
use 5.16.0;
use strict;
use warnings;
use subs qw(makespace);
use vars qw($VERSION @ISA @EXPORT);
$VERSION = "0.73";
@ISA = qw(DynaLoader);
@EXPORT = qw(new process translate
read write readpo writepo
getpoout setpoout get_in_charset get_out_charset handle_yaml);
# Try to use a C extension if present.
eval("bootstrap Locale::Po4a::TransTractor $VERSION");
use Carp qw(croak confess);
use Locale::Po4a::Po;
use Locale::Po4a::Common;
use File::Path; # mkdir before write
use File::Spec;
=encoding UTF-8
=head1 NAME
Locale::Po4a::TransTractor - generic trans(lator ex)tractor.
=head1 DESCRIPTION
The po4a (PO for anything) project goal is to ease translations (and more
interestingly, the maintenance of translations) using gettext tools on
areas where they were not expected like documentation.
This class is the ancestor of every po4a parser used to parse a document, to
search translatable strings, to extract them to a PO file and to replace them by
their translation in the output document.
More formally, it takes the following arguments as input:
=over 2
=item -
a document to translate;
=item -
a PO file containing the translations to use.
=back
As output, it produces:
=over 2
=item -
another PO file, resulting of the extraction of translatable strings from
the input document;
=item -
a translated document, with the same structure than the one in input, but
with all translatable strings replaced with the translations found in the
PO file provided in input.
=back
Here is a graphical representation of this:
Input document --\ /---> Output document
\ / (translated)
+-> parse() function -----+
/ \
Input PO --------/ \---> Output PO
(extracted)
=head1 FUNCTIONS YOUR PARSER SHOULD OVERRIDE
=over 4
=item parse()
This is where all the work takes place: the parsing of input documents, the
generation of output, and the extraction of the translatable strings. This
is pretty simple using the provided functions presented in the section
B<INTERNAL FUNCTIONS> below. See also the B<SYNOPSIS>, which presents an
example.
This function is called by the process() function below, but if you choose
to use the new() function, and to add content manually to your document,
you will have to call this function yourself.
=item docheader()
This function returns the header we should add to the produced document,
quoted properly to be a comment in the target language. See the section
B<Educating developers about translations>, from L<po4a(7)|po4a.7>, for what
it is good for.
=back
=cut
sub docheader { }
sub parse { }
=head1 SYNOPSIS
The following example parses a list of paragraphs beginning with "<p>". For the sake
of simplicity, we assume that the document is well formatted, i.e. that '<p>'
tags are the only tags present, and that this tag is at the very beginning
of each paragraph.
sub parse {
my $self = shift;
PARAGRAPH: while (1) {
my ($paragraph,$pararef)=("","");
my $first=1;
my ($line,$lref)=$self->shiftline();
while (defined($line)) {
if ($line =~ m/<p>/ && !$first--; ) {
# Not the first time we see <p>.
# Reput the current line in input,
# and put the built paragraph to output
$self->unshiftline($line,$lref);
# Now that the document is formed, translate it:
# - Remove the leading tag
$paragraph =~ s/^<p>//s;
# - push to output the leading tag (untranslated) and the
# rest of the paragraph (translated)
$self->pushline( "<p>"
. $self->translate($paragraph,$pararef)
);
next PARAGRAPH;
} else {
# Append to the paragraph
$paragraph .= $line;
$pararef = $lref unless(length($pararef));
}
# Reinit the loop
($line,$lref)=$self->shiftline();
}
# Did not get a defined line? End of input file.
return;
}
}
Once you've implemented the parse function, you can use your document
class, using the public interface presented in the next section.
=head1 PUBLIC INTERFACE for scripts using your parser
=head2 Constructor
=over 4
=item process(%)
This function can do all you need to do with a po4a document in one
invocation. Its arguments must be packed as a hash. ACTIONS:
=over 3
=item a.
Reads all the PO files specified in po_in_name
=item b.
Reads all original documents specified in file_in_name
=item c.
Parses the document
=item d.
Reads and applies all the addenda specified
=item e.
Writes the translated document to file_out_name (if given)
=item f.
Writes the extracted PO file to po_out_name (if given)
=back
ARGUMENTS, beside the ones accepted by new() (with expected type):
=over 4
=item file_in_name (@)
List of filenames where we should read the input document.
=item file_in_charset ($)
Charset used in the input document (if it isn't specified, use UTF-8).
=item file_out_name ($)
Filename where we should write the output document.
=item file_out_charset ($)
Charset used in the output document (if it isn't specified, use UTF-8).
=item po_in_name (@)
List of filenames where we should read the input PO files from, containing
the translation which will be used to translate the document.
=item po_out_name ($)
Filename where we should write the output PO file, containing the strings
extracted from the input document.
=item addendum (@)
List of filenames where we should read the addenda from.
=item addendum_charset ($)
Charset for the addenda.
=back
=item new(%)
Create a new po4a document. Accepted options (in the hash passed as a parameter):
=over 4
=item verbose ($)
Sets the verbosity.
=item debug ($)
Sets the debugging.
=item wrapcol ($)
The column at which we should wrap text in output document (default: 76).
The negative value means not to wrap lines at all.
=back
Also it accepts next options for underlying Po-files: B<porefs>,
B<copyright-holder>, B<msgid-bugs-address>, B<package-name>,
B<package-version>, B<wrap-po>.
=cut
sub process {
my $self = shift;
## Parameters are passed as an hash to avoid long and error-prone parameter lists
my %params = @_;
# Parameter checking
foreach ( keys %params ) {
confess "Unexpected parameter to process(): $_. Please report that bug."
unless ( $_ eq 'po_in_name'
|| $_ eq 'po_out_name'
|| $_ eq 'file_in_name'
|| $_ eq 'file_in_charset'
|| $_ eq 'file_out_name'
|| $_ eq 'file_out_charset'
|| $_ eq 'addendum'
|| $_ eq 'addendum_charset'
|| $_ eq 'srcdir'
|| $_ eq 'destdir'
|| $_ eq 'calldir' );
}
$self->{TT}{'file_in_charset'} = $params{'file_in_charset'} // 'UTF-8';
$self->{TT}{'file_out_charset'} = $params{'file_out_charset'} // 'UTF-8';
$self->{TT}{'addendum_charset'} = $params{'addendum_charset'};
our ( $destdir, $srcdir, $calldir ) = ( $params{'destdir'}, $params{'srcdir'}, $params{'calldir'} );
sub _input_file {
my $filename = $_[0];
return $filename if ( File::Spec->file_name_is_absolute($filename) );
foreach ( ( $destdir, $srcdir, $calldir ) ) {
next unless defined $_;
my $p = File::Spec->catfile( $_, $filename );
return $p if -e $p;
}
return $filename;
}
sub _output_file {
my $filename = $_[0];
return $filename if ( File::Spec->file_name_is_absolute($filename) );
foreach ( ( $destdir, $calldir ) ) {
next unless defined $_;
return File::Spec->catfile( $_, $filename ) if -d $_ and -w $_;
}
return $filename;
}
foreach my $file ( @{ $params{'po_in_name'} } ) {
my $infile = _input_file($file);
print STDERR wrap_mod( "po4a::transtractor::process", "Read PO file $infile" )
if $self->debug();
$self->readpo($infile);
}
foreach my $file ( @{ $params{'file_in_name'} } ) {
my $infile = _input_file($file);
print STDERR wrap_mod( "po4a::transtractor::process", "Read document $infile" )
if $self->debug();
$self->read( $infile, $file, $params{'file_in_charset'} );
}
print STDERR wrap_mod( "po4a::transtractor::process", "Call parse()" ) if $self->debug();
$self->parse();
print STDERR wrap_mod( "po4a::transtractor::process", "Done parse()" ) if $self->debug();
foreach my $file ( @{ $params{'addendum'} } ) {
my $infile = _input_file($file);
print STDERR wrap_mod( "po4a::transtractor::process", "Apply addendum $infile" )
if $self->debug();
$self->addendum($file) || die "An addendum failed\n";
}
if ( defined $params{'file_out_name'} ) {
my $outfile = _output_file( $params{'file_out_name'} );
print STDERR wrap_mod( "po4a::transtractor::process", "Write document $outfile" )
if $self->debug();
$self->write( $outfile, $self->{TT}{'file_out_charset'} );
}
if ( defined $params{'po_out_name'} ) {
my $outfile = _output_file( $params{'po_out_name'} );
print STDERR wrap_mod( "po4a::transtractor::process", "Write PO file $outfile" )
if $self->debug();
$self->writepo($outfile);
}
return $self;
}
sub new {
## Determine if we were called via an object-ref or a classname
my $this = shift;
my $class = ref($this) || $this;
my $self = {};
my %options = @_;
## Bless ourselves into the desired class and perform any initialization
bless $self, $class;
## initialize the plugin
# prevent the plugin from croaking on the options intended for Po.pm or ourself
$self->{options}{'porefs'} = '';
$self->{options}{'copyright-holder'} = '';
$self->{options}{'msgid-bugs-address'} = '';
$self->{options}{'package-name'} = '';
$self->{options}{'package-version'} = '';
$self->{options}{'wrap-po'} = '';
$self->{options}{'wrapcol'} = '';
# let the plugin parse the options and such
$self->initialize(%options);
## Create our private data
my %po_options;
$po_options{'porefs'} = $options{'porefs'};
$po_options{'copyright-holder'} = $options{'copyright-holder'};
$po_options{'msgid-bugs-address'} = $options{'msgid-bugs-address'};
$po_options{'package-name'} = $options{'package-name'};
$po_options{'package-version'} = $options{'package-version'};
$po_options{'wrap-po'} = $options{'wrap-po'};
# private data
$self->{TT} = ();
$self->{TT}{po_in} = Locale::Po4a::Po->new( \%po_options );
$self->{TT}{po_out} = Locale::Po4a::Po->new( \%po_options );
# Warning, $self->{TT}{doc_in} is an array of array:
# The document is split on lines, and for each array in array
# [0] is the line content, [1] is the reference $filename:$linenum
$self->{TT}{doc_in} = ();
$self->{TT}{doc_out} = ();
if ( defined $options{'verbose'} ) {
$self->{TT}{verbose} = $options{'verbose'};
}
if ( defined $options{'debug'} ) {
$self->{TT}{debug} = $options{'debug'};
}
if ( defined $options{'wrapcol'} ) {
if ( $options{'wrapcol'} < 0 ) {
$self->{TT}{wrapcol} = 'Inf';
} else {
$self->{TT}{wrapcol} = $options{'wrapcol'};
}
} else {
$self->{TT}{wrapcol} = 76;
}
return $self;
}
=back
=head2 Manipulating document files
=over 4
=item read($$$)
Add another input document data at the end of the existing array C<< @{$self->{TT}{doc_in}} >>.
This function takes two mandatory arguments and an optional one.
* The filename to read on disk;
* The name to use as filename when building the reference in the PO file;
* The charset to use to read that file (UTF-8 by default)
This array C<< @{$self->{TT}{doc_in}} >> holds this input document data as an
array of strings with alternating meanings.
* The string C<$textline> holding each line of the input text data.
* The string C<< $filename:$linenum >> holding its location and called as
"reference" (C<linenum> starts with 1).
Please note that it does not parse anything. You should use the parse()
function when you're done with packing input files into the document.
=cut
sub read() {
my $self = shift;
my $filename = shift or confess "Cannot read from a file without filename";
my $refname = shift or confess "Cannot read from a file without refname";
my $charset = shift || 'UTF-8';
my $linenum = 0;
use warnings FATAL => 'utf8';
use Encode qw(:fallbacks);
use PerlIO::encoding;
$PerlIO::encoding::fallback = FB_CROAK;
my $fh;
open( $fh, "<:encoding($charset)", $filename )
or croak wrap_msg( dgettext( "po4a", "Cannot read from %s: %s" ), $filename, $! );
# If we see a BOM while not in UTF-8, we want to croak. But this code is in an eval to deal with
# encoding issues. So save the BOM error until after the eval block
my $BOM_detected = 0;
eval {
while ( defined( my $textline = <$fh> ) ) {
$linenum++;
if ( $linenum == 1 && $textline =~ m/^\N{BOM}/ ) { # UTF-8 BOM detected
$BOM_detected = 1 if ( uc($charset) ne 'UTF-8' ); # Save the error message for after the eval{} bloc
$textline =~ s/^\N{BOM}//;
}
my $ref = "$refname:$linenum";
$textline =~ s/\r$//;
my @entry = ( $textline, $ref );
push @{ $self->{TT}{doc_in} }, @entry;
}
};
my $error = $@;
if ( length($error) ) {
chomp $error;
die wrap_msg(
dgettext(
"po4a",
"Malformed encoding while reading from file %s with charset %s: %s\nIf %s is not the expected charset, you need to configure the right one with with --master-charset or other similar flags."
),
$filename,
$charset, $error, $charset
);
}
# Croak if we need to
if ($BOM_detected) {
croak wrap_msg(
dgettext(
"po4a",
"The file %s starts with a BOM char indicating that its encoding is UTF-8, but you specified %s instead."
),
$filename,
$charset
);
}
close $fh
or croak wrap_msg( dgettext( "po4a", "Cannot close %s after reading: %s" ), $filename, $! );
}
=item write($)
Write the translated document to the given filename.
This translated document data are provided by:
* C<< $self->docheader() >> holding the header text for the plugin, and
* C<< @{$self->{TT}{doc_out}} >> holding each line of the main translated text in the array.
=cut
sub write {
my $self = shift;
my $filename = shift or confess "Cannot write to a file without filename";
my $charset = shift || 'UTF-8';
use warnings FATAL => 'utf8';
my $fh;
if ( $filename eq '-' ) {
$fh = \*STDOUT;
} else {
# make sure the directory in which we should write the localized file exists
my $dir = $filename;
if ( $dir =~ m|/| ) {
$dir =~ s|/[^/]*$||;
File::Path::mkpath( $dir, 0, 0755 ) # Croaks on error
if ( length($dir) && !-e $dir );
}
open( $fh, ">:encoding($charset)", $filename )
or croak wrap_msg( dgettext( "po4a", "Cannot write to %s: %s" ), $filename, $! );
}
map { print $fh $_ } $self->docheader();
eval {
map { print $fh $_ } @{ $self->{TT}{doc_out} };
# we use the "eval {} or do {}" approach to deal with exceptions, cf https://perlmaven.com/fatal-errors-in-external-modules
# but we want it to fail only if there is an error. It seems to be some cases where "map" returns false even if there is no error.
# Thus this final 1 to evaluate to true in absence of error.
1;
} or do {
my $error = $@ || 'Unknown failure';
chomp $error;
if ( $charset ne 'UTF-8' && $error =~ /^"\\x\{([^"}]*)\}"/ ) {
# Attempt to write the char that cannot be written. Very fragile code
binmode STDERR, ':encoding(UTF-8)';
my $char = chr( hex($1) );
die wrap_msg(
dgettext(
"po4a",
"Malformed encoding while writing char '%s' to file %s with charset %s: %s\nIf %s is not the expected charset, you need to configure the right one with with --localized-charset or other similar flags."
),
$char,
$filename,
$charset, $error, $charset
);
} else {
die wrap_msg(
dgettext(
"po4a",
"Malformed encoding while writing to file %s with charset %s: %s\nIf %s is not the expected charset, you need to configure the right one with with --localized-charset or other similar flags."
),
$filename,
$charset, $error, $charset
);
}
};
if ( $filename ne '-' ) {
close $fh or croak wrap_msg( dgettext( "po4a", "Cannot close %s after writing: %s" ), $filename, $! );
}
}
=back
=head2 Manipulating PO files
=over 4
=item readpo($)
Add the content of a file (which name is passed as argument) to the
existing input PO. The old content is not discarded.
=item writepo($)
Write the extracted PO file to the given filename.
=item stats()
Returns some statistics about the translation done so far. Please note that
it's not the same statistics than the one printed by msgfmt
--statistic. Here, it's stats about recent usage of the PO file, while
msgfmt reports the status of the file. It is a wrapper to the
Locale::Po4a::Po::stats_get function applied to the input PO file. Example
of use:
[normal use of the po4a document...]
($percent,$hit,$queries) = $document->stats();
print "We found translations for $percent\% ($hit from $queries) of strings.\n";
=back
=cut
sub getpoout {
return $_[0]->{TT}{po_out};
}
sub setpoout {
$_[0]->{TT}{po_out} = $_[1];
}
sub readpo {
$_[0]->{TT}{po_in}->read( $_[1] );
}
sub writepo {
$_[0]->{TT}{po_out}->write( $_[1] );
}
sub stats {
return $_[0]->{TT}{po_in}->stats_get();
}
=head2 Manipulating addenda
=over 4
=item addendum($)
Please refer to L<po4a(7)|po4a.7> for more information on what addenda are,
and how translators should write them. To apply an addendum to the translated
document, simply pass its filename to this function and you are done ;)
This function returns a non-null integer on error.
=cut
# Internal function to read the header.
sub addendum_parse {
my $filename = shift;
my $charset = shift || 'UTF-8';
my $header;
my ( $errcode, $mode, $position, $boundary, $bmode, $content ) = ( 1, "", "", "", "", "" );
unless ( open( INS, "<:encoding($charset)", $filename ) ) {
warn wrap_msg( dgettext( "po4a", "Cannot read from %s: %s" ), $filename, $! );
goto END_PARSE_ADDFILE;
}
$PerlIO::encoding::fallback = FB_CROAK;
eval {
unless ( defined( $header = <INS> ) && $header ) {
warn wrap_msg( dgettext( "po4a", "Cannot read po4a header from %s." ), $filename );
goto END_PARSE_ADDFILE;
}
} or do {
my $error = $@ || 'Unknown failure';
chomp $error;
die wrap_msg(
dgettext(
"po4a",
"Malformed encoding while reading from file %s with charset %s: %s\nIf %s is not the expected charset, you need to configure the right one with with --master-charset or other similar flags."
),
$filename,
$charset, $error, $charset
);
};
unless ( $header =~ s/PO4A-HEADER://i ) {
warn wrap_msg( dgettext( "po4a", "First line of %s does not look like a po4a header." ), $filename );
goto END_PARSE_ADDFILE;
}
foreach my $part ( split( /;/, $header ) ) {
unless ( $part =~ m/^\s*([^=]*)=(.*)$/ ) {
warn wrap_msg( dgettext( "po4a", "Syntax error in po4a header of %s, near \"%s\"" ), $filename, $part );
goto END_PARSE_ADDFILE;
}
my ( $key, $value ) = ( $1, $2 );
$key = lc($key);
if ( $key eq 'mode' ) {
$mode = lc($value);
} elsif ( $key eq 'position' ) {
$position = $value;
} elsif ( $key eq 'endboundary' ) {
$boundary = $value;
$bmode = 'after';
} elsif ( $key eq 'beginboundary' ) {
$boundary = $value;
$bmode = 'before';
} else {
warn wrap_msg( dgettext( "po4a", "Invalid argument in the po4a header of %s: %s" ), $filename, $key );
goto END_PARSE_ADDFILE;
}
}
unless ( length($mode) ) {
warn wrap_msg( dgettext( "po4a", "The po4a header of %s does not define the mode." ), $filename );
goto END_PARSE_ADDFILE;
}
unless ( $mode eq "before" || $mode eq "after" || $mode eq "eof" ) {
warn wrap_msg(
dgettext(
"po4a",
"Mode invalid in the po4a header of %s: should be 'before', 'after' or 'eof'. Instead, it is '%s'."
),
$filename,
$mode
);
goto END_PARSE_ADDFILE;
}
unless ( length($position) || $mode eq "eof" ) {
warn wrap_msg( dgettext( "po4a", "The po4a header of %s does not define the position." ), $filename );
goto END_PARSE_ADDFILE;
}
if ( $mode eq "after" && length($boundary) == 0 ) {
warn wrap_msg( dgettext( "po4a", "No ending boundary given in the po4a header, but mode=after." ) );
goto END_PARSE_ADDFILE;
}
if ( $mode eq "eof" && length($position) ) {
warn wrap_msg( dgettext( "po4a", "No position needed when mode=eof." ) );
goto END_PARSE_ADDFILE;
}
if ( $mode eq "eof" && length($boundary) ) {
warn wrap_msg( dgettext( "po4a", "No ending boundary needed when mode=eof." ) );
goto END_PARSE_ADDFILE;
}
eval {
while ( defined( my $line = <INS> ) ) {
$content .= $line;
}
};
my $error = $@;
if ( length($error) ) {
chomp $error;
die wrap_msg(
dgettext(
"po4a",
"Malformed encoding while reading from file %s with charset %s: %s\nIf %s is not the expected charset, you need to configure the right one with with --master-charset or other similar flags."
),
$filename,
$charset, $error, $charset
);
}
close INS;
$errcode = 0;
END_PARSE_ADDFILE:
return ( $errcode, $mode, $position, $boundary, $bmode, $content );
}
sub mychomp {
my ($str) = shift;
chomp($str);
return $str;
}
sub addendum {
my ( $self, $filename ) = @_;
print STDERR wrap_mod( "po4a::transtractor::addendum", "Apply addendum %s", $filename )
if $self->debug();
unless ($filename) {
warn wrap_msg( dgettext( "po4a", "Cannot apply addendum when not given the filename" ) );
return 0;
}
die wrap_msg( dgettext( "po4a", "Addendum %s does not exist." ), $filename )
unless -e $filename;
my ( $errcode, $mode, $position, $boundary, $bmode, $content ) =
addendum_parse( $filename, $self->{TT}{'addendum_charset'} );
return 0 if ($errcode);
# In order to make addendum more intuitive, each array item of
# @{$self->{TT}{doc_out}} must not have internal "\n". But previous parser
# code may put multiple internal "\n" to address things like placeholder
# tag handling. Let's normalize array content.
# Use internal "\n" as delimiter but keep it by using the lookbehind trick.
@{ $self->{TT}{doc_out} } = map { split /(?<=\n)/, $_ } @{ $self->{TT}{doc_out} };
# Bugs around addendum is hard to understand. So let's print involved data explicitly.
if ( $self->debug() ) {
print STDERR "Addendum position regex=$position\n";
print STDERR "Addendum mode=$mode\n";
if ( $mode eq "after" ) {
print STDERR "Addendum boundary regex=$boundary\n";
print STDERR "Addendum boundary mode=$bmode\n";
}
print STDERR "Addendum content (begin):\n";
print STDERR "$content";
print STDERR "Addendum content (end)\n";
print STDERR "Output items searched for the addendum insertion position:\n";
foreach my $item ( @{ $self->{TT}{doc_out} } ) {
print STDERR $item;
print STDERR "\n----- [ search item end marker with a preceding newline ] -----\n";
}
print STDERR "Start searching addendum insertion position...\n";
}
unless ( $mode eq 'eof' ) {
my $found = scalar grep { /$position/ } @{ $self->{TT}{doc_out} };
if ( $found == 0 ) {
warn wrap_msg( dgettext( "po4a", "No candidate position for the addendum %s." ), $filename );
return 0;
}
if ( $found > 1 ) {
warn wrap_msg( dgettext( "po4a", "More than one candidate position found for the addendum %s." ),
$filename );
return 0;
}
}
if ( $mode eq "eof" ) {
push @{ $self->{TT}{doc_out} }, $content;
} elsif ( $mode eq "before" ) {
if ( $self->verbose() > 1 || $self->debug() ) {
map {
print STDERR wrap_msg( dgettext( "po4a", "Addendum '%s' applied before this line: %s" ), $filename, $_ )
if (/$position/);
} @{ $self->{TT}{doc_out} };
}
@{ $self->{TT}{doc_out} } = map { /$position/ ? ( $content, $_ ) : $_ } @{ $self->{TT}{doc_out} };
} else {
my @newres = ();
do {
# make sure it doesn't whine on empty document
my $line = scalar @{ $self->{TT}{doc_out} } ? shift @{ $self->{TT}{doc_out} } : "";
push @newres, $line;
my $outline = mychomp($line);
$outline =~ s/^[ \t]*//;
if ( $line =~ m/$position/ ) {
while ( $line = shift @{ $self->{TT}{doc_out} } ) {
last if ( $line =~ /$boundary/ );
push @newres, $line;
}
if ( defined $line ) {
if ( $bmode eq 'before' ) {
print wrap_msg( dgettext( "po4a", "Addendum '%s' applied before this line: %s" ),
$filename, $outline )
if ( $self->verbose() > 1 || $self->debug() );
push @newres, $content;
push @newres, $line;
} else {
print wrap_msg( dgettext( "po4a", "Addendum '%s' applied after the line: %s." ),
$filename, $outline )
if ( $self->verbose() > 1 || $self->debug() );
push @newres, $line;
push @newres, $content;
}
} else {
print wrap_msg( dgettext( "po4a", "Addendum '%s' applied at the end of the file." ), $filename )
if ( $self->verbose() > 1 || $self->debug() );
push @newres, $content;
}
}
} while ( scalar @{ $self->{TT}{doc_out} } );
@{ $self->{TT}{doc_out} } = @newres;
}
print STDERR wrap_mod( "po4a::transtractor::addendum", "Done with addendum %s", $filename )
if $self->debug();
return 1;
}
=back
=head1 INTERNAL FUNCTIONS used to write derivative parsers
=head2 Getting input, providing output
Four functions are provided to get input and return output. They are very
similar to shift/unshift and push/pop of Perl.
* Perl shift returns the first array item and drop it from the array.
* Perl unshift prepends an item to the array as the first array item.
* Perl pop returns the last array item and drop it from the array.
* Perl push appends an item to the array as the last array item.
The first pair is about input, while the second is about output. Mnemonic: in
input, you are interested in the first line, what shift gives, and in output
you want to add your result at the end, like push does.
=over 4
=item shiftline()
This function returns the first line to be parsed and its corresponding
reference (packed as an array) from the array C<< @{$self->{TT}{doc_in}} >> and
drop these first 2 array items. Here, the reference is provided by a string
C<< $filename:$linenum >>.
=item unshiftline($$)
Unshifts the last shifted line of the input document and its corresponding
reference back to the head of C<< {$self->{TT}{doc_in}} >>.
=item pushline($)
Push a new line to the end of C<< {$self->{TT}{doc_out}} >>.
=item popline()
Pop the last pushed line from the end of C<< {$self->{TT}{doc_out}} >>.
=back
=cut
sub shiftline {
my ( $line, $ref ) = ( shift @{ $_[0]->{TT}{doc_in} }, shift @{ $_[0]->{TT}{doc_in} } );
return ( $line, $ref );
}
sub unshiftline {
my $self = shift;
unshift @{ $self->{TT}{doc_in} }, @_;
}
sub pushline { push @{ $_[0]->{TT}{doc_out} }, $_[1] if defined $_[1]; }
sub popline { return pop @{ $_[0]->{TT}{doc_out} }; }
=head2 Marking strings as translatable
One function is provided to handle the text which should be translated.
=over 4
=item translate($$$)
Mandatory arguments:
=over 2
=item -
A string to translate
=item -
The reference of this string (i.e. position in inputfile)
=item -
The type of this string (i.e. the textual description of its structural role;
used in Locale::Po4a::Po::gettextization(); see also L<po4a(7)|po4a.7>,
section B<Gettextization: how does it work?>)
=back
This function can also take some extra arguments. They must be organized as
a hash. For example:
$self->translate("string","ref","type",
'wrap' => 1);
=over
=item B<wrap>
boolean indicating whether we can consider that whitespaces in string are
not important. If yes, the function canonizes the string before looking for
a translation or extracting it, and wraps the translation.
=item B<wrapcol>
the column at which we should wrap (default: the value of B<wrapcol> specified
during creation of the TransTractor or 76).
The negative value will be substracted from the default.
=item B<comment>
an extra comment to add to the entry.
=back
Actions:
=over 2
=item -
Pushes the string, reference and type to po_out.
=item -
Returns the translation of the string (as found in po_in) so that the
parser can build the doc_out.
=item -
Handles the charsets to recode the strings before sending them to
po_out and before returning the translations.
=back
=back
=cut
sub translate {
my $self = shift;
my ( $string, $ref, $type ) = ( shift, shift, shift );
my (%options) = @_;
return "" unless length($string);
# my %validoption;
# map { $validoption{$_}=1 } (qw(wrap wrapcoll));
# foreach (keys %options) {
# Carp::confess "internal error: translate() called with unknown arg $_. Valid options: $validoption"
# unless $validoption{$_};
# }
if ( !defined $options{'wrapcol'} ) {
$options{'wrapcol'} = $self->{TT}{wrapcol};
} elsif ( $options{'wrapcol'} < 0 ) {
$options{'wrapcol'} = $self->{TT}{wrapcol} + $options{'wrapcol'};
}
my $transstring = $self->{TT}{po_in}->gettext(
$string,
'wrap' => $options{'wrap'} || 0,
'wrapcol' => $options{'wrapcol'}
);
# the comments provided by the modules are automatic comments from the PO point of view
$self->{TT}{po_out}->push(
'msgid' => $string,
'reference' => $ref,
'type' => $type,
'automatic' => $options{'comment'},
'flags' => $options{'flags'},
'wrap' => $options{'wrap'} || 0,
);
if ( $options{'wrap'} || 0 ) {
$transstring =~ s/( *)$//s;
my $trailing_spaces = $1 || "";
$transstring =~ s/(?<!\\) +$//gm;
$transstring .= $trailing_spaces;
}
return $transstring;
}
=head2 Misc functions
=over 4
=item verbose()
Returns if the verbose option was passed during the creation of the
TransTractor.
=cut
sub verbose {
if ( defined $_[1] ) {
$_[0]->{TT}{verbose} = $_[1];
} else {
return $_[0]->{TT}{verbose} || 0; # undef and 0 have the same meaning, but one generates warnings
}
}
=item debug()
Returns if the debug option was passed during the creation of the
TransTractor.
=cut
sub debug {
return $_[0]->{TT}{debug};
}
=item get_in_charset()
This function return the charset that was provided as master charset
=cut
sub get_in_charset() {
return $_[0]->{TT}{'file_in_charset'};
}
=item get_out_charset()
This function will return the charset that should be used in the output
document (usually useful to substitute the input document's detected charset
where it has been found).
It will use the output charset specified in the command line. If it wasn't
specified, it will use the input PO's charset, and if the input PO has the
default "CHARSET", it will return the input document's charset, so that no
encoding is performed.
=cut
sub get_out_charset {
my $self = shift;
# Prefer the value specified on the command line
return $self->{TT}{'file_out_charset'}
if length( $self->{TT}{'file_out_charset'} );
return $self->{TT}{po_in}->get_charset if $self->{TT}{po_in}->get_charset ne 'CHARSET';
return $self->{TT}{'file_in_charset'} if length( $self->{TT}{'file_in_charset'} );
return 'UTF-8';
}
# Push the translation of a Yaml document or Yaml Front-Matter header, parsed by YAML::Tiny in any case
# $is_yfm is a boolean indicating whether we are dealing with a Front Matter (true value) or whole document (false value)
sub handle_yaml {
my ( $self, $is_yfm, $blockref, $yamlarray, $yfm_keys, $yfm_skip_array, $yfm_paths ) = @_;
die "Empty YAML " . ( $is_yfm ? "Front Matter" : "document" ) unless ( length($yamlarray) > 0 );
my ( $indent, $ctx ) = ( 0, "" );
foreach my $cursor (@$yamlarray) {
# An empty document
if ( !defined $cursor ) {
$self->pushline("---\n");
# Do nothing
# A scalar document
} elsif ( !ref $cursor ) {
$self->pushline("---\n");
$self->pushline(
format_scalar(
$self->translate(
$cursor, $blockref,
"YAML " . ( $is_yfm ? "Front Matter " : "" ) . "(scalar)",
"wrap" => 0
)
)
);
# A list at the root
} elsif ( ref $cursor eq 'ARRAY' ) {
if (@$cursor) {
$self->pushline("---\n");
do_array( $self, $is_yfm, $blockref, $cursor, $indent, $ctx, $yfm_keys, $yfm_skip_array, $yfm_paths );
} else {
$self->pushline("---[]\n");
}
# A hash at the root
} elsif ( ref $cursor eq 'HASH' ) {
if (%$cursor) {
$self->pushline("---\n");
do_hash( $self, $is_yfm, $blockref, $cursor, $indent, $ctx, $yfm_keys, $yfm_skip_array, $yfm_paths );
} else {
$self->pushline("--- {}\n");
}
} else {
die( "Cannot serialize " . ref($cursor) );
}
}
# Escape the string to make it valid in YAML.
# This is very similar to YAML::Tiny::_dump_scalar but does not do the internal->UTF-8 decoding,
# as the translations that we feed into this function are already in UTF-8
sub format_scalar {
my $string = $_[0];
my $is_key = $_[1];
return '~' unless defined $string;
return "''" unless length $string;
if ( Scalar::Util::looks_like_number($string) ) {
# keys and values that have been used as strings get quoted
if ($is_key) {
return qq['$string'];
} else {
return $string;
}
}
if ( $string =~ /[\\\'\n]/ ) {
$string =~ s/\\/\\\\/g;
$string =~ s/"/\\"/g;
$string =~ s/\n/\\n/g;
return qq|"$string"|;
}
if ( $string =~ /(?:^[~!@#%&*|>?:,'"`{}\[\]]|^-+$|\s|:\z)/ ) {
return "'$string'";
}
return $string;
}
sub do_array {
my ( $self, $is_yfm, $blockref, $array, $indent, $ctx, $yfm_keys, $yfm_skip_array, $yfm_paths ) = @_;
foreach my $el (@$array) {
my $header = ( ' ' x $indent ) . '- ';
my $type = ref $el;
if ( !$type ) {
if ($yfm_skip_array) {
$self->pushline( $header . YAML::Tiny::_dump_scalar( "dummy", $el, 0 ) . "\n" );
} else {
$self->pushline(
$header
. format_scalar(
$self->translate(
$el, $blockref,
( $is_yfm ? "Yaml Front Matter " : "" ) . "Array Element:$ctx", "wrap" => 0
)
)
. "\n"
);
}
} elsif ( $type eq 'ARRAY' ) {
if (@$el) {
$self->pushline( $header . "\n" );
do_array( $self, $is_yfm, $blockref, $el, $indent + 1,
$ctx, $yfm_keys, $yfm_skip_array, $yfm_paths );
} else {
$self->pushline( $header . " []\n" );
}
} elsif ( $type eq 'HASH' ) {
if ( keys %$el ) {
$self->pushline( $header . "\n" );
do_hash( $self, $is_yfm, $blockref, $el, $indent + 1, $ctx, $yfm_keys, $yfm_skip_array,
$yfm_paths );
} else {
$self->pushline( $header . " {}\n" );
}
} else {
die "YAML $type references not supported";
}
}
}
sub do_hash {
my ( $self, $is_yfm, $blockref, $hash, $indent, $ctx, $yfm_keys, $yfm_skip_array, $yfm_paths ) = @_;
foreach my $name ( sort keys %$hash ) {
my $el = $hash->{$name} // "";
my $header = ( ' ' x $indent ) . YAML::Tiny::_dump_scalar( "dummy", $name, 1 ) . ":";
unless ( length($el) > 0 ) { # empty element, as in "tags: " with nothing after the column
$self->pushline( $header . "\n" );
next;
}
my $type = ref $el;
if ( !$type ) {
my %keys = %{$yfm_keys};
my %paths = %{$yfm_paths};
my $path = "$ctx $name" =~ s/^\s+|\s+$//gr; # Need to trim the path, at least when there is no ctx yet
if ( ( $el eq 'false' ) or ( $el eq 'true' ) ) { # Do not translate nor quote booleans
$self->pushline("$header $el\n");
} elsif (
( scalar %keys > 0 && exists $keys{$name} ) or # the key we need is provided
( scalar %paths > 0 && exists $paths{$path} ) or # that path is provided
( scalar %keys == 0 && scalar %paths == 0 ) # no key and no path provided
)
{
my $translation = $self->translate(
$el, $blockref,
( $is_yfm ? "Yaml Front Matter " : "" ) . "Hash Value:$ctx $name",
"wrap" => 0
);
# add extra quotes to the parameter, as a protection to the extra chars that the translator could add
$self->pushline( $header . ' ' . format_scalar($translation) . "\n" );
} else {
# Work around a bug in YAML::Tiny that quotes numbers
# See https://github.com/Perl-Toolchain-Gang/YAML-Tiny#additional-perl-specific-notes
if ( Scalar::Util::looks_like_number($el) ) {
$self->pushline("$header $el\n");
} else {
$self->pushline( $header . ' ' . YAML::Tiny::_dump_scalar( "dummy", $el ) . "\n" );
}
}
} elsif ( $type eq 'ARRAY' ) {
if (@$el) {
$self->pushline( $header . "\n" );
do_array(
$self, $is_yfm, $blockref, $el, $indent + 1, "$ctx $name",
$yfm_keys, $yfm_skip_array, $yfm_paths
);
} else {
$self->pushline( $header . " []\n" );
}
} elsif ( $type eq 'HASH' ) {
if ( keys %$el ) {
$self->pushline( $header . "\n" );
do_hash(
$self, $is_yfm, $blockref, $el, $indent + 1, "$ctx $name",
$yfm_keys, $yfm_skip_array, $yfm_paths
);
} else {
$self->pushline( $header . " {}\n" );
}
} else {
die "YAML $type references not supported";
}
}
}
}
=back
=head1 FUTURE DIRECTIONS
One shortcoming of the current TransTractor is that it can't handle
translated document containing all languages, like debconf templates, or
.desktop files.
To address this problem, the only interface changes needed are:
=over 2
=item -
take a hash as po_in_name (a list per language)
=item -
add an argument to translate to indicate the target language
=item -
make a pushline_all function, which would make pushline of its content for
all languages, using a map-like syntax:
$self->pushline_all({ "Description[".$langcode."]=".
$self->translate($line,$ref,$langcode)
});
=back
Will see if it's enough ;)
=head1 AUTHORS
Denis Barbier <barbier@linuxfr.org>
Martin Quinson (mquinson#debian.org)
Jordi Vilalta <jvprat@gmail.com>
=cut
1;
|