blib/lib/App/FileSync/Settings.pm

filter: Statementstmt 93.9% 232 / 247 Branchbran 82.8% 58 / 70 Conditioncond 50.0% 24 / 48 MC/DCmcdc 33.3% 9 / 27 Subroutinesub 97.9% 47 / 48 Podpod 100% 5 / 5 totaltotal 84.2% 375 / 445 CC 63 SCAR 21.6
CC
63
Cov
86%
_labels_for
42.0
explain_repos
18.5
explain
12.6
CRAP 8.6
« blib/lib/App/FileSync/Client.pm ↑ Summary blib/lib/App/FileSync/Admin.pm »
1 package App::FileSync::Settings;
2  
3 # Process-wide settings (logging and SSH defaults) read through
4 # Object::Configure, and the logger built from them. The repos themselves stay
5 # in ~/.filesync/config.json, which "filesync init" writes and the admin tool
6 # edits; this module never touches that store.
7  
8 # First, so the Windows end-of-scope hook is chosen before Log::Abstraction
9 # (through namespace::clean) or Sub::Private loads B::Hooks::EndOfScope.
10 331 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 331 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 331 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 331 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 # 0.41 for explain_sources(), which the settings report uses; an older copy
17 # autoloads that name as a config key and dies with "No such config key".
18 331 ▶use Config::Abstraction 0.41;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 331 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 331 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 331 ▶use List::Util qw(any first);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 # 0.36 for the structured fields the client passes as a trailing hashref;
23 # an older copy appends it to the message as "HASH(0x...)" in a log file and
24 # records an empty entry in an array logger.
25 331 ▶use Log::Abstraction 0.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 331 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 331 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 331 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 331 ▶use App::FileSync::Args qw(named);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 331 ▶use App::FileSync::I18N qw(throw);
Subroutine BEGIN: called CC=1 SCAR=0.0
32 331 ▶use App::FileSync::IO qw(ensure_dir);
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 331 ▶use version; our $VERSION = version->declare('0.002.1');
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 # The hook predicates moved to App::FileSync::Platform, which must load before
37 # this module's dependencies; these names are kept for existing callers.
38 {
39 331 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
40 331 *wants_plain_end_of_scope_hook = \&App::FileSync::Platform::wants_plain_end_of_scope_hook;
41 331 *use_plain_end_of_scope_hook = \&App::FileSync::Platform::use_plain_end_of_scope_hook;
42 }
43  
44 # Package variables, not Readonly: they are documented and tests may localise them.
45 331 our $DEFAULT_FORMAT = '%level%: %message%';
46 331 our $DEFAULT_LEVEL = 'warning';
47 331 our $CONFIG_BASENAME = 'app-filesync.json';
48  
49 # Defaults for every SSH repo. A repo's own config still wins, so one machine
50 # can point at another identity without repeating the common settings.
51 331 our $DEFAULT_SERVER_COMMAND = 'filesync-server';
52  
53 331 our @VALID_LEVELS = qw(
54 trace debug info informational notice warn warning error err
55 crit critical fatal alert emerg emergency panic
56 );
57  
58 # The process-wide settings, in the order "filesync settings" prints them.
59 331 our @SETTING_KEYS = qw(
60 log_level log_format log_file
61 ssh_identity ssh_known_hosts server_command
62 );
63  
64 # How each repo-level SSH key corresponds to the process setting it falls back
65 # to. The names differ only because the repo config uses shorter keys.
66 331 our %REPO_SSH_KEYS = (
67 ssh_identity => 'identity',
68 ssh_known_hosts => 'known_hosts',
69 server_command => 'server_command',
70 );
71 331 our @REPO_SSH_SETTINGS = qw(ssh_identity ssh_known_hosts server_command);
72  
73 # Section names Object::Configure and Config::Abstraction use.
74 331 Readonly::Scalar my $CLASS_SECTION => 'App__FileSync';
75 331 Readonly::Scalar my $UNIVERSAL_SECTION => 'UNIVERSAL';
76 331 Readonly::Scalar my $CONF_DIR => '.conf';
77  
78 # Settings that only a repo records: there is no process-wide layer, and ssh's
79 # own default applies when the repo leaves them out.
80 331 Readonly my @REPO_ONLY => ([ port => '22' ], [ host_key_checking => 'yes' ]);
81  
82 # Provenance labels for "filesync settings".
83 331 Readonly::Scalar my $LABEL_DEFAULT => 'built-in default';
84 331 Readonly::Scalar my $LABEL_SSH_DEFAULT => 'ssh default';
85 331 Readonly::Scalar my $LABEL_UNKNOWN => 'unknown source';
86  
87 # Object::Configure's search order for a universal file beside the settings file.
88 331 Readonly my @UNIVERSAL_EXTENSIONS => qw(.conf .yml .yaml .json);
89  
90 # The arguments load, explain and logger share.
91 331 my %FILE_ARGS = (
92 config_file => { type => 'string', optional => 1 },
93 config_dirs => { type => 'arrayref', optional => 1 },
94 );
95  
96 =encoding utf8
97  
98 =head1 NAME
99  
100 App::FileSync::Settings - process-wide settings and logging for App::FileSync
101  
102 =head1 SYNOPSIS
103  
104 use App::FileSync::Settings;
105  
106 my $logger = App::FileSync::Settings::logger(verbose => 1);
107 $logger->error('...');
108  
109 my $settings = App::FileSync::Settings::load();
110 my $level = $settings->{log_level};
111  
112 my $report = App::FileSync::Settings::explain();
113 printf "%s = %s (%s)\n", $_->{key}, $_->{value}, $_->{label}
114 for @{ $report->{settings} };
115  
116 =head1 DESCRIPTION
117  
118 Settings that apply to the process rather than to one repo - the log level,
119 format and destination, plus the SSH identity, known-hosts file and remote
120 server command - are read through L<Object::Configure>. The repos themselves
121 remain in F<~/.filesync/config.json>, which C<filesync init> writes; this
122 module does not replace that store.
123  
124 The settings file is F<~/.conf/app-filesync.json> when it exists, or the path in
125 C<FILESYNC_SETTINGS>. The section key is C<App__FileSync>, and a C<UNIVERSAL>
126 section in the same directory applies to every class that uses
127 Object::Configure. Environment variables named C<App__FileSync__I<key>>
128 override the file:
129  
130 # ~/.conf/app-filesync.json
131 { "App__FileSync": { "log_level": "debug", "log_format": "%level%: %message%" } }
132  
133 # or
134 export App__FileSync__log_level=debug
135  
136 C<log_file> sends the log to a file instead of standard error; leading
137 directories are created. C<log_format> is a L<Log::Abstraction> format string.
138  
139 C<ssh_identity>, C<ssh_known_hosts> and C<server_command> are the defaults for
140 every SSH repo, so a per-repo C<identity>, C<known_hosts> or C<server_command>
141 (written by C<filesync init --identity> and friends) only has to be set when it
142 differs. C<server_command> defaults to C<filesync-server>:
143  
144 { "App__FileSync": {
145 "ssh_identity" : "~/.ssh/filesync_ed25519",
146 "ssh_known_hosts" : "~/.ssh/filesync_known_hosts",
147 "server_command" : "/usr/local/bin/filesync-server"
148 } }
149  
150 Command output (sync summaries, plans, C<--json>) is written to standard output
151 by the commands themselves; the logger carries diagnostics on standard error,
152 so a cron job can separate the two. C<--verbose> raises the level to C<debug>
153 and C<--quiet> lowers it to C<error> for that run, overriding the file.
154  
155 C<wants_plain_end_of_scope_hook> and C<use_plain_end_of_scope_hook> are aliases
156 of the functions in L<App::FileSync::Platform>, kept for existing callers.
157  
158 =head1 FUNCTIONS
159  
160 =head2 config_file
161  
162 Purpose: the settings file that would be used.
163  
164 Args: an optional explicit path.
165  
166 Returns: the explicit path when one is given; otherwise C<FILESYNC_SETTINGS> or
167 F<~/.conf/app-filesync.json> if that file exists; otherwise C<undef>.
168  
169 Side Effects: none.
170  
171 Usage:
172  
173 my $file = App::FileSync::Settings::config_file();
174  
175 =head3 EXAMPLE
176  
177 my $file = App::FileSync::Settings::config_file() // 'none';
178 print "settings: $file\n";
179  
180 =head3 API SPECIFICATION
181  
182 =head4 INPUT
183  
184 [ { name => 'given', type => 'string', optional => 1 } ]
185  
186 =head4 OUTPUT
187  
188 { type => 'string', optional => 1 }
189  
190 =head3 MESSAGES
191  
192 None.
193  
194 =head3 FORMAL SPECIFICATION
195  
196 config_file(g) = g if g ≠ ""
197 config_file(g) = d if d = default_path ∧ d ∈ dom FS
198 config_file(g) = ⊥ otherwise
199  
200 =cut
201  
202 647 ▶sub config_file {
Subroutine config_file: called CC=5 SCAR=16.2
Pod documented
203 647 my ($given) = @_;
204  
205 # A file named on the command line is used as given, so a typo is an
206 # error later. A stale FILESYNC_SETTINGS must not fail every command:
207 # it is only a default, so a missing one is ignored.
208 647 my $path = $given;
209 647 ▶ unless (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path and length $path) 628 19 647
Condition66%2/3
defined $path and length $path
!ll&&!rl&&r
628019
MC/DC50%1/2
defined $path and length $path
defined $path length $path
Truth table66%2/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
210 628 $path = _default_config_path();
211 628 ▶ undef $path unless defined $path && -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -e $path 24 604 628
Condition66%2/3
defined $path and -e $path
!ll&&!rl&&r
024604
MC/DC50%1/2
defined $path and -e $path
defined $path -e $path
Truth table66%2/3
A and B
A= defined $pathB= -e $path
ABresult
0X0
100
111
212 }
213  
214 647 return $path;
215 }
216  
217 =head2 load
218  
219 Purpose: the merged process settings.
220  
221 Args: optional C<config_file> and C<config_dirs> (as for
222 L<Object::Configure/configure>).
223  
224 Returns: a hashref with every key in C<@SETTING_KEYS>, built-in defaults
225 overlaid by the settings file, the C<UNIVERSAL> section and C<App__FileSync__*>
226 environment variables.
227  
228 Side Effects: reads the settings file. Dies (through Object::Configure) when
229 an explicit file does not exist.
230  
231 Usage:
232  
233 my $settings = App::FileSync::Settings::load(config_file => $path);
234  
235 =head3 EXAMPLE
236  
237 print App::FileSync::Settings::load()->{log_level}, "\n"; # warning
238  
239 =head3 API SPECIFICATION
240  
241 =head4 INPUT
242  
243 {
244 config_file => { type => 'string', optional => 1 },
245 config_dirs => { type => 'arrayref', optional => 1 },
246 }
247  
248 =head4 OUTPUT
249  
250 { type => 'hashref' }
251  
252 =head3 MESSAGES
253  
254 Key Meaning Resolution
255 args.invalid an argument has the wrong type fix the call
256  
257 Object::Configure's own error for a missing explicit file is passed through.
258  
259 =head3 FORMAL SPECIFICATION
260  
261 load(a) = defaults ⊕ file(config_file(a)) ⊕ universal ⊕ env
262  
263 =cut
264  
265 637 ▶sub load {
Subroutine load: called CC=3 SCAR=11.0
Pod documented
266 637 my $args = named(\@_, {%FILE_ARGS}, 'Settings::load');
267  
268 637 my $config_file = config_file($args->{config_file});
269  
270 my %params = (
271 637 %{ _defaults() },
272 # We build the logger ourselves; this keeps Object::Configure from
273 # constructing its default Log::Log4perl backend as a side effect.
274 logger => [],
275 );
276 637 ▶ $params{config_file} = $config_file if defined $config_file;
Branch: 1 branch
BranchTrueFalseTotal
if defined $config_file 616 21 637
277 637 ▶ $params{config_dirs} = $args->{config_dirs} if $args->{config_dirs};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"config_dirs"} 0 637 637
278  
279 637 my $settings = Object::Configure::configure('App::FileSync', \%params);
280 636 delete $settings->{logger};
281  
282 636 return $settings;
283 }
284  
285 =head2 explain
286  
287 Purpose: where each effective setting came from, for C<filesync settings>.
288  
289 Args: as L</load>.
290  
291 Returns: C<{ settings_file =E<gt> $path_or_undef, settings =E<gt> \@rows }>, one
292 row per key in C<@SETTING_KEYS>. Each row has the effective C<value>, a
293 C<source> of C<default>, C<file>, C<env> or C<merged>, and a human-readable
294 C<label> naming the file section, environment variable or built-in default
295 that supplied it.
296  
297 The values are whatever L</load> returns; the provenance is reconstructed from
298 the same layers Object::Configure merges. A value no modelled layer accounts
299 for (a C<global> section, say) is reported as C<merged> rather than claimed as
300 a default.
301  
302 Side Effects: reads the settings file and any universal file beside it.
303  
304 Usage:
305  
306 my $report = App::FileSync::Settings::explain();
307  
308 =head3 EXAMPLE
309  
310 for my $row (@{ App::FileSync::Settings::explain()->{settings} }) {
311 printf "%-16s %-20s %s\n", $row->{key}, $row->{value}, $row->{label};
312 }
313  
314 =head3 API SPECIFICATION
315  
316 =head4 INPUT
317  
318 {
319 config_file => { type => 'string', optional => 1 },
320 config_dirs => { type => 'arrayref', optional => 1 },
321 }
322  
323 =head4 OUTPUT
324  
325 {
326 type => 'hashref',
327 schema => {
328 settings_file => { type => 'string', optional => 1 },
329 settings => { type => 'arrayref' },
330 },
331 }
332  
333 =head3 MESSAGES
334  
335 As L</load>.
336  
337 =head3 FORMAL SPECIFICATION
338  
339 ∀ k : SETTING_KEYS •
340 row(k).value = load()(k)
341 row(k).source = last layer ∈ ⟨default, universal, class⟩ that sets k,
342 or merged if that layer's value ≠ row(k).value
343  
344 =head3 PSEUDOCODE
345  
346 load the settings
347 explain the class and universal sections of the settings file, if any
348 for each key:
349 start from the built-in default
350 let the universal section, then the class section, override it
351 without a file, let UNIVERSAL__key then App__FileSync__key override it
352 if the loaded value differs from the winner, call it merged
353  
354 =cut
355  
356 8 ▶sub explain {
Subroutine explain: called CC=12 SCAR=25.3
Pod documented
357 8 my $args = named(\@_, {%FILE_ARGS}, 'Settings::explain');
358  
359 8 my $config_file = config_file($args->{config_file});
360 8 my $settings = load(%{$args});
361 8 my $defaults = _defaults();
362  
363 # Each layer is [ section explanation, label for a file entry ], lowest first.
364 8 my @layers;
365 8 ▶ if (defined $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config_file) 6 2 8
366 6 my $universal = _universal_file($config_file);
367 6 ▶ push @layers, [ _explanation($universal, $UNIVERSAL_SECTION), $UNIVERSAL_SECTION, "$universal [$UNIVERSAL_SECTION]" ]
Branch: 1 branch
BranchTrueFalseTotal
if defined $universal 2 4 6
368 if defined $universal;
369 6 push @layers, [ _explanation($config_file, $CLASS_SECTION), $CLASS_SECTION, "$config_file [$CLASS_SECTION]" ];
370 }
371  
372 8 my @rows;
373 8 for my $key (@SETTING_KEYS) {
374 48 my %row = (key => $key, value => $settings->{$key}, source => 'default', label => $LABEL_DEFAULT);
375 48 my $winner = $defaults->{$key};
376  
377 48 ▶ if (defined $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config_file) { } 36 12 48
378 36 for my $layer (@layers) {
379 48 my ($explanation, $section, $file_label) = @{$layer};
380 48 ▶ my $entry = _pick($explanation, $section, $key) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = _pick($explanation, $section, $key) or next 8 40 48
381 8 $row{source} = $entry->{type};
382 8 ▶ $row{label} = $entry->{type} eq 'env' ? $entry->{label} : $file_label;
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'type'} eq 'env' ? : 1 7 8
383 8 $winner = $entry->{value};
384 }
385 } else {
386 # No settings file: Object::Configure falls back to environment
387 # variables only, universal ones first and class ones last.
388 12 for my $section ($UNIVERSAL_SECTION, $CLASS_SECTION) {
389 24 ▶ my $name = _env_key("${section}__$key") // next;
Condition100%2/2
_env_key("${section}__$key") // (next)
l!l
420
MC/DC100%1/1
_env_key("${section}__$key") // (next)
_env_key("${section}__$key")
Truth table100%2/2
A
A= _env_key("${section}__$key")
Aresult
11
00
390 4 @row{qw(source label)} = ('env', $name);
391 4 $winner = $ENV{$name};
392 }
393 }
394  
395 48 ▶ if (_differs($settings->{$key}, $winner)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_differs($settings->{$key}, $winner)) 0 48 48
396 0 $row{source} = 'merged';
397 0 ▶ $row{label} = join(' + ', @{ _labels_for($key, map { $_->[0] } @layers) }) || $LABEL_UNKNOWN;
Condition0%0/3
join(' + ', @{_labels_for($key, map({$_->[0];} @layers));}) || $LABEL_UNKNOWN
l!l&&r!l&&!r
000
MC/DC0%0/2
join(' + ', @{_labels_for($key, map({$_->[0];} @layers));}) || $LABEL_UNKNOWN
join(' + ', @{_labels_for($key, map({$_->[0];} @layers));}) $LABEL_UNKNOWN
Truth table0%0/3
A || B
A= join(' + ', @{_labels_for($key, map({$_->[0];} @layers));})B= $LABEL_UNKNOWN
ABresult
1X1
011
000
398 }
399  
400 48 push @rows, \%row;
401 }
402  
403 8 return { settings_file => $config_file, settings => \@rows };
404 }
405  
406 =head2 explain_repos
407  
408 Purpose: how the SSH settings resolve for every repo in a client config.
409  
410 Args: C<config> (the hashref from C<App::FileSync::Config::load_client>),
411 C<report> (the result of L</explain>), C<config_file> (the client config path,
412 used in labels).
413  
414 Returns: an arrayref, one entry per repo in name order, with C<repo>,
415 C<transport>, C<server> (when the repo records one) and C<ssh>: one
416 C<{key, value, source, label}> row per setting, where C<source> is C<repo>
417 (the repo's own entry), C<process> (the settings reported by C<explain>) or
418 C<default> (ssh's own default). C<port> and C<host_key_checking> rows carry
419 C<repo_only =E<gt> 1>. C<ssh> is C<undef> for the local transport, which never
420 runs ssh.
421  
422 Side Effects: none.
423  
424 Usage:
425  
426 my $repos = App::FileSync::Settings::explain_repos(
427 config => $config, report => App::FileSync::Settings::explain(), config_file => $path,
428 );
429  
430 =head3 EXAMPLE
431  
432 for my $repo (@{ $repos }) {
433 next unless $repo->{ssh};
434 print "$repo->{repo}: $_->{key} = $_->{value} ($_->{label})\n" for @{ $repo->{ssh} };
435 }
436  
437 =head3 API SPECIFICATION
438  
439 =head4 INPUT
440  
441 {
442 config => { type => 'hashref', optional => 1 },
443 report => { type => 'hashref', optional => 1 },
444 config_file => { type => 'string', optional => 1 },
445 }
446  
447 =head4 OUTPUT
448  
449 { type => 'arrayref' }
450  
451 =head3 MESSAGES
452  
453 Key Meaning Resolution
454 args.invalid an argument has the wrong type fix the call
455  
456 =head3 FORMAL SPECIFICATION
457  
458 ∀ r : dom config.repos • ∀ k : REPO_SSH_SETTINGS •
459 value(r, k) = repo(r)(k) if repo(r)(k) ≠ ""
460 = process(k) else if process(k) ≠ ""
461 = "" otherwise
462  
463 =head3 PSEUDOCODE
464  
465 for each repo, by name:
466 record its transport and server
467 if it uses ssh:
468 for each SSH setting take the repo's value, else the process
469 setting, else ssh's default
470 add the repo-only port and host-key-checking rows
471  
472 =cut
473  
474 3 ▶sub explain_repos {
Subroutine explain_repos: called CC=18 SCAR=29.2
Pod documented
475 3 my $args = named(\@_, {
476 config => { type => 'hashref', optional => 1 },
477 report => { type => 'hashref', optional => 1 },
478 config_file => { type => 'string', optional => 1 },
479 }, 'Settings::explain_repos');
480  
481 3 ▶ my $config = $args->{config} || {};
Condition50%1/2
$args->{'config'} || {}
l!l
30
MC/DC0%0/1
$args->{'config'} || {}
$args->{'config'}
Truth table50%1/2
A
A= $args->{'config'}
Aresult
11
00
482 3 ▶ my %process = map { $_->{key} => $_ } @{ ($args->{report} || {})->{settings} || [] };
Condition50%2/4
+($args->{'report'} || {})->{'settings'} || []
l!l
30
$args->{'report'} || {}
l!l
30
MC/DC0%0/1
+($args->{'report'} || {})->{'settings'} || []
$args->{'report'}
Truth table50%1/2
A
A= $args->{'report'}
Aresult
11
00
483  
484 3 my @repos;
485 3 ▶ for my $name (sort keys %{ $config->{repos} || {} }) {
Condition50%1/2
$config->{'repos'} || {}
l!l
30
MC/DC0%0/1
$config->{'repos'} || {}
$config->{'repos'}
Truth table50%1/2
A
A= $config->{'repos'}
Aresult
11
00
486 9 my $repo = $config->{repos}{$name};
487 9 ▶ $repo = {} unless ref($repo) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $repo eq "HASH" 0 9 9
488  
489 9 ▶ my $entry = { repo => $name, transport => $repo->{transport} || 'ssh', ssh => undef };
Condition50%1/2
$repo->{'transport'} || 'ssh'
l!l
90
MC/DC0%0/1
$repo->{'transport'} || 'ssh'
$repo->{'transport'}
Truth table50%1/2
A
A= $repo->{'transport'}
Aresult
11
00
490 9 ▶ $entry->{server} = $repo->{server} if _set($repo->{server});
Branch: 1 branch
BranchTrueFalseTotal
if _set($repo->{"server"}) 6 3 9
491  
492 # The local transport never runs ssh, so there is nothing to resolve.
493 9 ▶ if ($entry->{transport} eq 'ssh') {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"transport"} eq "ssh") 6 3 9
494 6 my $repo_label = _repo_label($args->{config_file}, $name);
495 6 my @rows;
496 6 for my $key (@REPO_SSH_SETTINGS) {
497 18 my $value = $repo->{ $REPO_SSH_KEYS{$key} };
498 18 my $setting = $process{$key};
499  
500 18 ▶ if (_set($value)) {
Branch: 2 branches
BranchTrueFalseTotal
if (_set($value)) { } 3 15 18
elsif ($setting and _set($setting->{'value'})) { } 8 7 15
501 3 push @rows, { key => $key, value => $value, source => 'repo', label => $repo_label };
502 ▶ } elsif ($setting && _set($setting->{value})) {
Condition66%2/3
$setting and _set($setting->{"value"})
!ll&&!rl&&r
078
MC/DC50%1/2
$setting and _set($setting->{"value"})
$setting _set($setting->{"value"})
Truth table66%2/3
A and B
A= $settingB= _set($setting->{"value"})
ABresult
0X0
100
111
503 8 push @rows, { key => $key, value => $setting->{value}, source => 'process', label => $setting->{label} };
504 } else {
505 7 push @rows, { key => $key, value => '', source => 'default', label => $LABEL_SSH_DEFAULT };
506 }
507 }
508  
509 # The transport omits -p and StrictHostKeyChecking defaults to yes.
510 6 for my $only (@REPO_ONLY) {
511 12 my ($key, $default) = @{$only};
512 12 my $set = _set($repo->{$key});
513 push @rows, {
514 key => $key,
515 repo_only => 1,
516 12 ▶ value => $set ? $repo->{$key} : $default,
Branch: 3 branches
BranchTrueFalseTotal
$set ? : 6 6 12
$set ? : 6 6 12
$set ? : 6 6 12
517 source => $set ? 'repo' : 'default',
518 label => $set ? $repo_label : $LABEL_SSH_DEFAULT,
519 };
520 }
521 6 $entry->{ssh} = \@rows;
522 }
523  
524 9 push @repos, $entry;
525 }
526  
527 3 return \@repos;
528 }
529  
530 =head2 logger
531  
532 Purpose: the diagnostics logger for this run.
533  
534 Args: as L</load>, plus C<level> (overrides the settings), C<verbose> (debug)
535 and C<quiet> (errors only). A command-line flag describes this run, so it
536 beats the settings file.
537  
538 Returns: a L<Log::Abstraction> writing to standard error, or to C<log_file>.
539  
540 Side Effects: reads the settings; creates C<log_file>'s directory.
541  
542 Usage:
543  
544 my $logger = App::FileSync::Settings::logger(verbose => $opts{verbose});
545  
546 =head3 EXAMPLE
547  
548 my $logger = App::FileSync::Settings::logger(level => 'info');
549 $logger->info('starting');
550  
551 =head3 API SPECIFICATION
552  
553 =head4 INPUT
554  
555 {
556 config_file => { type => 'string', optional => 1 },
557 config_dirs => { type => 'arrayref', optional => 1 },
558 level => { type => 'string', optional => 1 },
559 verbose => { type => 'boolean', optional => 1 },
560 quiet => { type => 'boolean', optional => 1 },
561 }
562  
563 =head4 OUTPUT
564  
565 { type => 'object', isa => 'Log::Abstraction' }
566  
567 =head3 MESSAGES
568  
569 Key Meaning Resolution
570 settings.bad_level log_level is not a known level use one of @VALID_LEVELS
571 io.mkdir log_file's directory cannot be made fix log_file
572  
573 =head3 FORMAL SPECIFICATION
574  
575 level = debug if verbose
576 = error else if quiet
577 = args.level else if set
578 = settings.log_level else if set
579 = warning otherwise
580 pre lc level ∈ lc VALID_LEVELS
581  
582 =head3 PSEUDOCODE
583  
584 load the settings
585 choose the level: argument, then settings, then the default
586 reject an unknown level
587 send output to log_file (creating its directory) or standard error
588 build the logger; apply --verbose or --quiet over it
589  
590 =cut
591  
592 613 ▶sub logger {
Subroutine logger: called CC=6 SCAR=17.9
Pod documented
593 613 my $args = named(\@_, {
594 %FILE_ARGS,
595 level => { type => 'string', optional => 1 },
596 verbose => { type => 'scalar', optional => 1 },
597 quiet => { type => 'scalar', optional => 1 },
598 }, 'Settings::logger');
599  
600 613 my $settings = load(map { $_ => $args->{$_} } grep { exists $args->{$_} } keys %FILE_ARGS);
601  
602 613 ▶ my $level = first { _set($_) } $args->{level}, $settings->{log_level}, $DEFAULT_LEVEL;
Subroutine __ANON__: called CC=1 SCAR=0.0
603 throw('settings.bad_level', { level => $level, valid => join(', ', @VALID_LEVELS) })
604 613 ▶ unless any { lc($_) eq lc($level) } @VALID_LEVELS;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { lc $_ eq lc $level; } , @App::FileSync::Settings::VALID_LEVELS) 1 612 613
605  
606 612 ▶ my $format = _set($settings->{log_format}) ? $settings->{log_format} : $DEFAULT_FORMAT;
Branch: 1 branch
BranchTrueFalseTotal
_set($settings->{'log_format'}) ? : 612 0 612
607  
608 612 my $destination = { fd => \*STDERR };
609 612 ▶ if (_set($settings->{log_file})) {
Branch: 1 branch
BranchTrueFalseTotal
if (_set($settings->{"log_file"})) 3 609 612
610 3 ensure_dir(dirname($settings->{log_file}));
611 3 $destination = { file => $settings->{log_file} };
612 }
613  
614 612 my $logger = Log::Abstraction->new(
615 level => $level,
616 format => $format,
617 # Logging must never turn a handled error into a second, uncaught one.
618 croak_on_error => 0,
619 logger => $destination,
620 );
621  
622 612 ▶ $logger = $logger->new(level => 'debug') if $args->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"verbose"} 2 610 612
623 612 ▶ $logger = $logger->new(level => 'error') if $args->{quiet};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"quiet"} 6 606 612
624  
625 612 return $logger;
626 }
627  
628 # _set
629 # Purpose: true for a value that is defined and not empty.
630 # Entry: any scalar.
631 # Exit: returns 1 or 0.
632 # Side effects: none.
633 3766 ▶sub _set :Private {
Subroutine _set: called CC=3 SCAR=11.0
634 3766 my ($value) = @_;
635  
636 3766 ▶ return (defined $value && length $value) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $value && length $value ? : 2495 1271 3766
Condition100%3/3
defined $value and length $value
!ll&&!rl&&r
6556162495
MC/DC100%2/2
defined $value and length $value
defined $value length $value
Truth table100%3/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
637 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
638  
639 # _default_config_path
640 # Purpose: where the settings file would be when none is given.
641 # Entry: none.
642 # Exit: returns FILESYNC_SETTINGS, else HOME (or USERPROFILE on
643 # Windows) /.conf/app-filesync.json, else undef.
644 # Side effects: none; existence is the caller's question.
645 628 ▶sub _default_config_path :Private {
Subroutine _default_config_path: called CC=3 SCAR=11.0
646 628 ▶ my $home = first { _set($_) } @ENV{qw(HOME USERPROFILE)};
Subroutine __ANON__: called CC=1 SCAR=0.0
647  
648 my $path = _set($ENV{FILESYNC_SETTINGS}) ? $ENV{FILESYNC_SETTINGS}
649 628 ▶ : defined $home ? File::Spec->catfile($home, $CONF_DIR, $CONFIG_BASENAME)
Branch: 2 branches
BranchTrueFalseTotal
_set($ENV{'FILESYNC_SETTINGS'}) ? : 610 18 628
defined $home ? : 18 0 18
650 : undef;
651 628 return $path;
652 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
653  
654 # _defaults
655 # Purpose: the built-in value of every setting.
656 # Entry: none.
657 # Exit: returns a fresh hashref (callers may change it).
658 # Side effects: none.
659 645 ▶sub _defaults :Private {
Subroutine _defaults: called CC=1 SCAR=0.0
660 return {
661 645 log_level => $DEFAULT_LEVEL,
662 log_format => $DEFAULT_FORMAT,
663 log_file => '',
664 ssh_identity => '',
665 ssh_known_hosts => '',
666 server_command => $DEFAULT_SERVER_COMMAND,
667 };
668 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
669  
670 # _repo_label
671 # Purpose: the provenance label for a value a repo's own entry supplied.
672 # Entry: $config_file may be undef.
673 # Exit: returns "FILE [name]" or "[name]".
674 # Side effects: none.
675 6 ▶sub _repo_label :Private {
Subroutine _repo_label: called CC=2 SCAR=7.2
676 6 my ($config_file, $name) = @_;
677  
678 6 ▶ return _set($config_file) ? "$config_file [$name]" : "[$name]";
Branch: 1 branch
BranchTrueFalseTotal
_set($config_file) ? : 6 0 6
679 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
680  
681 # _differs
682 # Purpose: compare two setting values as strings, undef only equal to undef.
683 # Entry: two scalars.
684 # Exit: returns 1 if they differ, else 0.
685 # Side effects: none.
686 48 ▶sub _differs :Private {
Subroutine _differs: called CC=5 SCAR=20.9
687 48 my ($left, $right) = @_;
688  
689 48 ▶ return (defined $left xor defined $right) ? 1
Branch: 3 branches
BranchTrueFalseTotal
defined $left ^^ defined $right ? : 0 48 48
!defined($left) ? : 0 48 48
"$left" ne "$right" ? : 0 48 48
Condition25%1/4
defined $left xor defined $right
l&&rl&&!r!l&&r!l&&!r
48000
MC/DC0%0/2
defined $left xor defined $right
defined $left defined $right
Truth table25%1/4
A xor B
A= defined $leftB= defined $right
ABresult
110
101
011
000
690 : !defined $left ? 0
691 : ("$left" ne "$right") ? 1 : 0;
692 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
693  
694 # _explanation
695 # Purpose: ask Config::Abstraction which sources set each key of a section.
696 # Entry: $file exists; $section is the env prefix's stem.
697 # Exit: returns a hashref (empty when the reader cannot be built).
698 # Side effects: reads $file.
699 8 ▶sub _explanation :Private {
Subroutine _explanation: called CC=3 SCAR=11.4
700 8 my ($file, $section) = @_;
701  
702 8 my $reader = Config::Abstraction->new(config_file => $file, env_prefix => "${section}__");
703 8 ▶ my $explanation = $reader ? $reader->explain_sources() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$reader ? : 8 0 8
704 8 ▶ return ref($explanation) eq 'HASH' ? $explanation : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $explanation eq 'HASH' ? : 8 0 8
705 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
706  
707 # _env_key
708 # Purpose: the name the environment actually uses for a variable.
709 # Entry: $name is "prefix__key".
710 # Exit: returns the matching %ENV key, or undef.
711 # Side effects: none.
712 # Config::Abstraction matches an env_prefix case-insensitively, and Windows
713 # reports environment names upper-cased, so the report must name the variable
714 # in the spelling that actually supplied the value.
715 27 ▶sub _env_key :Private {
Subroutine _env_key: called CC=2 SCAR=6.9
716 27 my ($name) = @_;
717  
718 # Not "exists $ENV{$name}": on Windows that lookup ignores case too, so it
719 # answered with the caller's spelling instead of the environment's.
720 27 my @names = sort keys %ENV;
721 27 ▶ return (first { $_ eq $name } @names) // first { lc $_ eq lc $name } @names;
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Condition100%3/3
&first(sub { $_ eq $name; } , @names) // &first(sub { lc $_ eq lc $name; } , @names)
l!l&&r!l&&!r
4221
MC/DC100%2/2
&first(sub { $_ eq $name; } , @names) // &first(sub { lc $_ eq lc $name; } , @names)
&first(sub { $_ eq $name; } , @names) &first(sub { lc $_ eq lc $name; } , @names)
Truth table100%3/3
A // B
A= &first(sub { $_ eq $name; } , @names)B= &first(sub { lc $_ eq lc $name; } , @names)
ABresult
1X1
011
000
722 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
723  
724 # _pick
725 # Purpose: the source that set a key in one section.
726 # Entry: $explanation is from _explanation.
727 # Exit: returns { type, label, value } or undef.
728 # Side effects: none.
729 # The last source wins, which is how Config::Abstraction layers a file under
730 # its environment variables.
731 48 ▶sub _pick :Private {
Subroutine _pick: called CC=5 SCAR=16.2
732 48 my ($explanation, $section, $key) = @_;
733  
734 48 for my $full ("$section.$key", "global.$key", $key) {
735 128 my $entry = $explanation->{$full};
736 128 ▶ next unless ref($entry) eq 'HASH' && ref($entry->{sources}) eq 'ARRAY' && @{ $entry->{sources} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and ref $entry->{"sources"} eq "ARRAY" and @{$entry->{"sources"};} 120 8 128
Condition66%4/6
ref $entry eq "HASH" and ref $entry->{"sources"} eq "ARRAY" and @{$entry->{"sources"};}
!ll&&!rl&&r
12008
ref $entry eq "HASH" and ref $entry->{"sources"} eq "ARRAY"
!ll&&!rl&&r
12008
MC/DC33%1/3
ref $entry eq "HASH" and ref $entry->{"sources"} eq "ARRAY" and @{$entry->{"sources"};}
ref $entry eq "HASH" ref $entry->{"sources"} eq "ARRAY" @{$entry->{"sources"};}
Truth table50%2/4
A and B and C
A= ref $entry eq "HASH"B= ref $entry->{"sources"} eq "ARRAY"C= @{$entry->{"sources"};}
ABCresult
0XX0
10X0
1100
1111
737  
738 8 my $winner = $entry->{sources}[-1];
739 8 return { map { $_ => $winner->{$_} } qw(type label value) };
740 }
741  
742 40 return undef; ## no critic (Subroutines::ProhibitExplicitReturnUndef) -- callers test it in scalar context
743 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
744  
745 # _labels_for
746 # Purpose: every source label that mentions a key, for a merged value.
747 # Entry: explanations from _explanation.
748 # Exit: returns an arrayref of distinct labels, in order found.
749 # Side effects: none.
750 0 ▶sub _labels_for :Private {
Subroutine _labels_for: not called CC=6 SCAR=37.4
751 0 my ($key, @explanations) = @_;
752  
753 0 my (%seen, @labels);
754 0 for my $explanation (@explanations) {
755 0 ▶ for my $full (grep { $_ eq $key || /\.\Q$key\E\z/ } sort keys %{$explanation}) {
Condition0%0/3
$_ eq $key || /\.\Q$key\E\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$_ eq $key || /\.\Q$key\E\z/
$_ eq $key /\.\Q$key\E\z/
Truth table0%0/3
A || B
A= $_ eq $keyB= /\.\Q$key\E\z/
ABresult
1X1
011
000
756 0 ▶ push @labels, grep { _set($_) && !$seen{$_}++ }
Condition0%0/3
_set($_) && !$seen{$_}++
!ll&&!rl&&r
000
MC/DC0%0/2
_set($_) && !$seen{$_}++
_set($_) !$seen{$_}++
Truth table0%0/3
A && not(B)
A= _set($_)B= !$seen{$_}++
ABresult
0X0
100
111
757 0 ▶ map { $_->{label} } @{ $explanation->{$full}{sources} || [] };
Condition0%0/2
$explanation->{$full}{'sources'} || []
l!l
00
MC/DC0%0/1
$explanation->{$full}{'sources'} || []
$explanation->{$full}{'sources'}
Truth table0%0/2
A
A= $explanation->{$full}{'sources'}
Aresult
11
00
758 }
759 }
760  
761 0 return \@labels;
762 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
763  
764 # _universal_file
765 # Purpose: the universal settings file Object::Configure would read.
766 # Entry: $config_file is the settings file.
767 # Exit: returns the first readable candidate, or undef.
768 # Side effects: none.
769 # Mirrors Object::Configure's search: universal<ext> beside the settings
770 # file, then the other config-file extensions, so the report matches.
771 6 ▶sub _universal_file :Private {
Subroutine _universal_file: called CC=2 SCAR=6.9
772 6 my ($config_file) = @_;
773  
774 6 my ($volume, $directory) = File::Spec->splitpath($config_file);
775 6 my $base = File::Spec->catpath($volume, $directory, '');
776 6 ▶ my $ext = $config_file =~ /(\.[^.\/\\]+)\z/ ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$config_file =~ m((\.[^./\\]+)\z) ? : 6 0 6
777  
778 6 my %seen;
779 18 ▶ return first { -f $_ && -r $_ }
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
-f $_ and -r $_ 2 16 18
780 24 map { File::Spec->catfile($base, "universal$_") }
781 6 grep { !$seen{$_}++ } ($ext, @UNIVERSAL_EXTENSIONS);
782 331 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
783  
784 331 1;
785  
786 __END__
« blib/lib/App/FileSync/Client.pm ↑ Summary blib/lib/App/FileSync/Admin.pm »