lib/App/Syslogd/I18N.pm

filter: Statementstmt 100% 42 / 42 Branchbran 100% 12 / 12 Conditioncond 100% 20 / 20 MC/DCmcdc 100% 11 / 11 Subroutinesub 100% 9 / 9 Podpod 100% 3 / 3 totaltotal 100% 97 / 97 CC 15 SCAR 18.4
CC
15
Cov
100%
text
11.0
handle
3.0
gender
3.0
CRAP 6.3
« lib/App/Syslogd/Cache.pm ↑ Summary lib/App/Syslogd.pm »
1 package App::Syslogd::I18N;
2  
3 # Message catalogue for App::Syslogd.
4 #
5 # This is a thin layer over Locale::Maketext (core Perl) rather than a
6 # home-grown catalogue. Maketext already gives us language negotiation,
7 # [quant,...] pluralisation and [sprintf,...] formatting; all we add is
8 # named arguments (so callers never depend on positional order) and a
9 # [gender,...] bracket method.
10  
11 50 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 50 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 50 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 50 ▶use parent 'Locale::Maketext';
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 50 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 50 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 50 our $VERSION = '0.002.1';
21  
22 # Language used when nothing in the environment matches a lexicon we ship
23 50 Readonly::Scalar my $FALLBACK_LANGUAGE => 'en';
24  
25 # The order in which each message's named arguments become [_1], [_2], ...
26 # Translators of every language see the same positional slots, so this
27 # table is the single source of truth for every message's arguments.
28 50 Readonly my %ARGUMENT_ORDER => (
29 usage => [qw(program)],
30 listening => [qw(address port)],
31 shutdown => [qw(count)],
32 socket_failed => [qw(address port error)],
33 open_failed => [qw(file error)],
34 unsafe_file => [qw(file)],
35 write_failed => [qw(file error)],
36 recv_failed => [qw(error)],
37 no_log_open => [],
38 not_a_datagram => [qw(type)],
39 missing_key => [],
40 bad_values => [qw(type)],
41 no_progress => [],
42 not_cgi => [],
43 not_a_log => [qw(file)],
44 already_running => [],
45 );
46  
47 =encoding utf8
48  
49 =head1 NAME
50  
51 App::Syslogd::I18N - Localised messages for App::Syslogd
52  
53 =head1 VERSION
54  
55 Version 0.002.1
56  
57 =head1 SYNOPSIS
58  
59 =head2 1. Get a message in the user's language
60  
61 use App::Syslogd::I18N;
62  
63 my $lh = App::Syslogd::I18N->handle(); # language from the environment
64 print $lh->text('listening', { address => '0.0.0.0', port => 514 }), "\n";
65 # Syslog server listening on 0.0.0.0 UDP port 514
66  
67 =head2 2. Ask for one language
68  
69 my $lh = App::Syslogd::I18N->handle('en-gb');
70 print $lh->text('shutdown', { count => 2 }), "\n";
71 # Syslog server shutting down after recording 2 messages
72  
73 =head2 3. Add a translation
74  
75 Put this in F<lib/App/Syslogd/I18N/de.pm>. Inherit from the English
76 lexicon, so that any message you have not translated yet is still shown in
77 English instead of causing an error.
78  
79 package App::Syslogd::I18N::de;
80 use parent 'App::Syslogd::I18N::en';
81  
82 our %Lexicon = (
83 listening => 'Syslog-Server wartet auf [_1], UDP-Port [_2]',
84 shutdown => 'Syslog-Server endet nach [quant,_1,Nachricht,Nachrichten]',
85 );
86  
87 1;
88  
89 =head1 DESCRIPTION
90  
91 A program shows messages to people: "listening on port 514", "could not
92 open the file", and so on. This module keeps those messages in one place, so
93 that they can be translated into other languages.
94  
95 Each message has a I<key> (a short name, such as C<listening>) and some
96 I<values> (such as the port number). You give the key and the values; you
97 get back the finished sentence in the chosen language.
98  
99 Each language is a small Perl package called C<App::Syslogd::I18N::xx>
100 (where C<xx> is the language code) with a hash called C<%Lexicon>. The hash
101 maps each key to its text. The text uses the "bracket notation" of
102 L<Locale::Maketext>:
103  
104 =over 4
105  
106 =item * C<[_1]>, C<[_2]>, ... are replaced by the values, in the order given
107 by the table in L</text>.
108  
109 =item * C<[quant,_1,message,messages]> chooses the singular or plural form
110 for the number in C<[_1]>, and writes the number.
111  
112 =item * C<[sprintf,%05d,_1]> formats a value, as Perl's C<sprintf> does.
113  
114 =item * C<[gender,_1,his,her,their]> chooses a word by gender; see
115 L</gender>.
116  
117 =item * A real square bracket is written C<~[> or C<~]>.
118  
119 =back
120  
121 =head1 ENCODING
122  
123 =over 4
124  
125 =item * B<Language tags> must be ASCII, for example C<en> or C<en-gb>.
126  
127 =item * B<Lexicon text> may contain any Unicode characters, including
128 non-ASCII letters and emoji, if the language file starts with C<use utf8;>.
129 The English lexicon is pure ASCII.
130  
131 =item * B<Values> are copied into the message unchanged. They may be byte
132 strings or character strings. Square brackets and C<~> in a value are not
133 special: only the lexicon text is parsed.
134  
135 =item * B<The result> is a Perl string. If it contains characters above
136 255 (for example from a translation with emoji), set an output layer before
137 printing it: C<binmode(STDOUT, ':encoding(UTF-8)')>. Otherwise Perl prints
138 a "Wide character" warning.
139  
140 =back
141  
142 =head1 COMMON PITFALLS
143  
144 =over 4
145  
146 =item * B<A translation must inherit from the English lexicon.> If
147 C<App::Syslogd::I18N::de> inherits only from C<App::Syslogd::I18N>, any key
148 it does not translate makes L<Locale::Maketext> die with "maketext doesn't
149 know how to say". Inherit from C<App::Syslogd::I18N::en>, as in the
150 SYNOPSIS, and missing keys fall back to English.
151  
152 =item * B<Missing values become empty strings.> C<< text('open_failed', {}) >>
153 gives "Could not open log file : " with no warning. This is on purpose (an
154 error message should never fail), but check your values if a message looks
155 incomplete.
156  
157 =item * B<undef or non-numbers in a plural become 0.>
158 C<< text('shutdown', { count => undef }) >> says "0 messages".
159  
160 =item * B<An unknown key does not die.> C<< text('no_such_key', { a => 1 }) >>
161 returns C<no_such_key (a=1)>. This keeps the information in an error path,
162 but it means a misspelt key is not reported. Test the messages you use.
163  
164 =item * B<Values are matched to positions by name, not by order.> The order
165 of the C<[_1]>, C<[_2]> slots comes from a fixed table (see L</text>), not
166 from the order you write the hash. A new key must be added to that table
167 too, or it is treated as unknown.
168  
169 =item * B<gender() knows only "male" and "female".> Any other value,
170 including C<m>, C<f> and C<undef>, gives the neutral form. Upper and lower
171 case are the same.
172  
173 =item * B<The language comes from the environment> when you give none:
174 C<LANGUAGE>, C<LC_ALL>, C<LC_MESSAGES>, then C<LANG>. A language with no
175 lexicon falls back to English without a warning.
176  
177 =item * B<Operating-system errors stay in English.> A value such as C<"$!">
178 is in the C locale unless the code that made it used C<use locale>, whatever
179 C<LC_ALL> says.
180  
181 =back
182  
183 =head1 METHODS
184  
185 =head2 handle
186  
187 Purpose: get a "language handle", the object that makes messages in one
188 language.
189  
190 Args: optional: a language tag, such as C<de> or C<en-gb>. Without one, the
191 language is taken from the environment (C<LANGUAGE>, C<LC_ALL>,
192 C<LC_MESSAGES>, C<LANG>).
193  
194 Returns: an object of a C<App::Syslogd::I18N> subclass. Never C<undef>: if
195 there is no lexicon for the language, you get the English one.
196  
197 Side Effects: may load the language's module file.
198  
199 Usage:
200  
201 my $lh = App::Syslogd::I18N->handle();
202  
203 =head3 EXAMPLE
204  
205 my $lh = App::Syslogd::I18N->handle('fr'); # there is no French yet...
206 print ref($lh), "\n"; # ...so: App::Syslogd::I18N::en
207  
208 =head3 API SPECIFICATION
209  
210 =head4 INPUT
211  
212 {
213 language => { type => 'string', optional => 1, position => 0 },
214 }
215  
216 Domains: a supported tag (C<en>, C<en-gb>, C<EN>) gives that language;
217 an unsupported (C<fr>), malformed (C<../x>, C<en;x>) or very long tag gives
218 English; undef or "" reads the environment.
219  
220 =head4 OUTPUT
221  
222 { type => 'object', isa => 'App::Syslogd::I18N' }
223  
224 =head3 MESSAGES
225  
226 None.
227  
228 =cut
229  
230 sub handle
231 621 ▶{
Subroutine handle: called CC=3 SCAR=11.0
Pod documented
232 621 my ($class, $language) = @_;
233  
234 # Locale::Maketext returns undef when no lexicon matches, which is
235 # never useful to a caller that just wants a message printed
236 621 ▶ my @tags = defined($language) ? ($language) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $language ? : 89 532 621
237  
238 621 ▶ return $class->get_handle(@tags) || $class->get_handle($FALLBACK_LANGUAGE);
Condition100%3/3
$class->get_handle(@tags) || $class->get_handle($FALLBACK_LANGUAGE)
l!l&&r!l&&!r
61542
MC/DC100%2/2
$class->get_handle(@tags) || $class->get_handle($FALLBACK_LANGUAGE)
$class->get_handle(@tags) $class->get_handle($FALLBACK_LANGUAGE)
Truth table100%3/3
A || B
A= $class->get_handle(@tags)B= $class->get_handle($FALLBACK_LANGUAGE)
ABresult
1X1
011
000
239 }
240  
241 =head2 text
242  
243 Purpose: make one finished message.
244  
245 Args:
246  
247 =over 4
248  
249 =item 1. The message key.
250  
251 =item 2. Optional: a hash reference of named values. A missing value becomes
252 an empty string.
253  
254 =back
255  
256 The keys, and the values each one uses (in slot order C<[_1]>, C<[_2]>,
257 ...):
258  
259 +---------------+----------------------+
260 | Key | Values, in order |
261 +---------------+----------------------+
262 | usage | program |
263 | listening | address, port |
264 | shutdown | count |
265 | socket_failed | address, port, error |
266 | open_failed | file, error |
267 | unsafe_file | file |
268 | write_failed | file, error |
269 | recv_failed | error |
270 | no_log_open | (none) |
271 | not_a_datagram| type |
272 | missing_key | (none) |
273 | bad_values | type |
274 | no_progress | (none) |
275 | not_cgi | (none) |
276 | not_a_log | file |
277 | already_running | (none) |
278 +---------------+----------------------+
279  
280 Returns: the message, as a string. An unknown key does not die: it returns
281 the key, followed by its values in brackets if there are any. The most
282 likely caller is reporting an error, and losing that error would be worse
283 than showing an untranslated key.
284  
285 Side Effects: none.
286  
287 Usage:
288  
289 my $msg = $lh->text('open_failed', { file => '/x', error => "$!" });
290  
291 =head3 EXAMPLE
292  
293 my $lh = App::Syslogd::I18N->handle('en');
294 print $lh->text('shutdown', { count => 1 }), "\n"; # "... 1 message"
295 print $lh->text('shutdown', { count => 2 }), "\n"; # "... 2 messages"
296 print $lh->text('no_such_key', { a => 1 }), "\n"; # "no_such_key (a=1)"
297  
298 =head3 API SPECIFICATION
299  
300 =head4 INPUT
301  
302 {
303 key => { type => 'string', min => 1, position => 0 },
304 args => { type => 'hashref', optional => 1, position => 1 },
305 }
306  
307 Domains: C<key> as in the table below (undef, "" or a reference dies;
308 an unknown key comes back as text). C<args>: a hash reference or undef;
309 an array, code, glob or plain string dies, including C<""> and C<0>. Values: any text, including
310 non-ASCII characters, emoji and right-to-left text, copied unchanged;
311 missing ones become "".
312  
313 =head4 OUTPUT
314  
315 { type => 'string' }
316  
317 =head3 MESSAGES
318  
319 +-----------------------------------+----------------------------+------------------------------+
320 | Message (dies) | Meaning | What to do |
321 +-----------------------------------+----------------------------+------------------------------+
322 | maketext doesn't know how to say: | A translation has no text | Make the language inherit |
323 | KEY | for KEY and does not | from App::Syslogd::I18N::en|
324 | | inherit from English | (see COMMON PITFALLS) |
325 | A message key is needed | KEY was undef, empty or a | Pass a key from the table |
326 | | reference | |
327 | Message values must be a hash | The values were not a hash | Pass { name => value, ... } |
328 | reference (the type given was T)| reference | |
329 +-----------------------------------+----------------------------+------------------------------+
330  
331 The English text of every key is in L<App::Syslogd/i18n>.
332  
333 =cut
334  
335 sub text
336 366 ▶{
Subroutine text: called CC=11 SCAR=24.0
Pod documented
337 366 my ($self, $key, $args) = @_;
338  
339 # Programming errors, reported clearly rather than as an
340 # "uninitialized" warning or Perl's "Not a HASH reference". These two
341 # messages come straight from the lexicon with maketext(), never
342 # through text() again: an error path that calls the routine it guards
343 # can recurse for ever if the guard is ever wrong (mutation testing
344 # found exactly that). Their single value is the [_1] of
345 # %ARGUMENT_ORDER.
346 366 ▶ croak($self->maketext('missing_key')) if(!defined($key) || ref($key) || !length($key));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $key or ref $key or not length $key 16 350 366
Condition100%6/6
not defined $key or ref $key or not length $key
l!l&&r!l&&!r
115350
not defined $key or ref $key
l!l&&r!l&&!r
65355
MC/DC100%3/3
not defined $key or ref $key or not length $key
not defined $key ref $key not length $key
Truth table100%4/4
not(A) or B or not(C)
A= not defined $keyB= ref $keyC= not length $key
ABCresult
1XX1
01X1
0011
0000
347  
348 # The values are undef (none) or a hash reference; nothing else. "||="
349 # used to turn "" and 0 into "no values" too, which broke that rule.
350 350 ▶ $args //= {};
Condition100%2/2
$args //= {}
l!l
31733
MC/DC100%1/1
$args //= {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
351 350 ▶ if(ref($args) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 16 334 350
352 16 ▶ croak($self->maketext('bad_values', ref($args) || 'SCALAR'));
Condition100%2/2
ref $args || 'SCALAR'
l!l
88
MC/DC100%1/1
ref $args || 'SCALAR'
ref $args
Truth table100%2/2
A
A= ref $args
Aresult
11
00
353 }
354  
355 # Unknown keys still produce something readable; see POD above
356 334 my $order = $ARGUMENT_ORDER{$key};
357 334 ▶ if(!defined($order)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $order) 11 323 334
358 11 ▶ my $detail = join(', ', map { "$_=" . ($args->{$_} // '') } sort keys %{$args});
Condition100%2/2
$args->{$_} // ""
l!l
72
MC/DC100%1/1
$args->{$_} // ""
$args->{$_}
Truth table100%2/2
A
A= $args->{$_}
Aresult
11
00
359 11 ▶ return length($detail) ? "$key ($detail)" : $key;
Branch: 1 branch
BranchTrueFalseTotal
length $detail ? : 5 6 11
360 }
361  
362 # Missing arguments become empty strings so a sloppy caller gets a
363 # slightly odd message instead of "Use of uninitialized value" noise
364 323 ▶ return $self->maketext($key, map { $args->{$_} // '' } @{$order});
Condition100%2/2
$args->{$_} // ""
l!l
47718
MC/DC100%1/1
$args->{$_} // ""
$args->{$_}
Truth table100%2/2
A
A= $args->{$_}
Aresult
11
00
365 }
366  
367 =head2 gender
368  
369 Purpose: choose a word by grammatical gender inside a message. You do not
370 call it directly; a lexicon uses it with bracket notation:
371 C<[gender,_1,male form,female form,neutral form]>.
372  
373 Args: the gender value, then the male, female and neutral forms.
374  
375 Returns: the male form for C<male>, the female form for C<female> (upper or
376 lower case), and the neutral form for anything else, including C<undef>.
377  
378 Side Effects: none.
379  
380 Usage:
381  
382 # In a lexicon:
383 owner_changed => '[_1] changed [gender,_2,his,her,their] password',
384  
385 =head3 EXAMPLE
386  
387 my $lh = App::Syslogd::I18N->handle('en');
388 print $lh->gender('Female', 'his', 'her', 'their'), "\n"; # her
389 print $lh->gender(undef, 'his', 'her', 'their'), "\n"; # their
390  
391 =head3 API SPECIFICATION
392  
393 =head4 INPUT
394  
395 {
396 gender => { type => 'string', optional => 1, position => 0 },
397 male => { type => 'string', position => 1 },
398 female => { type => 'string', position => 2 },
399 neutral => { type => 'string', position => 3 },
400 }
401  
402 Domains of C<gender>: "male" or "female" in any case pick their form;
403 everything else (undef, "", "m", "f", references) picks the neutral
404 form.
405  
406 =head4 OUTPUT
407  
408 { type => 'string' }
409  
410 =head3 MESSAGES
411  
412 None.
413  
414 =cut
415  
416 sub gender
417 50 ▶{
Subroutine gender: called CC=3 SCAR=11.0
Pod documented
418 50 my ($self, $gender, $male, $female, $neutral) = @_;
419  
420 # A single lookup table keeps this to one return statement
421 50 my %form = (male => $male, female => $female);
422  
423 50 ▶ return defined($gender) && exists($form{lc $gender}) ? $form{lc $gender} : $neutral;
Branch: 1 branch
BranchTrueFalseTotal
defined $gender && exists $form{lc $gender} ? : 23 27 50
Condition100%3/3
defined $gender and exists $form{lc $gender}
!ll&&!rl&&r
52223
MC/DC100%2/2
defined $gender and exists $form{lc $gender}
defined $gender exists $form{lc $gender}
Truth table100%3/3
A and B
A= defined $genderB= exists $form{lc $gender}
ABresult
0X0
100
111
424 }
425  
426 =head1 LIMITATIONS
427  
428 Only English is included. Messages that contain an operating-system error
429 (C<$!>) show it in English, as explained in L</COMMON PITFALLS>.
430  
431 =head1 AUTHOR
432  
433 Nigel Horne, C<< <njh at nigelhorne.com> >>
434  
435 =head1 LICENSE AND COPYRIGHT
436  
437 Copyright 2026 Nigel Horne.
438  
439 This program is released under the GNU General Public License, version 2
440 (see the F<LICENSE> file). If you use it, please let me know.
441  
442 =head1 FORMAL SPECIFICATION
443  
444 This section describes each method exactly, in the Z notation. You do not
445 need it to use the module.
446  
447 =head2 handle
448  
449 [LANGTAG, KEY, NAME, VALUE, STRING]
450 lexicons : LANGTAG ⇸ (KEY ⇸ STRING)
451 en ∈ dom lexicons
452  
453 Handle
454 lang? : LANGTAG ∪ {⊥}
455 h! : HANDLE
456 ─────────
457 let l == (if lang? = ⊥ then fromEnvironment else lang?) •
458 (l ∈ dom lexicons ⇒ language(h!) = l) ∧
459 (l ∉ dom lexicons ⇒ language(h!) = en)
460  
461 =head2 text
462  
463 ARGUMENT_ORDER : KEY ⇸ seq NAME
464  
465 Text
466 h? : HANDLE ; key? : KEY ; args? : NAME ⇸ VALUE
467 out! : STRING
468 ─────────
469 key? ∈ dom ARGUMENT_ORDER ⇒
470 out! = render(lexicon(language(h?), key?),
471 ⟨ n : ran ARGUMENT_ORDER(key?) •
472 if n ∈ dom args? ∧ args?(n) ≠ ⊥ then args?(n) else "" ⟩)
473 key? ∉ dom ARGUMENT_ORDER ∧ args? = ∅ ⇒ out! = key?
474 key? ∉ dom ARGUMENT_ORDER ∧ args? ≠ ∅ ⇒
475 out! = key? ⁀ " (" ⁀ join(", ", sorted(args?)) ⁀ ")"
476  
477 =head2 gender
478  
479 Gender
480 g? : STRING ∪ {⊥} ; m?, f?, n? : STRING ; out! : STRING
481 ─────────
482 (g? ≠ ⊥ ∧ lower(g?) = "male" ⇒ out! = m?) ∧
483 (g? ≠ ⊥ ∧ lower(g?) = "female" ⇒ out! = f?) ∧
484 (g? = ⊥ ∨ lower(g?) ∉ {"male", "female"} ⇒ out! = n?)
485  
486 =head1 STATE DIAGRAM
487  
488 A language handle has no states that change. C<handle()> makes it, and
489 after that C<text()> and C<gender()> only read it.
490  
491 handle(LANG)
492 | [load LANG's lexicon, or English if there is none]
493 v
494 +-----------+
495 | READY |<-- text(KEY, VALUES) [return a message; no change]
496 | |<-- gender(...) [return a word; no change]
497 +-----------+
498  
499 +--------+-------------------+--------+--------------------------------------+
500 | From | Trigger | To | Action / side effect |
501 +--------+-------------------+--------+--------------------------------------+
502 | (none) | handle(LANG) | READY | language chosen; module may be |
503 | | | | loaded |
504 | READY | text(KEY, VALUES) | READY | message returned |
505 | READY | gender(...) | READY | word returned |
506 | READY | text() for a key | READY | dies "maketext doesn't know how to |
507 | | the language | | say" (only if the language does |
508 | | lacks | | not inherit from English) |
509 +--------+-------------------+--------+--------------------------------------+
510  
511 =cut
512  
513 50 1;
« lib/App/Syslogd/Cache.pm ↑ Summary lib/App/Syslogd.pm »