blib/lib/App/FileSync/I18N.pm

filter: Statementstmt 96.5% 139 / 144 Branchbran 85.7% 60 / 70 Conditioncond 66.6% 30 / 45 MC/DCmcdc 50.0% 14 / 28 Subroutinesub 91.6% 33 / 36 Podpod 100% 10 / 10 totaltotal 85.8% 286 / 333 CC 51 SCAR 16.0
CC
51
Cov
88%
_select
10.7
language
10.0
parse_locale
8.0
CRAP 4.9
« blib/lib/App/FileSync/Server.pm ↑ Summary blib/lib/App/FileSync/Delta.pm »
1 package App::FileSync::I18N;
2  
3 # Message catalogue lookup, interpolation and error raising for App::FileSync.
4 # Every user-facing string in the distribution is a key here, so a translation
5 # is one new catalogue rather than a hunt through the code.
6  
7 342 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 342 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 342 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 342 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 342 ▶use Carp qw(croak carp confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 342 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 342 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 342 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
17 342 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 342 ▶use App::FileSync::I18N::en;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 342 ▶use version; our $VERSION = version->declare('0.002.1');
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 342 our @EXPORT_OK = qw(message throw warning os_error strip_location);
24  
25 # Croak and carp report the first caller outside the message machinery, not
26 # the line inside it that raised the error.
27 342 $Carp::Internal{ (__PACKAGE__) }++;
28  
29 # The language every lookup falls back to, and the catalogue that must hold
30 # every key.
31 342 Readonly::Scalar my $FALLBACK => 'en';
32  
33 # Selector keys inside a catalogue entry, see "CATALOGUE FORMAT" below.
34 342 Readonly::Scalar my $SELECT_KEY => '_by';
35 342 Readonly::Scalar my $SELECT_COUNT => 'count';
36 342 Readonly::Scalar my $SELECT_GENDER => 'gender';
37 342 Readonly::Scalar my $OTHER => 'other';
38  
39 # Environment variables consulted, in order, when no language is configured.
40 # FILESYNC_LANG lets a cron job choose a language without touching the
41 # C library's locale.
42 342 Readonly my @LOCALE_VARIABLES => qw(FILESYNC_LANG LC_ALL LC_MESSAGES LANG);
43  
44 # Territory to language, for a locale whose language has no catalogue but whose
45 # country does (for example "xx_DE" or a bare "DE"). Keys are upper case; the
46 # lookup upper-cases its input, so "gb" and "Gb" work too.
47 342 Readonly my %COUNTRY_LANGUAGE => (
48 AT => 'de', AU => 'en', BE => 'fr', CA => 'en', CH => 'de', CN => 'zh',
49 DE => 'de', ES => 'es', FR => 'fr', GB => 'en', HK => 'zh', IE => 'en',
50 IN => 'en', IT => 'it', JP => 'ja', KR => 'ko', NL => 'nl', NZ => 'en',
51 PT => 'pt', SG => 'zh', TW => 'zh', UK => 'en', US => 'en',
52 );
53  
54 # Plural category for a count, per language (a small subset of CLDR). Anything
55 # not listed uses the English rule.
56 Readonly my %PLURAL_RULE => (
57 60 ▶ en => sub { $_[0] == 1 ? 'one' : $OTHER },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] == 1 ? : 12 48 60
58 3 ▶ de => sub { $_[0] == 1 ? 'one' : $OTHER },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] == 1 ? : 1 2 3
59 7 ▶ fr => sub { ($_[0] == 0 || $_[0] == 1) ? 'one' : $OTHER },
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
$_[0] == 0 || $_[0] == 1 ? : 3 4 7
Condition100%3/3
$_[0] == 0 or $_[0] == 1
l!l&&r!l&&!r
124
MC/DC100%2/2
$_[0] == 0 or $_[0] == 1
$_[0] == 0 $_[0] == 1
Truth table100%3/3
A or B
A= $_[0] == 0B= $_[0] == 1
ABresult
1X1
011
000
60 0 ▶ ja => sub { $OTHER },
Subroutine __ANON__: not called CC=1 SCAR=6.9
61 0 ▶ ko => sub { $OTHER },
Subroutine __ANON__: not called CC=1 SCAR=6.9
62 1 ▶ zh => sub { $OTHER },
Subroutine __ANON__: called CC=1 SCAR=0.0
63 342 );
64  
65 # Settings, in the shape Object::Configure fills: "language" overrides the
66 # environment, and "trace" makes throw() confess with a stack trace.
67 our %config = (
68 language => undef,
69 342 ▶ trace => $ENV{FILESYNC_TRACE} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'FILESYNC_TRACE'} ? : 0 342 342
70 );
71  
72 # Registered catalogues by language. English is always present.
73 342 my %CATALOG = ($FALLBACK => \%App::FileSync::I18N::en::MESSAGES);
74  
75 =encoding utf8
76  
77 =head1 NAME
78  
79 App::FileSync::I18N - message catalogue and error raising for App::FileSync
80  
81 =head1 SYNOPSIS
82  
83 use App::FileSync::I18N qw(message throw);
84  
85 print message('cli.sync.summary', { repo => 'docs', dry => '', pulled => 2, pushed => 0, deleted => 0, conflicts => 0 }), "\n";
86 throw('path.unsafe', { path => $path, reason => $why });
87  
88 =head1 DESCRIPTION
89  
90 Every user-facing string is looked up by key in a catalogue. English is built
91 in (L<App::FileSync::I18N::en>); other languages are added with
92 L</register>. The language is chosen from C<$config{language}>, then
93 C<FILESYNC_LANG>, C<LC_ALL>, C<LC_MESSAGES> and C<LANG>, falling back to
94 English for any language or key that has no catalogue entry.
95  
96 =head2 CATALOGUE FORMAT
97  
98 An entry is either a string or a selector hash.
99  
100 A string may contain C<%{name}FMT> placeholders, where FMT is any C<sprintf>
101 conversion (C<%{path}s>, C<%{count}d>, C<%{ratio}.1f>). C<%%> is a literal
102 percent sign. An undefined argument renders as the empty string (or 0 for a
103 numeric conversion).
104  
105 A selector hash chooses a form by count or by gender, and may nest:
106  
107 'trash.pruned' => {
108 _by => 'count',
109 one => 'removed %{count}d day of trash',
110 other => 'removed %{count}d days of trash',
111 },
112 'admin.owner' => {
113 _by => 'gender',
114 female => '%{name}s owns her repo',
115 male => '%{name}s owns his repo',
116 other => '%{name}s owns their repo',
117 },
118  
119 The count form is chosen by the language's plural rule from C<< $args->{count} >>,
120 and the gender form from C<< $args->{gender} >>; C<other> is the fallback in both.
121  
122 =cut
123  
124 =head1 FUNCTIONS
125  
126 =head2 register
127  
128 Purpose: add or replace the catalogue for a language.
129  
130 Args: C<$language> (two or three lower-case letters), C<\%entries>.
131  
132 Returns: the language code.
133  
134 Side Effects: later lookups in that language use the new entries. Keys the
135 catalogue does not hold still fall back to English.
136  
137 Usage:
138  
139 App::FileSync::I18N::register(de => { 'path.empty' => 'leerer Pfad' });
140  
141 =head3 EXAMPLE
142  
143 App::FileSync::I18N::register(fr => { 'cli.no_repos' => 'Aucun depot configure' });
144 print App::FileSync::I18N::message('cli.no_repos', {}, 'fr'), "\n";
145  
146 =head3 API SPECIFICATION
147  
148 =head4 INPUT
149  
150 [
151 { name => 'language', type => 'string', matches => qr/\A[a-z]{2,3}\z/ },
152 { name => 'entries', type => 'hashref' },
153 ]
154  
155 =head4 OUTPUT
156  
157 { type => 'string', matches => qr/\A[a-z]{2,3}\z/ }
158  
159 =head3 MESSAGES
160  
161 Key Meaning Resolution
162 i18n.bad_language language code is malformed pass "de", not "de_DE"
163 i18n.bad_catalogue entries is not a hash pass a hashref
164  
165 =head3 FORMAL SPECIFICATION
166  
167 ΔCatalog
168 lang? : LANG ; entries? : KEY ⇸ ENTRY
169 Catalog' = Catalog ⊕ {lang? ↦ entries?}
170  
171 =cut
172  
173 4 ▶sub register {
Subroutine register: called CC=4 SCAR=15.2
Pod documented
174 4 my ($language, $entries) = @_;
175  
176 4 ▶ throw('i18n.bad_language', { language => $language })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $language and $language =~ /\A[a-z]{2,3}\z/ 0 4 4
Condition33%1/3
defined $language and $language =~ /\A[a-z]{2,3}\z/
!ll&&!rl&&r
004
MC/DC0%0/2
defined $language and $language =~ /\A[a-z]{2,3}\z/
defined $language $language =~ /\A[a-z]{2,3}\z/
Truth table33%1/3
A and B
A= defined $languageB= $language =~ /\A[a-z]{2,3}\z/
ABresult
0X0
100
111
177 unless defined $language && $language =~ /\A[a-z]{2,3}\z/;
178 4 ▶ throw('i18n.bad_catalogue', { language => $language })
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entries eq "HASH" 0 4 4
179 unless ref($entries) eq 'HASH';
180  
181 4 $CATALOG{$language} = $entries;
182 4 return $language;
183 }
184  
185 =head2 unregister
186  
187 Purpose: remove a registered catalogue (English cannot be removed).
188  
189 Args: C<$language>.
190  
191 Returns: 1 when a catalogue was removed, otherwise 0.
192  
193 Side Effects: later lookups in that language fall back to English.
194  
195 Usage:
196  
197 App::FileSync::I18N::unregister('de');
198  
199 =head3 EXAMPLE
200  
201 App::FileSync::I18N::register(de => {});
202 App::FileSync::I18N::unregister('de');
203  
204 =head3 API SPECIFICATION
205  
206 =head4 INPUT
207  
208 [ { name => 'language', type => 'string' } ]
209  
210 =head4 OUTPUT
211  
212 { type => 'integer', min => 0, max => 1 }
213  
214 =head3 MESSAGES
215  
216 None.
217  
218 =head3 FORMAL SPECIFICATION
219  
220 ΔCatalog
221 lang? : LANG ; r! : 𝔹
222 lang? ≠ en ⇒ Catalog' = {lang?} ⩤ Catalog
223 r! ⇔ lang? ≠ en ∧ lang? ∈ dom Catalog
224  
225 =cut
226  
227 1 ▶sub unregister {
Subroutine unregister: called CC=4 SCAR=17.1
Pod documented
228 1 my ($language) = @_;
229  
230 my $removed = (defined $language && $language ne $FALLBACK
231 1 ▶ && delete $CATALOG{$language}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $language && $language ne $FALLBACK && delete $CATALOG{$language} ? : 1 0 1
Condition33%2/6
defined $language and $language ne $FALLBACK and delete $CATALOG{$language}
!ll&&!rl&&r
001
defined $language and $language ne $FALLBACK
!ll&&!rl&&r
001
MC/DC0%0/3
defined $language and $language ne $FALLBACK and delete $CATALOG{$language}
defined $language $language ne $FALLBACK delete $CATALOG{$language}
Truth table25%1/4
A and B and C
A= defined $languageB= $language ne $FALLBACKC= delete $CATALOG{$language}
ABCresult
0XX0
10X0
1100
1111
232 1 return $removed;
233 }
234  
235 =head2 parse_locale
236  
237 Purpose: split a POSIX locale name into language and country.
238  
239 Args: C<$locale>, such as C<de_DE.UTF-8>, C<en_GB>, C<fr>, C<DE> or C<C>.
240  
241 Returns: a hashref C<{ language =E<gt> 'de', country =E<gt> 'DE' }>; either
242 value is C<undef> when the name does not carry it. Matching is
243 case-insensitive; the language is returned in lower case and the country in
244 upper case.
245  
246 Side Effects: none.
247  
248 Usage:
249  
250 my $parts = App::FileSync::I18N::parse_locale('zh_CN.UTF-8');
251  
252 =head3 EXAMPLE
253  
254 my $parts = App::FileSync::I18N::parse_locale('EN_gb.utf8');
255 # { language => 'en', country => 'GB' }
256  
257 =head3 API SPECIFICATION
258  
259 =head4 INPUT
260  
261 [ { name => 'locale', type => 'string', optional => 1 } ]
262  
263 =head4 OUTPUT
264  
265 {
266 type => 'hashref',
267 schema => {
268 language => { type => 'string', optional => 1 },
269 country => { type => 'string', optional => 1 },
270 },
271 }
272  
273 =head3 MESSAGES
274  
275 None.
276  
277 =head3 FORMAL SPECIFICATION
278  
279 parse : LOCALE → (LANG ∪ {⊥}) × (COUNTRY ∪ {⊥})
280 parse("ll_CC.enc@mod") = (lower ll, upper CC)
281 parse("CC") = (⊥, upper CC) where CC is two letters in upper case
282 parse("C") = parse("POSIX") = (⊥, ⊥)
283  
284 =cut
285  
286 1184 ▶sub parse_locale {
Subroutine parse_locale: called CC=8 SCAR=20.8
Pod documented
287 1184 my ($locale) = @_;
288  
289 1184 my %parts = (language => undef, country => undef);
290  
291 # "C" and "POSIX" name no language at all; an empty value is not a locale.
292 1184 ▶ if (defined $locale && length $locale && $locale !~ /\A(?:C|POSIX)(?:\.|\z)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $locale and length $locale and not $locale =~ /\A(?:C|POSIX)(?:\.|\z)/i) 36 1148 1184
Condition83%5/6
defined $locale and length $locale and not $locale =~ /\A(?:C|POSIX)(?:\.|\z)/i
!ll&&!rl&&r
1147136
defined $locale and length $locale
!ll&&!rl&&r
1147037
MC/DC66%2/3
defined $locale and length $locale and not $locale =~ /\A(?:C|POSIX)(?:\.|\z)/i
defined $locale length $locale not $locale =~ /\A(?:C|POSIX)(?:\.|\z)/i
Truth table75%3/4
A and B and not(C)
A= defined $localeB= length $localeC= not $locale =~ /\A(?:C|POSIX)(?:\.|\z)/i
ABCresult
0XX0
10X0
1100
1111
293 36 ▶ if ($locale =~ /\A([A-Za-z]{2,3})(?:[_-]([A-Za-z]{2}))?(?:[.@].*)?\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($locale =~ /\A([A-Za-z]{2,3})(?:[_-]([A-Za-z]{2}))?(?:[.\@].*)?\z/) 36 0 36
294 36 my ($first, $second) = ($1, $2);
295  
296 # A bare upper-case pair is a country code ("DE"), as a GeoIP
297 # lookup or a web form would supply; anything else leads with a
298 # language.
299 36 ▶ if (!defined $second && $first =~ /\A[A-Z]{2}\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $second and $first =~ /\A[A-Z]{2}\z/) { } 7 29 36
Condition100%3/3
not defined $second and $first =~ /\A[A-Z]{2}\z/
!ll&&!rl&&r
7227
MC/DC100%2/2
not defined $second and $first =~ /\A[A-Z]{2}\z/
not defined $second $first =~ /\A[A-Z]{2}\z/
Truth table100%3/3
not(A) and B
A= not defined $secondB= $first =~ /\A[A-Z]{2}\z/
ABresult
0X0
100
111
300 7 $parts{country} = $first;
301 } else {
302 29 $parts{language} = lc $first;
303 29 ▶ $parts{country} = uc $second if defined $second;
Branch: 1 branch
BranchTrueFalseTotal
if defined $second 7 22 29
304 }
305 }
306 }
307  
308 1184 return \%parts;
309 }
310  
311 =head2 country_language
312  
313 Purpose: the language usually spoken in a country.
314  
315 Args: C<$country>, an ISO 3166-1 alpha-2 code in any case.
316  
317 Returns: a lower-case language code, or C<undef> for an unknown country.
318  
319 Side Effects: none.
320  
321 Usage:
322  
323 my $language = App::FileSync::I18N::country_language('fr'); # 'fr'
324  
325 =head3 EXAMPLE
326  
327 print App::FileSync::I18N::country_language('CN'), "\n"; # zh
328  
329 =head3 API SPECIFICATION
330  
331 =head4 INPUT
332  
333 [ { name => 'country', type => 'string', optional => 1 } ]
334  
335 =head4 OUTPUT
336  
337 { type => 'string', optional => 1, matches => qr/\A[a-z]{2}\z/ }
338  
339 =head3 MESSAGES
340  
341 None.
342  
343 =head3 FORMAL SPECIFICATION
344  
345 country_language : COUNTRY ⇸ LANG
346 country_language(c) = CountryLanguage(upper c) if upper c ∈ dom CountryLanguage
347  
348 =cut
349  
350 1195 ▶sub country_language {
Subroutine country_language: called CC=2 SCAR=6.9
Pod documented
351 1195 my ($country) = @_;
352  
353 1195 ▶ return defined $country ? $COUNTRY_LANGUAGE{ uc $country } : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $country ? : 24 1171 1195
354 }
355  
356 =head2 language
357  
358 Purpose: the catalogue language a lookup will use.
359  
360 Args: optional C<$wanted>, a language code or locale name that overrides the
361 configuration and the environment.
362  
363 Returns: a language code that has a registered catalogue; English when nothing
364 better matches.
365  
366 Side Effects: none.
367  
368 Usage:
369  
370 my $language = App::FileSync::I18N::language();
371 my $german = App::FileSync::I18N::language('de_DE.UTF-8');
372  
373 =head3 EXAMPLE
374  
375 local $ENV{LC_ALL} = 'fr_FR.UTF-8';
376 print App::FileSync::I18N::language(), "\n"; # fr when registered, else en
377  
378 =head3 API SPECIFICATION
379  
380 =head4 INPUT
381  
382 [ { name => 'wanted', type => 'string', optional => 1 } ]
383  
384 =head4 OUTPUT
385  
386 { type => 'string', matches => qr/\A[a-z]{2,3}\z/ }
387  
388 =head3 MESSAGES
389  
390 None.
391  
392 =head3 FORMAL SPECIFICATION
393  
394 language : LOCALE ∪ {⊥} → dom Catalog
395 let (l, c) = parse(first defined of wanted, config, env)
396 language = l if l ∈ dom Catalog
397 = cl(c) if cl(c) ∈ dom Catalog
398 = en otherwise
399  
400 =head3 PSEUDOCODE
401  
402 source := wanted, else config{language}, else the first set of
403 FILESYNC_LANG, LC_ALL, LC_MESSAGES, LANG
404 (language, country) := parse_locale(source)
405 if language has a catalogue: return language
406 if country_language(country) has a catalogue: return it
407 return en
408  
409 =cut
410  
411 1184 ▶sub language {
Subroutine language: called CC=10 SCAR=23.1
Pod documented
412 1184 my ($wanted) = @_;
413  
414 1184 my $source = $wanted;
415 1184 ▶ $source = $config{language} unless defined $source && length $source;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source and length $source 1153 31 1184
Condition66%2/3
defined $source and length $source
!ll&&!rl&&r
1153031
MC/DC50%1/2
defined $source and length $source
defined $source length $source
Truth table66%2/3
A and B
A= defined $sourceB= length $source
ABresult
0X0
100
111
416 1184 for my $variable (@LOCALE_VARIABLES) {
417 4634 ▶ last if defined $source && length $source;
Branch: 1 branch
BranchTrueFalseTotal
if defined $source and length $source 37 4597 4634
Condition66%2/3
defined $source and length $source
!ll&&!rl&&r
4597037
MC/DC50%1/2
defined $source and length $source
defined $source length $source
Truth table66%2/3
A and B
A= defined $sourceB= length $source
ABresult
0X0
100
111
418 4597 $source = $ENV{$variable};
419 }
420  
421 1184 my $parts = parse_locale($source);
422 1184 my $by_country = country_language($parts->{country});
423  
424 # The language named by the locale wins; the country is only a hint for
425 # a language that has no catalogue of its own.
426 my $chosen = (defined $parts->{language} && $CATALOG{ $parts->{language} })
427 ? $parts->{language}
428 1184 ▶ : (defined $by_country && $CATALOG{$by_country}) ? $by_country : $FALLBACK;
Branch: 2 branches
BranchTrueFalseTotal
defined $parts->{'language'} && $CATALOG{$parts->{'language'}} ? : 27 1157 1184
defined $by_country && $CATALOG{$by_country} ? : 5 1152 1157
Condition100%6/6
defined $parts->{"language"} and $CATALOG{$parts->{"language"}}
!ll&&!rl&&r
1155227
defined $by_country and $CATALOG{$by_country}
!ll&&!rl&&r
114935
MC/DC100%2/2
defined $parts->{"language"} and $CATALOG{$parts->{"language"}}
defined $parts->{"language"} $CATALOG{$parts->{"language"}}
MC/DC100%2/2
defined $by_country and $CATALOG{$by_country}
defined $by_country $CATALOG{$by_country}
Truth table100%3/3
A and B
A= defined $parts->{"language"}B= $CATALOG{$parts->{"language"}}
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= defined $by_countryB= $CATALOG{$by_country}
ABresult
0X0
100
111
429  
430 1184 return $chosen;
431 }
432  
433 =head2 message
434  
435 Purpose: render a catalogue entry.
436  
437 Args: C<$key>, optional C<\%args> for the placeholders and selectors, and an
438 optional C<$language> (code or locale name).
439  
440 Returns: the rendered string, without a trailing newline. A key that no
441 catalogue holds renders as the key itself followed by its arguments, so a
442 missing translation is visible rather than silent.
443  
444 Side Effects: none.
445  
446 Usage:
447  
448 my $text = message('path.unsafe', { path => 'a/../b', reason => 'parent path component' });
449  
450 =head3 EXAMPLE
451  
452 print message('word.file', { count => 3 }), "\n"; # 3 files
453  
454 =head3 API SPECIFICATION
455  
456 =head4 INPUT
457  
458 [
459 { name => 'key', type => 'string', min => 1 },
460 { name => 'args', type => 'hashref', optional => 1 },
461 { name => 'language', type => 'string', optional => 1 },
462 ]
463  
464 =head4 OUTPUT
465  
466 { type => 'string' }
467  
468 =head3 MESSAGES
469  
470 None; this is the function that renders them.
471  
472 =head3 FORMAL SPECIFICATION
473  
474 message : KEY × ARGS × LANG → TEXT
475 let l = language(lang?) ; e = Catalog(l)(key) if defined, else Catalog(en)(key)
476 message(key, a, lang?) = interpolate(select(e, a, l), a) if key ∈ dom Catalog(en) ∪ dom Catalog(l)
477 = key ⁀ describe(a) otherwise
478  
479 =head3 PSEUDOCODE
480  
481 language := language(requested)
482 entry := catalogue(language){key}, else catalogue(en){key}
483 if no entry: return key and its arguments
484 while entry is a selector hash:
485 pick the form named by the plural category of args{count}
486 or by args{gender}; fall back to "other"
487 replace each %{name}FMT with sprintf(FMT, args{name}); %% with %
488  
489 =cut
490  
491 1181 ▶sub message {
Subroutine message: called CC=4 SCAR=13.9
Pod documented
492 1181 my ($key, $args, $wanted) = @_;
493  
494 1181 ▶ $args = {} unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 524 657 1181
495 1181 my $language = language($wanted);
496  
497 1181 my $entry = $CATALOG{$language}{$key};
498 1181 ▶ $entry = $CATALOG{$FALLBACK}{$key} unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 1 1180 1181
499  
500 # An unknown key is a bug, but the person reading the error still
501 # deserves its arguments.
502 1181 ▶ return $key . _describe($args) unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 1 1180 1181
503  
504 1180 return _interpolate(_select($entry, $args, $language), $args);
505 }
506  
507 =head2 throw
508  
509 Purpose: raise a catalogued error.
510  
511 Args: C<$key>, optional C<\%args>, optional C<$language>.
512  
513 Returns: never returns.
514  
515 Side Effects: croaks with the rendered message, which reports the caller's
516 location; with C<$config{trace}> (or C<FILESYNC_TRACE>) set it confesses with a
517 full stack trace instead. L</strip_location> removes either for display.
518  
519 Usage:
520  
521 throw('snapshot.no_root') unless defined $root;
522  
523 =head3 EXAMPLE
524  
525 eval { throw('path.empty') };
526 print strip_location($@); # "empty path\n"
527  
528 =head3 API SPECIFICATION
529  
530 =head4 INPUT
531  
532 [
533 { name => 'key', type => 'string', min => 1 },
534 { name => 'args', type => 'hashref', optional => 1 },
535 { name => 'language', type => 'string', optional => 1 },
536 ]
537  
538 =head4 OUTPUT
539  
540 { type => 'void' }
541  
542 =head3 MESSAGES
543  
544 Whatever C<$key> names.
545  
546 =head3 FORMAL SPECIFICATION
547  
548 throw : KEY × ARGS × LANG ↛ ∅
549 throw(k, a, l) raises message(k, a, l) ⁀ "\n" ⁀ location
550  
551 =cut
552  
553 90 ▶sub throw {
Subroutine throw: called CC=2 SCAR=7.1
Pod documented
554 90 my ($key, $args, $wanted) = @_;
555  
556 # The newline keeps the location croak appends on a line of its own, which
557 # is what lets strip_location remove it without touching the message.
558 90 my $text = message($key, $args, $wanted) . "\n";
559 90 ▶ $config{trace} ? confess($text) : croak($text);
Branch: 1 branch
BranchTrueFalseTotal
$App::FileSync::I18N::config{'trace'} ? : 0 90 90
560 }
561  
562 =head2 warning
563  
564 Purpose: emit a catalogued warning.
565  
566 Args: as for L</throw>.
567  
568 Returns: 1.
569  
570 Side Effects: carps the rendered message to STDERR (or C<$SIG{__WARN__}>).
571  
572 Usage:
573  
574 warning('client.record_failed', { path => $path, error => $reason });
575  
576 =head3 EXAMPLE
577  
578 local $SIG{__WARN__} = sub { print "warned: ", strip_location($_[0]) };
579 warning('path.empty');
580  
581 =head3 API SPECIFICATION
582  
583 =head4 INPUT
584  
585 [
586 { name => 'key', type => 'string', min => 1 },
587 { name => 'args', type => 'hashref', optional => 1 },
588 { name => 'language', type => 'string', optional => 1 },
589 ]
590  
591 =head4 OUTPUT
592  
593 { type => 'integer', min => 1, max => 1 }
594  
595 =head3 MESSAGES
596  
597 Whatever C<$key> names.
598  
599 =head3 FORMAL SPECIFICATION
600  
601 warning(k, a, l) ⇒ STDERR' = STDERR ⁀ message(k, a, l) ⁀ location
602  
603 =cut
604  
605 0 ▶sub warning {
Subroutine warning: not called CC=1 SCAR=6.9
Pod documented
606 0 my ($key, $args, $wanted) = @_;
607  
608 0 carp(message($key, $args, $wanted) . "\n");
609 0 return 1;
610 }
611  
612 =head2 os_error
613  
614 Purpose: the operating-system reason behind a failed call.
615  
616 Args: optional C<$error>: an L<autodie::exception>, or anything else.
617  
618 Returns: the C<$!> string the exception recorded, or the current C<$!>.
619  
620 Side Effects: none.
621  
622 Usage:
623  
624 eval { open my $fh, '<', $path; 1 } or throw('io.read', { path => $path, error => os_error($@) });
625  
626 =head3 EXAMPLE
627  
628 use autodie;
629 eval { opendir my $dh, '/nonexistent' };
630 print os_error($@), "\n"; # No such file or directory
631  
632 =head3 API SPECIFICATION
633  
634 =head4 INPUT
635  
636 [ { name => 'error', type => 'scalar', optional => 1 } ]
637  
638 =head4 OUTPUT
639  
640 { type => 'string' }
641  
642 =head3 MESSAGES
643  
644 None.
645  
646 =head3 FORMAL SPECIFICATION
647  
648 os_error(e) = e.errno if e ∈ AutodieException
649 = errno otherwise
650  
651 =cut
652  
653 4 ▶sub os_error {
Subroutine os_error: called CC=4 SCAR=14.2
Pod documented
654 4 my ($error) = @_;
655  
656 4 ▶ my $text = (blessed($error) && $error->can('errno')) ? $error->errno : $!;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($error) && $error->can('errno') ? : 3 1 4
Condition66%2/3
builtin::blessed($error) and $error->can("errno")
!ll&&!rl&&r
103
MC/DC50%1/2
builtin::blessed($error) and $error->can("errno")
builtin::blessed($error) $error->can("errno")
Truth table66%2/3
A and B
A= builtin::blessed($error)B= $error->can("errno")
ABresult
0X0
100
111
657 4 ▶ return defined $text ? "$text" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 4 0 4
658 }
659  
660 =head2 strip_location
661  
662 Purpose: turn a raised error into text for a person or a log line.
663  
664 Args: C<$error> as caught in C<$@>.
665  
666 Returns: the message without the C<at FILE line N.> suffix croak adds, without
667 a confess stack trace, and without a trailing newline.
668  
669 Side Effects: none.
670  
671 Usage:
672  
673 print STDERR strip_location($@), "\n";
674  
675 =head3 EXAMPLE
676  
677 eval { throw('path.empty') };
678 print strip_location($@), "\n"; # empty path
679  
680 =head3 API SPECIFICATION
681  
682 =head4 INPUT
683  
684 [ { name => 'error', type => 'scalar', optional => 1 } ]
685  
686 =head4 OUTPUT
687  
688 { type => 'string' }
689  
690 =head3 MESSAGES
691  
692 None.
693  
694 =head3 FORMAL SPECIFICATION
695  
696 strip(m ⁀ "\n at " ⁀ f ⁀ " line " ⁀ n ⁀ "." ⁀ trace) = m
697 strip(m ⁀ "\n") = m
698 strip(m) = m otherwise
699  
700 =cut
701  
702 274 ▶sub strip_location {
Subroutine strip_location: called CC=2 SCAR=6.9
Pod documented
703 274 my ($error) = @_;
704  
705 274 ▶ my $text = defined $error ? "$error" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $error ? : 118 156 274
706  
707 # throw() ends its message with a newline, so croak's location (and a
708 # confess trace) always starts on a fresh line and cannot be confused
709 # with a path inside the message.
710 274 $text =~ s/\n\s*at [^\n]+ line \d+[^\n]*\.\n(?:\t[^\n]*\n?)*\z/\n/;
711  
712 # autodie and plain die put the location on the same line instead.
713 274 $text =~ s/ at \S+ line \d+\.?\s*\z//;
714 274 $text =~ s/\s+\z//;
715  
716 274 return $text;
717 }
718  
719 # _select
720 # Purpose: choose the plural or gender form of a catalogue entry.
721 # Entry: $entry is a string or a selector hash; $args holds count/gender;
722 # $language names the plural rule.
723 # Exit: returns a string (an empty one if a selector has no usable form).
724 # Side effects: none.
725 1180 ▶sub _select :Private {
Subroutine _select: called CC=10 SCAR=23.7
726 1180 my ($entry, $args, $language) = @_;
727  
728 # Selectors may nest (gender, then count), so keep choosing until a
729 # plain string is left.
730 1180 ▶ while (ref($entry) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq "HASH") 75 1180 1255
731 75 ▶ my $by = $entry->{$SELECT_KEY} || $SELECT_COUNT;
Condition33%1/3
$entry->{$SELECT_KEY} || $SELECT_COUNT
l!l&&r!l&&!r
7500
MC/DC0%0/2
$entry->{$SELECT_KEY} || $SELECT_COUNT
$entry->{$SELECT_KEY} $SELECT_COUNT
Truth table33%1/3
A || B
A= $entry->{$SELECT_KEY}B= $SELECT_COUNT
ABresult
1X1
011
000
732 75 my $form;
733 75 ▶ if ($by eq $SELECT_GENDER) {
Branch: 1 branch
BranchTrueFalseTotal
if ($by eq $SELECT_GENDER) { } 4 71 75
734 4 ▶ $form = defined $args->{gender} ? $args->{gender} : $OTHER;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'gender'} ? : 3 1 4
735 } else {
736 71 ▶ my $rule = $PLURAL_RULE{$language} || $PLURAL_RULE{$FALLBACK};
Condition33%1/3
$PLURAL_RULE{$language} || $PLURAL_RULE{$FALLBACK}
l!l&&r!l&&!r
7100
MC/DC0%0/2
$PLURAL_RULE{$language} || $PLURAL_RULE{$FALLBACK}
$PLURAL_RULE{$language} $PLURAL_RULE{$FALLBACK}
Truth table33%1/3
A || B
A= $PLURAL_RULE{$language}B= $PLURAL_RULE{$FALLBACK}
ABresult
1X1
011
000
737 my $count = defined $args->{count} && $args->{count} =~ /\A-?\d+(?:\.\d+)?\z/
738 71 ▶ ? $args->{count} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'count'} && $args->{'count'} =~ /\A-?\d+(?:\.\d+)?\z/ ? : 70 1 71
Condition66%2/3
defined $args->{"count"} and $args->{"count"} =~ /\A-?\d+(?:\.\d+)?\z/
!ll&&!rl&&r
0170
MC/DC50%1/2
defined $args->{"count"} and $args->{"count"} =~ /\A-?\d+(?:\.\d+)?\z/
defined $args->{"count"} $args->{"count"} =~ /\A-?\d+(?:\.\d+)?\z/
Truth table66%2/3
A and B
A= defined $args->{"count"}B= $args->{"count"} =~ /\A-?\d+(?:\.\d+)?\z/
ABresult
0X0
100
111
739 71 $form = $rule->($count);
740 }
741 75 ▶ $entry = defined $entry->{$form} ? $entry->{$form} : $entry->{$OTHER};
Branch: 1 branch
BranchTrueFalseTotal
defined $entry->{$form} ? : 74 1 75
742 }
743  
744 1180 ▶ return defined $entry ? $entry : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $entry ? : 1180 0 1180
745 342 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
746  
747 # _interpolate
748 # Purpose: replace %{name}FMT placeholders and %% in a template.
749 # Entry: $template is a string; $args is a hashref.
750 # Exit: returns the rendered string.
751 # Side effects: none. sprintf runs with warnings off for the conversion only,
752 # so an argument of the wrong type renders rather than warns.
753 1180 ▶sub _interpolate :Private {
Subroutine _interpolate: called CC=2 SCAR=6.9
754 1180 my ($template, $args) = @_;
755  
756 1180 $template =~ s{%(?:(%)|\{(\w+)\}([-+ 0#]*\d*(?:\.\d+)?[a-zA-Z]))}{
757 1818 ▶ defined $1 ? '%' : _format($3, $args->{$2})
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 10 1808 1818
758 }ge;
759  
760 1180 return $template;
761 342 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
762  
763 # _format
764 # Purpose: sprintf one value, treating undef as empty (or 0 for numbers).
765 # Entry: $conversion is a sprintf conversion without the leading %.
766 # Exit: returns the formatted value.
767 # Side effects: none.
768 1808 ▶sub _format :Private {
Subroutine _format: called CC=4 SCAR=13.9
769 1808 my ($conversion, $value) = @_;
770  
771 1808 ▶ my $numeric = $conversion =~ /[dioxXeEfgGbBu]\z/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$conversion =~ /[dioxXeEfgGbBu]\z/ ? : 395 1413 1808
772 1808 ▶ $value = $numeric ? 0 : '' unless defined $value;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $value 5 1803 1808
$numeric ? : 4 1 5
773  
774 342 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
775 1808 return sprintf('%' . $conversion, $value);
776 342 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
777  
778 # _describe
779 # Purpose: show the arguments of a message whose key has no entry.
780 # Entry: $args is a hashref.
781 # Exit: returns " (k=v, ...)" or "" when there are none.
782 # Side effects: none.
783 1 ▶sub _describe :Private {
Subroutine _describe: called CC=3 SCAR=11.3
784 1 my ($args) = @_;
785  
786 1 ▶ my @pairs = map { "$_=" . (defined $args->{$_} ? $args->{$_} : '') } sort keys %{$args};
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{$_} ? : 1 0 1
787 1 ▶ return @pairs ? ' (' . join(', ', @pairs) . ')' : '';
Branch: 1 branch
BranchTrueFalseTotal
@pairs ? : 1 0 1
788 342 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
789  
790 342 1;
791  
792 __END__
« blib/lib/App/FileSync/Server.pm ↑ Summary blib/lib/App/FileSync/Delta.pm »