blib/lib/App/FileSync/Client.pm

filter: Statementstmt 98.3% 647 / 658 Branchbran 79.7% 193 / 242 Conditioncond 55.2% 121 / 219 MC/DCmcdc 24.8% 31 / 125 Subroutinesub 100% 113 / 113 Podpod 100% 11 / 11 totaltotal 81.5% 1116 / 1368 CC 207 SCAR 21.8
CC
207
Cov
86%
_session
27.6
log
21.1
_transport
18.3
CRAP 8.9
« blib/lib/App/FileSync/Scan.pm ↑ Summary blib/lib/App/FileSync/Settings.pm »
1 package App::FileSync::Client;
2  
3 # The client end of a sync, plus the client-side commands that work on one
4 # repo: log, verify, restore from the local trash, and replica snapshots.
5 # Everything the client keeps for a repo lives under ~/.filesync: its cache
6 # (the base of the last sync), its run log, its lock and its trash.
7  
8 326 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 326 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 326 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 326 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 326 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 326 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 326 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 326 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 326 ▶use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 326 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 326 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
21 326 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 326 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 326 ▶use parent 'App::FileSync::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 326 ▶use App::FileSync qw(json_encode json_decode validate_relpath validate_repo_name parse_since parse_until);
Subroutine BEGIN: called CC=1 SCAR=0.0
27 326 ▶use App::FileSync::Args qw(named);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 326 ▶use App::FileSync::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 326 ▶use App::FileSync::Constants qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
30 $PROTOCOL_VERSION $ROLE_CLIENT $ROLE_REPLICA $TYPE_FILE $TYPE_DIR $MODE_MASK
31 $EXIT_OK $EXIT_FATAL $EXIT_LOCKED $EXIT_WARNINGS
32 $ROOT_MARKER $SNAPSHOT_DIR $TEMP_PREFIX $TRASH_DAYS $SNAPSHOT_KEEP
33 $STAT_MODE $STAT_SIZE $STAT_MTIME $SHA_BITS
34 326 );
35 326 ▶use App::FileSync::Delta;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 326 ▶use App::FileSync::I18N qw(os_error strip_location);
Subroutine BEGIN: called CC=1 SCAR=0.0
37 326 ▶use App::FileSync::IO qw(append_line ensure_dir install_file open_file read_text temp_file write_atomic);
Subroutine BEGIN: called CC=1 SCAR=0.0
38 326 ▶use App::FileSync::Ignore;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 326 ▶use App::FileSync::Lock;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 326 ▶use App::FileSync::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 326 ▶use App::FileSync::Scan;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 326 ▶use App::FileSync::Settings;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 326 ▶use App::FileSync::Snapshot;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 326 ▶use App::FileSync::Transport::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 326 ▶use App::FileSync::Transport::SSH;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 326 ▶use App::FileSync::Trash;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 326 ▶use App::FileSync::Verify;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 326 ▶use version; our $VERSION = version->declare('0.002.1');
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 # Tunables, kept as package variables so tests can localise them.
52 326 our $CHUNK = 262_144;
53 326 our $MANIFEST_CHUNK = 2_000;
54  
55 # How many run summaries the local log keeps before trimming the oldest.
56 326 our $LOG_LIMIT = 500;
57  
58 # How many runs "filesync log" shows when no limit is given.
59 326 Readonly::Scalar my $LOG_DEFAULT_LIMIT => 20;
60  
61 # Wire cost of one delta record (see the server's identical estimate).
62 326 Readonly::Scalar my $DELTA_OP_BYTES => 12;
63 326 Readonly::Scalar my $DELTA_OVERHEAD => 64;
64  
65 # Per-repo trash lives under trash/repos/NAME; "repos" can never be mistaken
66 # for a year directory of the trash layout used before 0.001.1, which put
67 # every repo's trash straight under trash/.
68 326 Readonly::Scalar my $TRASH_REPOS => 'repos';
69  
70 # Names probed to discover whether the sync root's filesystem folds case.
71 326 Readonly::Scalar my $CASE_PROBE => "${TEMP_PREFIX}caseprobe";
72  
73 # Summary counters, in the order the run log records them.
74 326 Readonly my @SUMMARY_KEYS => qw(pulled pushed deleted conflicts skipped delta_pulled delta_pushed bytes_sent bytes_received);
75  
76 =encoding utf8
77  
78 =head1 NAME
79  
80 App::FileSync::Client - sync one repo, and the client-side repo commands
81  
82 =head1 VERSION
83  
84 0.002.1
85  
86 =head1 SYNOPSIS
87  
88 my $config = App::FileSync::Config::load_client();
89 my $client = App::FileSync::Client->new(config => $config, name => 'docs', opts => { verbose => 1 });
90  
91 my $result = $client->sync;
92 exit $result->{exit};
93  
94 =head1 DESCRIPTION
95  
96 A sync is one session with the server: hello, manifest, plan, then the
97 transfers the plan lists, then done. The client keeps under
98 F<~/.filesync> (or C<FILESYNC_HOME>):
99  
100 cache/NAME.json the base: what the last successful sync left
101 logs/NAME.jsonl one line per attempt, for "filesync log"
102 locks/NAME.lock held for the whole run
103 trash/repos/NAME/Y/M/D/ files the sync deleted or replaced locally
104  
105 Exit codes: 0 ok, 1 error, 2 another run holds the lock, 3 finished with
106 warnings (conflicts or skipped paths).
107  
108 =head1 METHODS
109  
110 =head2 new
111  
112 Purpose: a client for one repo of a client configuration.
113  
114 Args: C<config> (from L<App::FileSync::Config/load_client>), C<name> (the
115 repo's key in it), optional C<opts> (C<dry_run>, C<force>, C<no_prune>,
116 C<no_delta>, C<verbose>, C<quiet>), C<logger>, C<settings> (process settings,
117 read lazily otherwise), C<language>.
118  
119 Returns: the client.
120  
121 Side Effects: builds a logger from the settings when none is given.
122  
123 Usage:
124  
125 my $client = App::FileSync::Client->new(config => $config, name => 'docs');
126  
127 =head3 EXAMPLE
128  
129 my $client = App::FileSync::Client->new(
130 config => $config, name => 'docs', opts => { dry_run => 1 },
131 );
132  
133 =head3 API SPECIFICATION
134  
135 =head4 INPUT
136  
137 {
138 config => { type => 'hashref' },
139 name => { type => 'string', min => 1, max => 64 },
140 opts => { type => 'hashref', optional => 1 },
141 logger => { type => 'object', optional => 1 },
142 settings => { type => 'hashref', optional => 1 },
143 language => { type => 'string', optional => 1 },
144 }
145  
146 =head4 OUTPUT
147  
148 { type => 'object', isa => 'App::FileSync::Client' }
149  
150 =head3 MESSAGES
151  
152 Key Meaning Resolution
153 client.no_config no configuration was given pass config
154 client.bad_name the repo name is not a plain id rename the repo in config.json
155  
156 =head3 FORMAL SPECIFICATION
157  
158 pre config ≠ ⊥ ∧ name ∈ Id
159 post self.name = name ∧ self.opts = opts ∨ ∅
160  
161 =cut
162  
163 280 ▶sub new {
Subroutine new: called CC=6 SCAR=18.1
Pod documented
164 280 my $class = shift;
165 280 my $args = named(\@_, {
166 config => { type => 'hashref', optional => 1 },
167 name => { type => 'string', optional => 1 },
168 opts => { type => 'hashref', optional => 1 },
169 logger => { type => 'object', optional => 1 },
170 settings => { type => 'hashref', optional => 1 },
171 language => { type => 'string', optional => 1 },
172 }, 'Client->new');
173  
174 280 ▶ App::FileSync::I18N::throw('client.no_config') unless $args->{config};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"config"} 0 280 280
175  
176 # The name becomes part of the cache, log, lock and trash paths, so it
177 # must be a plain id, not something like "../x".
178 280 my ($ok, $reason) = validate_repo_name($args->{name});
179 280 ▶ App::FileSync::I18N::throw('client.bad_name', { reason => $reason }) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 3 277 280
180  
181 277 ▶ my $opts = $args->{opts} || {};
Condition100%2/2
$args->{'opts'} || {}
l!l
21166
MC/DC100%1/1
$args->{'opts'} || {}
$args->{'opts'}
Truth table100%2/2
A
A= $args->{'opts'}
Aresult
11
00
182 my $self = bless {
183 config => $args->{config},
184 name => $args->{name},
185 opts => $opts,
186 language => $args->{language},
187 277 ▶ logger => $args->{logger} || App::FileSync::Settings::logger(verbose => $opts->{verbose}, quiet => $opts->{quiet}),
Condition66%2/3
$args->{'logger'} || App::FileSync::Settings::logger('verbose', $opts->{'verbose'}, 'quiet', $opts->{'quiet'})
l!l&&r!l&&!r
122650
MC/DC0%0/2
$args->{'logger'} || App::FileSync::Settings::logger('verbose', $opts->{'verbose'}, 'quiet', $opts->{'quiet'})
$args->{'logger'} App::FileSync::Settings::logger('verbose', $opts->{'verbose'}, 'quiet', $opts->{'quiet'})
Truth table66%2/3
A || B
A= $args->{'logger'}B= App::FileSync::Settings::logger('verbose', $opts->{'verbose'}, 'quiet', $opts->{'quiet'})
ABresult
1X1
011
000
188 }, $class;
189  
190 # Read lazily unless the caller (a test, or a command that already loaded
191 # them) supplies the process settings.
192 277 ▶ $self->{settings} = $args->{settings} if exists $args->{settings};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"settings"} 0 277 277
193 277 return $self;
194 }
195  
196 =head2 sync
197  
198 Purpose: run one sync session for the repo.
199  
200 Args: none (see C<opts> in L</new>).
201  
202 Returns: C<{ repo, ok, exit, summary, warnings, stats }>; with C<dry_run>,
203 also C<dry_run =E<gt> 1> and the planned C<actions>. A lock refusal (here or
204 on the server) returns C<ok =E<gt> 0, exit =E<gt> 2, locked =E<gt> 1> rather than
205 raising: cron starting a run while the last one is finishing is normal.
206  
207 Side Effects: changes the local tree and the master; updates the cache;
208 prunes this repo's local trash (unless C<no_prune>); appends to the run log,
209 whatever the outcome.
210  
211 Usage:
212  
213 my $result = App::FileSync::Client->new(%args)->sync;
214  
215 =head3 EXAMPLE
216  
217 my $result = $client->sync;
218 printf "pulled %d, pushed %d\n", @{ $result->{summary} }{qw(pulled pushed)};
219 print "warning: $_\n" for @{ $result->{warnings} };
220  
221 =head3 API SPECIFICATION
222  
223 =head4 INPUT
224  
225 [ { name => 'self', type => 'object' } ]
226  
227 =head4 OUTPUT
228  
229 {
230 type => 'hashref',
231 schema => {
232 repo => { type => 'string' },
233 ok => { type => 'integer', memberof => [ 0, 1 ] },
234 exit => { type => 'integer', memberof => [ 0, 2, 3 ] },
235 summary => { type => 'hashref', optional => 1 },
236 warnings => { type => 'arrayref', optional => 1 },
237 },
238 }
239  
240 =head3 MESSAGES
241  
242 Key Meaning Resolution
243 client.no_repo the repo is not in the configuration filesync init
244 client.bad_root the sync root is not a directory fix root in config.json
245 client.no_marker the root has no .filesync-root marker mount the drive, or create the marker
246 client.no_client_id the configuration has no client_id filesync init
247 client.refused the server refused the session read the reason
248 client.req.* the server rejected a step read the reason
249 client.hash_mismatch a transfer arrived corrupted rerun the sync
250  
251 =head3 FORMAL SPECIFICATION
252  
253 ΔFS
254 sync = ⟨exit ↦ 2⟩ if lock held elsewhere
255 sync = ⟨exit ↦ 0 | 3⟩ ∧ local' ≡ master' if the session completes
256 sync raises ∧ base' = base otherwise
257  
258 =head3 PSEUDOCODE
259  
260 look up the repo
261 run the session (lock, transport, protocol)
262 record the attempt in the run log, success or failure
263 log a summary; return the result, or re-raise the error
264  
265 =cut
266  
267 175 ▶sub sync {
Subroutine sync: called CC=6 SCAR=17.9
Pod documented
268 175 my ($self) = @_;
269  
270 175 my $repo = $self->_repo_config();
271 175 my $result = eval { $self->_run_session($repo) };
272  
273 175 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 12 163 175
274 # A run that started and then failed is still something cron attempted,
275 # so the audit trail records it before the error escapes.
276 12 my $error = $@;
277 12 $self->_record_run({ exit => $EXIT_FATAL, error => strip_location($error) });
278 12 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
279 }
280  
281 163 $self->_record_run($result);
282  
283 163 ▶ if ($result->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"ok"}) 155 8 163
284 $self->{logger}->info('sync finished', {
285 repo => $self->{name},
286 1085 ▶ (map { $_ => ($result->{summary}{$_} || 0) } qw(pulled pushed deleted conflicts skipped bytes_sent bytes_received)),
Branch: 1 branch
BranchTrueFalseTotal
$result->{'dry_run'} ? : 8 147 155
Condition80%4/5
$result->{'summary'}{$_} || 0
l!l
248837
$result->{'exit'} || $App::FileSync::Client::EXIT_OK
l!l&&r!l&&!r
220133
MC/DC100%1/1
$result->{'summary'}{$_} || 0
$result->{'summary'}{$_}
MC/DC50%1/2
$result->{'exit'} || $App::FileSync::Client::EXIT_OK
$result->{'exit'} $App::FileSync::Client::EXIT_OK
Truth table100%2/2
A
A= $result->{'summary'}{$_}
Aresult
11
00
Truth table66%2/3
A || B
A= $result->{'exit'}B= $App::FileSync::Client::EXIT_OK
ABresult
1X1
011
000
287 exit => $result->{exit} || $EXIT_OK,
288 155 dry_run => $result->{dry_run} ? 1 : 0,
289 });
290 }
291  
292 163 return $result;
293 }
294  
295 =head2 log
296  
297 Purpose: recent run attempts from the local run log.
298  
299 Args: optional C<limit> (default 20), C<since> and C<until> (C<YYYY-MM-DD>
300 or epoch, inclusive), C<exits> (an exit code or arrayref of them),
301 C<warnings> (only runs that recorded a warning, conflict or skipped path).
302 All filters apply before the limit.
303  
304 Returns: C<{ repo, path, runs }> (runs oldest first), plus the filters used.
305  
306 Side Effects: reads the log. A torn final line from a killed run is skipped.
307  
308 Usage:
309  
310 my $log = $client->log(limit => 5, exits => [ 1, 2 ]);
311  
312 =head3 EXAMPLE
313  
314 for my $run (@{ $client->log(since => '2026-10-01')->{runs} }) {
315 print "$run->{ts} exit $run->{exit}\n";
316 }
317  
318 =head3 API SPECIFICATION
319  
320 =head4 INPUT
321  
322 {
323 limit => { type => 'integer', optional => 1 },
324 since => { type => 'string', optional => 1 },
325 until => { type => 'string', optional => 1 },
326 exits => { type => 'arrayref', optional => 1 }, # a lone code is wrapped
327 warnings => { type => 'boolean', optional => 1 },
328 }
329  
330 =head4 OUTPUT
331  
332 { type => 'hashref', schema => { repo => { type => 'string' }, path => { type => 'string' }, runs => { type => 'arrayref' } } }
333  
334 =head3 MESSAGES
335  
336 Key Meaning Resolution
337 when.bad since/until is malformed use YYYY-MM-DD or an epoch
338 io.read the log cannot be read check permissions
339  
340 =head3 FORMAL SPECIFICATION
341  
342 log = last limit ⟨ r ∈ runs | since ≤ r.ts ≤ until ∧ (exits = ∅ ∨ r.exit ∈ exits) ∧ (¬warnings ∨ has_warnings(r)) ⟩
343  
344 =head3 PSEUDOCODE
345  
346 parse the filters
347 read each JSON line of the log, skipping torn ones
348 keep the runs that pass every filter
349 keep the newest limit; report the filters used
350  
351 =cut
352  
353 69 ▶sub log { ## no critic (Subroutines::ProhibitBuiltinHomonyms) -- public API name
Subroutine log: called CC=21 SCAR=30.5
Pod documented
354 69 my ($self, %raw) = @_;
355  
356 # One exit code is accepted as shorthand for a list of one.
357 69 ▶ $raw{exits} = [ $raw{exits} ] if defined $raw{exits} && !ref $raw{exits};
Branch: 1 branch
BranchTrueFalseTotal
if defined $raw{"exits"} and not ref $raw{"exits"} 0 69 69
Condition66%2/3
defined $raw{"exits"} and not ref $raw{"exits"}
!ll&&!rl&&r
21480
MC/DC0%0/2
defined $raw{"exits"} and not ref $raw{"exits"}
defined $raw{"exits"} not ref $raw{"exits"}
Truth table66%2/3
A and not(B)
A= defined $raw{"exits"}B= not ref $raw{"exits"}
ABresult
0X0
100
111
358 69 my $args = named([ %raw ], {
359 limit => { type => 'integer', optional => 1 },
360 since => { type => 'string', optional => 1 },
361 until => { type => 'string', optional => 1 },
362 exits => { type => 'arrayref', optional => 1 },
363 warnings => { type => 'scalar', optional => 1 },
364 }, 'Client::log');
365  
366 69 ▶ my $limit = ($args->{limit} && $args->{limit} > 0) ? $args->{limit} : $LOG_DEFAULT_LIMIT;
Branch: 1 branch
BranchTrueFalseTotal
$args->{'limit'} && $args->{'limit'} > 0 ? : 7 62 69
Condition66%2/3
$args->{"limit"} and $args->{"limit"} > 0
!ll&&!rl&&r
6207
MC/DC50%1/2
$args->{"limit"} and $args->{"limit"} > 0
$args->{"limit"} $args->{"limit"} > 0
Truth table66%2/3
A and B
A= $args->{"limit"}B= $args->{"limit"} > 0
ABresult
0X0
100
111
367 69 ▶ my $since = defined $args->{since} ? parse_since($args->{since}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'since'} ? : 12 57 69
368 69 ▶ my $until = defined $args->{until} ? parse_until($args->{until}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'until'} ? : 10 59 69
369 69 ▶ my $warnings = $args->{warnings} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args->{'warnings'} ? : 9 60 69
370  
371 69 ▶ my @exits = map { $_ + 0 } @{ $args->{exits} || [] };
Condition100%2/2
$args->{'exits'} || []
l!l
4821
MC/DC100%1/1
$args->{'exits'} || []
$args->{'exits'}
Truth table100%2/2
A
A= $args->{'exits'}
Aresult
11
00
372  
373 69 my $path = $self->log_path();
374 my @runs = grep {
375 203 ▶ my $ts = $_->{ts} || 0;
Condition50%1/2
$_->{'ts'} || 0
l!l
2030
MC/DC0%0/1
$_->{'ts'} || 0
$_->{'ts'}
Truth table50%1/2
A
A= $_->{'ts'}
Aresult
11
00
376 203 ▶ (!defined $since || $ts >= $since)
Condition100%15/15
(!defined($since) || $ts >= $since) && (!defined($until) || $ts <= $until) && (!$warnings || _has_warnings($_))
!ll&&!rl&&r
3221150
!defined($since) || $ts >= $since and !defined($until) || $ts <= $until
!ll&&!rl&&r
1715171
not defined $since or $ts >= $since
l!l&&r!l&&!r
1622417
not defined $until or $ts <= $until
l!l&&r!l&&!r
1482315
not $warnings or _has_warnings($_)
l!l&&r!l&&!r
1331721
MC/DC100%6/6
(!defined($since) || $ts >= $since) && (!defined($until) || $ts <= $until) && (!$warnings || _has_warnings($_))
not defined $since $ts >= $since not defined $until $ts <= $until not $warnings _has_warnings($_)
Truth table73%11/15
not(A) or B and not(C) or D && not(E) or F
A= not defined $sinceB= $ts >= $sinceC= not defined $untilD= $ts <= $untilE= not $warningsF= _has_warnings($_)
ABCDEFresult
00XXXX0
1X00XX0
0100XX0
1X1X000
1X01000
011X000
0101000
1X1X1X1
1X1X011
1X011X1
1X01011
011X1X1
011X011
01011X1
0101011
377 && (!defined $until || $ts <= $until)
378 && (!$warnings || _has_warnings($_));
379 69 } @{ _read_jsonl($path) };
380  
381 # any's block sees its own $_, so the exit test reads the run explicitly.
382 69 ▶ @runs = grep { my $run = $_; !@exits || any { ($run->{exit} || 0) == $_ } @exits } @runs;
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%5/5
!@exits || &any(sub { ($run->{'exit'} || 0) == $_; } , @exits)
l!l&&r!l&&!r
1111128
$run->{'exit'} || 0
l!l
3012
MC/DC100%2/2
!@exits || &any(sub { ($run->{'exit'} || 0) == $_; } , @exits)
!@exits &any(sub { ($run->{'exit'} || 0) == $_; } , @exits)
MC/DC100%1/1
$run->{'exit'} || 0
$run->{'exit'}
Truth table100%3/3
not(A) || B
A= !@exitsB= &any(sub { ($run->{'exit'} || 0) == $_; } , @exits)
ABresult
1X1
011
000
Truth table100%2/2
A
A= $run->{'exit'}
Aresult
11
00
383 69 ▶ splice(@runs, 0, @runs - $limit) if @runs > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if @runs > $limit 5 64 69
384  
385 return {
386 repo => $self->{name},
387 69 ▶ path => $path,
Branch: 4 branches
BranchTrueFalseTotal
defined $since ? : 12 57 69
defined $until ? : 10 59 69
@exits ? : 10 59 69
$warnings ? : 9 60 69
388 runs => \@runs,
389 (defined $since ? (since => $since) : ()),
390 (defined $until ? (until => $until) : ()),
391 (@exits ? (exits => \@exits) : ()),
392 ($warnings ? (warnings => 1) : ()),
393 };
394 }
395  
396 =head2 verify
397  
398 Purpose: compare the local tree with the base the last successful sync
399 recorded. Drift means the tree changed without being synced.
400  
401 Args: optional C<deep> (hash every file rather than trusting size and mtime).
402  
403 Returns: the L<App::FileSync::Verify> report, plus C<repo>.
404  
405 Side Effects: reads the tree; logs a summary. Works offline: the ignore list
406 is the one cached by the last sync.
407  
408 Usage:
409  
410 my $report = $client->verify(deep => 1);
411  
412 =head3 EXAMPLE
413  
414 my $report = $client->verify;
415 print $report->{ok} ? "clean\n" : scalar(@{ $report->{modified} }) . " modified\n";
416  
417 =head3 API SPECIFICATION
418  
419 =head4 INPUT
420  
421 { deep => { type => 'boolean', optional => 1 } }
422  
423 =head4 OUTPUT
424  
425 { type => 'hashref' }
426  
427 =head3 MESSAGES
428  
429 Key Meaning Resolution
430 client.bad_root the sync root is not a directory fix root in config.json
431 client.no_marker the root has no .filesync-root marker mount the drive
432  
433 =head3 FORMAL SPECIFICATION
434  
435 verify = Verify(root, cache.entries, Ignore(cache.ignore ∪ {snapshots}))
436  
437 =cut
438  
439 10 ▶sub verify {
Subroutine verify: called CC=3 SCAR=11.0
Pod documented
440 10 my $self = shift;
441 10 my $args = named(\@_, { deep => { type => 'scalar', optional => 1 } }, 'Client::verify');
442  
443 10 my $root = $self->_checked_root($self->_repo_config());
444 10 my $cache = $self->cache();
445 10 ▶ my $patterns = ref($cache->{ignore}) eq 'ARRAY' ? $cache->{ignore} : \@App::FileSync::Config::DEFAULT_IGNORE;
Branch: 1 branch
BranchTrueFalseTotal
ref $cache->{'ignore'} eq 'ARRAY' ? : 8 2 10
446  
447 my $report = App::FileSync::Verify::verify(
448 root => $root,
449 entries => $cache->{entries},
450 ignore => App::FileSync::Ignore->new(patterns => _with_reserved($patterns)),
451 deep => $args->{deep},
452 10 );
453 10 $report->{repo} = $self->{name};
454  
455 $self->{logger}->info('verify finished', {
456 repo => $self->{name},
457 files => $report->{files},
458 30 ▶ (map { $_ => scalar @{ $report->{$_} } } qw(modified missing extra)),
Branch: 1 branch
BranchTrueFalseTotal
$report->{'ok'} ? : 3 7 10
459 10 ok => $report->{ok} ? 1 : 0,
460 });
461  
462 10 return $report;
463 }
464  
465 =head2 restore
466  
467 Purpose: put a path back from this repo's local trash. The newest stored
468 version wins; C<list> shows them all instead.
469  
470 Args: C<path>, optional C<to> (a directory; default the sync root), C<list>.
471  
472 Versions are searched in this repo's trash first, then in the shared trash
473 that releases before 0.001.1 used, so files trashed before an upgrade can
474 still be restored.
475  
476 Returns: with C<list>, C<{ repo, path, versions }>; otherwise
477 C<{ repo, path, from, to }>.
478  
479 Side Effects: copies the version out; the trash entry is kept.
480  
481 Usage:
482  
483 $client->restore(path => 'notes/a.txt', to => '/tmp/out');
484  
485 =head3 EXAMPLE
486  
487 my $versions = $client->restore(path => 'a.txt', list => 1)->{versions};
488 print "$_->{date} $_->{size}\n" for @{$versions};
489  
490 =head3 API SPECIFICATION
491  
492 =head4 INPUT
493  
494 {
495 path => { type => 'string', min => 1 },
496 to => { type => 'string', optional => 1 },
497 list => { type => 'boolean', optional => 1 },
498 }
499  
500 =head4 OUTPUT
501  
502 { type => 'hashref' }
503  
504 =head3 MESSAGES
505  
506 Key Meaning Resolution
507 client.unsafe the path fails validate_relpath fix the path
508 client.no_versions nothing of that path is in the trash check --list
509 client.not_dir the target is not a directory choose another
510 client.exists the destination exists move it aside or use --to
511  
512 =head3 FORMAL SPECIFICATION
513  
514 ΔFS
515 pre path ∈ SafePath ∧ versions(path) ≠ ⟨⟩ ∧ dest ∉ dom FS
516 post tree'(dest) = tree(head versions(path))
517  
518 =head3 PSEUDOCODE
519  
520 validate the path; list versions from the repo trash then the legacy trash
521 if listing, return them
522 destination := to (created) or the sync root, plus the path
523 refuse to overwrite; copy the newest version out
524  
525 =cut
526  
527 12 ▶sub restore {
Subroutine restore: called CC=10 SCAR=23.3
Pod documented
528 12 my $self = shift;
529 12 my $args = named(\@_, {
530 path => { type => 'string', optional => 1 },
531 to => { type => 'string', optional => 1 },
532 list => { type => 'scalar', optional => 1 },
533 }, 'Client::restore');
534  
535 12 my $repo = $self->_repo_config();
536 12 my $path = $args->{path};
537 12 my ($safe, $reason) = validate_relpath($path);
538 12 ▶ $self->_throw('client.unsafe', { path => $path // '', reason => $reason }) unless $safe;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe 0 12 12
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
539  
540 12 my @versions = map { @{ App::FileSync::Trash::versions(root => $_, rel => $path) } }
541 $self->_trash_root(), $self->_legacy_trash_root();
542  
543 12 ▶ if ($args->{list}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"list"}) 3 9 12
544 3 return { repo => $self->{name}, path => $path, versions => [ map { App::FileSync::Trash::version_info($_) } @versions ] };
545 }
546  
547 9 ▶ $self->_throw('client.no_versions', { path => $path, repo => $self->{name}, trash => $self->_trash_root() })
Branch: 1 branch
BranchTrueFalseTotal
unless @versions 2 7 9
548 unless @versions;
549  
550 7 ▶ my $to_root = (defined $args->{to} && length $args->{to}) ? $args->{to} : $repo->{root};
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'to'} && length $args->{'to'} ? : 1 6 7
Condition66%2/3
defined $args->{"to"} and length $args->{"to"}
!ll&&!rl&&r
601
MC/DC50%1/2
defined $args->{"to"} and length $args->{"to"}
defined $args->{"to"} length $args->{"to"}
Truth table66%2/3
A and B
A= defined $args->{"to"}B= length $args->{"to"}
ABresult
0X0
100
111
551 7 ensure_dir($to_root);
552 7 ▶ $self->_throw('client.not_dir', { path => $to_root }) unless -d $to_root;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $to_root 0 7 7
553  
554 7 my $destination = File::Spec->catfile($to_root, split m{/}, $path);
555 7 ▶ $self->_throw('client.exists', { path => $destination }) if -e $destination || -l $destination;
Branch: 1 branch
BranchTrueFalseTotal
if -e $destination or -l $destination 2 5 7
Condition66%2/3
-e $destination or -l $destination
l!l&&r!l&&!r
205
MC/DC50%1/2
-e $destination or -l $destination
-e $destination -l $destination
Truth table66%2/3
A or B
A= -e $destinationB= -l $destination
ABresult
1X1
011
000
556  
557 5 App::FileSync::Trash::restore(src => $versions[0], to => $destination);
558  
559 5 my %done = (path => $path, from => $versions[0], to => $destination);
560 5 $self->{logger}->info('restored path', { repo => $self->{name}, %done });
561 5 return { repo => $self->{name}, %done };
562 }
563  
564 =head2 snapshot_create
565  
566 Purpose: take today's snapshot of a replica.
567  
568 Args: optional C<keep> (how many snapshots to keep; default the repo's
569 C<snapshot_keep>, else 14; 0 keeps all).
570  
571 Returns: C<{ repo, ok, exit, keep, pruned, older, ... }> with the
572 L<App::FileSync::Snapshot/create> result merged in; C<exit =E<gt> 2> when
573 another run holds the lock.
574  
575 Side Effects: holds the repo lock; creates a snapshot; prunes old ones when a
576 new one was made.
577  
578 Usage:
579  
580 my $made = $client->snapshot_create(keep => 7);
581  
582 =head3 EXAMPLE
583  
584 my $made = $client->snapshot_create;
585 print $made->{created} ? "snapshot $made->{date}\n" : "already have $made->{date}\n";
586  
587 =head3 API SPECIFICATION
588  
589 =head4 INPUT
590  
591 { keep => { type => 'integer', min => 0, optional => 1 } }
592  
593 =head4 OUTPUT
594  
595 { type => 'hashref' }
596  
597 =head3 MESSAGES
598  
599 Key Meaning Resolution
600 client.not_replica the repo is a client snapshots are for replicas
601 snapshot.* see App::FileSync::Snapshot
602  
603 =head3 FORMAL SPECIFICATION
604  
605 pre role = replica
606 created ∧ keep > 0 ⇒ #snapshots' ≤ keep
607  
608 =head3 PSEUDOCODE
609  
610 refuse unless the repo is a replica
611 take the lock, or report that another run holds it
612 choose the mode and the number to keep
613 create today's snapshot; prune if one was made
614  
615 =cut
616  
617 4 ▶sub snapshot_create {
Subroutine snapshot_create: called CC=10 SCAR=24.7
Pod documented
618 4 my $self = shift;
619 4 my $args = named(\@_, { keep => { type => 'integer', min => 0, optional => 1 } }, 'Client::snapshot_create');
620  
621 4 my $repo = $self->_repo_config();
622 $self->_throw('client.not_replica', { repo => $self->{name} })
623 4 ▶ unless ($repo->{role} || $ROLE_CLIENT) eq $ROLE_REPLICA;
Branch: 1 branch
BranchTrueFalseTotal
unless ($repo->{"role"} || $App::FileSync::Client::ROLE_CLIENT) eq $App::FileSync::Client::ROLE_REPLICA 1 3 4
Condition33%1/3
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
l!l&&r!l&&!r
400
MC/DC0%0/2
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
$repo->{'role'} $App::FileSync::Client::ROLE_CLIENT
Truth table33%1/3
A || B
A= $repo->{'role'}B= $App::FileSync::Client::ROLE_CLIENT
ABresult
1X1
011
000
624  
625 3 ▶ my $lock = $self->_lock() or return $self->_locked_result();
Branch: 1 branch
BranchTrueFalseTotal
my $lock = $self->_lock or return $self->_locked_result 3 0 3
626  
627 my $mode = (defined $repo->{snapshot_mode} && length $repo->{snapshot_mode})
628 ? $repo->{snapshot_mode}
629 3 ▶ : App::FileSync::Snapshot::default_mode();
Branch: 1 branch
BranchTrueFalseTotal
defined $repo->{'snapshot_mode'} && length $repo->{'snapshot_mode'} ? : 0 3 3
Condition33%1/3
defined $repo->{"snapshot_mode"} and length $repo->{"snapshot_mode"}
!ll&&!rl&&r
300
MC/DC0%0/2
defined $repo->{"snapshot_mode"} and length $repo->{"snapshot_mode"}
defined $repo->{"snapshot_mode"} length $repo->{"snapshot_mode"}
Truth table33%1/3
A and B
A= defined $repo->{"snapshot_mode"}B= length $repo->{"snapshot_mode"}
ABresult
0X0
100
111
630 3 ▶ my $keep = $args->{keep} // $repo->{snapshot_keep} // $SNAPSHOT_KEEP;
Condition66%4/6
($args->{"keep"} // $repo->{"snapshot_keep"}) // $App::FileSync::Client::SNAPSHOT_KEEP
l!l&&r!l&&!r
210
$args->{"keep"} // $repo->{"snapshot_keep"}
l!l&&r!l&&!r
201
MC/DC0%0/3
($args->{"keep"} // $repo->{"snapshot_keep"}) // $App::FileSync::Client::SNAPSHOT_KEEP
$args->{"keep"} $repo->{"snapshot_keep"} $App::FileSync::Client::SNAPSHOT_KEEP
Truth table50%2/4
A // B // C
A= $args->{"keep"}B= $repo->{"snapshot_keep"}C= $App::FileSync::Client::SNAPSHOT_KEEP
ABCresult
1XX1
01X1
0011
0000
631  
632 3 my $created = App::FileSync::Snapshot::create(root => $repo->{root}, mode => $mode);
633 my $pruned = ($created->{created} && $keep > 0)
634 3 ▶ ? App::FileSync::Snapshot::prune(root => $repo->{root}, keep => $keep)
Branch: 1 branch
BranchTrueFalseTotal
$created->{'created'} && $keep > 0 ? : 2 1 3
Condition66%2/3
$created->{"created"} and $keep > 0
!ll&&!rl&&r
102
MC/DC50%1/2
$created->{"created"} and $keep > 0
$created->{"created"} $keep > 0
Truth table66%2/3
A and B
A= $created->{"created"}B= $keep > 0
ABresult
0X0
100
111
635 : { removed => [], kept => [] };
636  
637 return {
638 repo => $self->{name},
639 ok => 1,
640 exit => $EXIT_OK,
641 3 %{$created},
642 keep => $keep,
643 pruned => $pruned->{removed},
644 older => $pruned->{kept},
645 3 };
646 }
647  
648 =head2 snapshot_list
649  
650 Purpose: a replica's snapshots, newest first.
651  
652 Args: none.
653  
654 Returns: C<{ repo, snapshots }>.
655  
656 Side Effects: walks every snapshot to count it.
657  
658 Usage:
659  
660 my $list = $client->snapshot_list;
661  
662 =head3 EXAMPLE
663  
664 print "$_->{date}\n" for @{ $client->snapshot_list->{snapshots} };
665  
666 =head3 API SPECIFICATION
667  
668 =head4 INPUT
669  
670 [ { name => 'self', type => 'object' } ]
671  
672 =head4 OUTPUT
673  
674 { type => 'hashref', schema => { repo => { type => 'string' }, snapshots => { type => 'arrayref' } } }
675  
676 =head3 MESSAGES
677  
678 Key Meaning Resolution
679 client.no_repo the repo is not in the config filesync init
680  
681 =head3 FORMAL SPECIFICATION
682  
683 snapshot_list = ⟨repo ↦ name, snapshots ↦ Snapshot::list(root)⟩
684  
685 =cut
686  
687 2 ▶sub snapshot_list {
Subroutine snapshot_list: called CC=1 SCAR=0.0
Pod documented
688 2 my ($self) = @_;
689  
690 2 return { repo => $self->{name}, snapshots => App::FileSync::Snapshot::list(root => $self->_repo_config()->{root}) };
691 }
692  
693 =head2 snapshot_restore
694  
695 Purpose: copy a snapshot (or one path of it) back.
696  
697 Args: C<date>, optional C<path> (one relative path; default everything) and
698 C<to> (default the sync root, which rolls the replica back).
699  
700 Returns: the L<App::FileSync::Snapshot/restore> result plus C<repo>, C<ok>,
701 C<exit> and C<into_root>; C<exit =E<gt> 2> when another run holds the lock.
702  
703 Side Effects: holds the repo lock; replaces files under C<to>.
704  
705 Usage:
706  
707 $client->snapshot_restore(date => '2026-10-20', path => 'notes');
708  
709 =head3 EXAMPLE
710  
711 my $done = $client->snapshot_restore(date => '2026-10-20', to => '/tmp/export');
712 print "$done->{files} files\n";
713  
714 =head3 API SPECIFICATION
715  
716 =head4 INPUT
717  
718 {
719 date => { type => 'string', optional => 1 },
720 path => { type => 'string', optional => 1 },
721 to => { type => 'string', optional => 1 },
722 }
723  
724 =head4 OUTPUT
725  
726 { type => 'hashref' }
727  
728 =head3 MESSAGES
729  
730 See L<App::FileSync::Snapshot/restore>.
731  
732 =head3 FORMAL SPECIFICATION
733  
734 ΔFS
735 into_root ⇔ to = root
736 tree'(to / p) = tree(snapshot(date) / p) for each restored p
737  
738 =cut
739  
740 2 ▶sub snapshot_restore {
Subroutine snapshot_restore: called CC=7 SCAR=20.2
Pod documented
741 2 my $self = shift;
742 2 my $args = named(\@_, {
743 date => { type => 'string', optional => 1 },
744 path => { type => 'string', optional => 1 },
745 to => { type => 'string', optional => 1 },
746 }, 'Client::snapshot_restore');
747  
748 2 my $repo = $self->_repo_config();
749 2 ▶ my $lock = $self->_lock() or return $self->_locked_result();
Branch: 1 branch
BranchTrueFalseTotal
my $lock = $self->_lock or return $self->_locked_result 2 0 2
750  
751 2 ▶ my $to = (defined $args->{to} && length $args->{to}) ? $args->{to} : $repo->{root};
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'to'} && length $args->{'to'} ? : 1 1 2
Condition66%2/3
defined $args->{"to"} and length $args->{"to"}
!ll&&!rl&&r
101
MC/DC50%1/2
defined $args->{"to"} and length $args->{"to"}
defined $args->{"to"} length $args->{"to"}
Truth table66%2/3
A and B
A= defined $args->{"to"}B= length $args->{"to"}
ABresult
0X0
100
111
752 my $result = App::FileSync::Snapshot::restore(
753 root => $repo->{root},
754 date => $args->{date},
755 2 ▶ paths => (defined $args->{path} && length $args->{path}) ? [ $args->{path} ] : [],
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'path'} && length $args->{'path'} ? : 2 0 2
Condition33%1/3
defined $args->{"path"} and length $args->{"path"}
!ll&&!rl&&r
002
MC/DC0%0/2
defined $args->{"path"} and length $args->{"path"}
defined $args->{"path"} length $args->{"path"}
Truth table33%1/3
A and B
A= defined $args->{"path"}B= length $args->{"path"}
ABresult
0X0
100
111
756 to => $to,
757 );
758  
759 2 ▶ return { repo => $self->{name}, ok => 1, exit => $EXIT_OK, into_root => ($to eq $repo->{root} ? 1 : 0), %{$result} };
Branch: 1 branch
BranchTrueFalseTotal
$to eq $repo->{'root'} ? : 1 1 2
760 }
761  
762 =head2 cache_path
763  
764 Documented with L</log_path> below.
765  
766 =head2 log_path
767  
768 Purpose: where this repo's cache and run log live.
769  
770 Args: none.
771  
772 Returns: F<HOME/cache/NAME.json>, F<HOME/logs/NAME.jsonl>.
773  
774 Side Effects: none.
775  
776 Usage:
777  
778 my $path = $client->cache_path;
779  
780 =head3 EXAMPLE
781  
782 print $client->log_path, "\n";
783  
784 =head3 API SPECIFICATION
785  
786 =head4 INPUT
787  
788 [ { name => 'self', type => 'object' } ]
789  
790 =head4 OUTPUT
791  
792 { type => 'string', min => 1 }
793  
794 =head3 MESSAGES
795  
796 Key Meaning Resolution
797 config.no_home no home directory is known set HOME or FILESYNC_HOME
798  
799 =head3 FORMAL SPECIFICATION
800  
801 cache_path = home / "cache" / name ⁀ ".json"
802 log_path = home / "logs" / name ⁀ ".jsonl"
803  
804 =cut
805  
806 321 ▶sub cache_path {
Subroutine cache_path: called CC=1 SCAR=0.0
Pod documented
807 321 my ($self) = @_;
808  
809 321 return $self->_home_file('cache', "$self->{name}.json");
810 }
811  
812 244 ▶sub log_path {
Subroutine log_path: called CC=1 SCAR=0.0
Pod documented
813 244 my ($self) = @_;
814  
815 244 return $self->_home_file('logs', "$self->{name}.jsonl");
816 }
817  
818 =head2 cache
819  
820 Purpose: the cached base and last-run summary.
821  
822 Args: none.
823  
824 Returns: the cache hashref, always with an C<entries> hashref; an empty cache
825 when there is none or it is unreadable (the next sync rebuilds it).
826  
827 Side Effects: reads the cache file.
828  
829 Usage:
830  
831 my $last = $client->cache->{last_run};
832  
833 =head3 EXAMPLE
834  
835 my $cache = $client->cache;
836 printf "%d files at the last sync\n", scalar keys %{ $cache->{entries} };
837  
838 =head3 API SPECIFICATION
839  
840 =head4 INPUT
841  
842 [ { name => 'self', type => 'object' } ]
843  
844 =head4 OUTPUT
845  
846 { type => 'hashref', schema => { entries => { type => 'hashref' } } }
847  
848 =head3 MESSAGES
849  
850 None; a damaged cache is treated as empty.
851  
852 =head3 FORMAL SPECIFICATION
853  
854 cache = json(FS(cache_path)) if that parses to an object, else ⟨entries ↦ ∅⟩
855  
856 =cut
857  
858 174 ▶sub cache {
Subroutine cache: called CC=4 SCAR=13.9
Pod documented
859 174 my ($self) = @_;
860  
861 174 my $path = $self->cache_path();
862 174 ▶ my $cache = -e $path ? eval { json_decode(read_text($path)) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $path ? : 106 68 174
863 174 ▶ $cache = {} unless ref($cache) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cache eq "HASH" 68 106 174
864 174 ▶ $cache->{entries} = {} unless ref($cache->{entries}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cache->{"entries"} eq "HASH" 68 106 174
865  
866 174 return $cache;
867 }
868  
869 # _run_session
870 # Purpose: one attempt: check the root, lock, connect, run the session.
871 # Entry: $repo is this repo's client config.
872 # Exit: returns a result hashref; a lock refusal is a result, not an
873 # exception.
874 # Side effects: holds the lock for the session; starts and closes the
875 # transport. When the transport failed, its own error text
876 # ("Permission denied (publickey)", a host key mismatch) is
877 # raised instead of the protocol error it caused.
878 175 ▶sub _run_session :Private {
Subroutine _run_session: called CC=6 SCAR=18.0
879 175 my ($self, $repo) = @_;
880  
881 175 my $root = $self->_checked_root($repo);
882 172 ▶ my $lock = $self->_lock() or return $self->_locked_result();
Branch: 1 branch
BranchTrueFalseTotal
my $lock = $self->_lock or return $self->_locked_result 167 5 172
883  
884 167 my $transport = $self->_transport($repo);
885 167 my $connection = App::FileSync::Protocol->new(in => $transport->reader(), out => $transport->writer());
886  
887 167 my $result = eval { $self->_session($connection, $repo, $root) };
888 167 my $error = $@;
889 167 $transport->close();
890 167 ▶ return $result if $result;
Branch: 1 branch
BranchTrueFalseTotal
if $result 158 9 167
891  
892 9 ▶ if ($connection->transport_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($connection->transport_failed) 2 7 9
893 2 my $text = eval { $transport->error_text() };
894 2 ▶ $error = "$text\n" if defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
if defined $text and length $text 2 0 2
Condition33%1/3
defined $text and length $text
!ll&&!rl&&r
002
MC/DC0%0/2
defined $text and length $text
defined $text length $text
Truth table33%1/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
895 }
896 9 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
897 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
898  
899 # _session
900 # Purpose: the protocol conversation, from hello to done.
901 # Entry: $connection is open; $root has been checked.
902 # Exit: returns the result hashref.
903 # Side effects: scans the tree; applies the plan; saves the cache and prunes
904 # the trash after a real (not dry) run.
905 167 ▶sub _session :Private {
Subroutine _session: called CC=25 SCAR=33.2
906 167 my ($self, $connection, $repo, $root) = @_;
907  
908 167 my $opts = $self->{opts};
909 167 my $client_id = $self->{config}{client_id};
910 167 ▶ $self->_throw('client.no_client_id') unless defined $client_id && length $client_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $client_id and length $client_id 0 167 167
Condition33%1/3
defined $client_id and length $client_id
!ll&&!rl&&r
00167
MC/DC0%0/2
defined $client_id and length $client_id
defined $client_id length $client_id
Truth table33%1/3
A and B
A= defined $client_idB= length $client_id
ABresult
0X0
100
111
911  
912 $connection->send({
913 cmd => 'hello',
914 proto => $PROTOCOL_VERSION,
915 client => $client_id,
916 host => Sys::Hostname::hostname(),
917 os => $^O,
918 role => $repo->{role} || $ROLE_CLIENT,
919 repo => $repo->{remote_repo} || $self->{name},
920 case_insensitive => _case_insensitive($root),
921 now => time,
922 dry_run => $opts->{dry_run} ? 1 : 0,
923 167 ▶ force => $opts->{force} ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
$opts->{'dry_run'} ? : 8 159 167
$opts->{'force'} ? : 8 159 167
Condition33%2/6
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
l!l&&r!l&&!r
16700
$repo->{'remote_repo'} || $self->{'name'}
l!l&&r!l&&!r
16700
MC/DC0%0/2
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
$repo->{'role'} $App::FileSync::Client::ROLE_CLIENT
MC/DC0%0/2
$repo->{'remote_repo'} || $self->{'name'}
$repo->{'remote_repo'} $self->{'name'}
Truth table33%1/3
A || B
A= $repo->{'role'}B= $App::FileSync::Client::ROLE_CLIENT
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= $repo->{'remote_repo'}B= $self->{'name'}
ABresult
1X1
011
000
924 });
925  
926 167 my $hello = $connection->recv();
927 165 ▶ unless ($hello->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hello->{"ok"}) 4 161 165
928 4 ▶ my $reason = $hello->{error} || $self->i18n('client.unknown_reason');
Condition33%1/3
$hello->{'error'} || $self->i18n('client.unknown_reason')
l!l&&r!l&&!r
400
MC/DC0%0/2
$hello->{'error'} || $self->i18n('client.unknown_reason')
$hello->{'error'} $self->i18n('client.unknown_reason')
Truth table33%1/3
A || B
A= $hello->{'error'}B= $self->i18n('client.unknown_reason')
ABresult
1X1
011
000
929 # Lock contention on the server is as normal as it is here.
930 3 return { %{ $self->_locked_result($reason) }, summary => { map { $_ => 0 } qw(pulled pushed deleted conflicts) } }
931 4 ▶ if ($hello->{code} // '') eq 'locked';
Branch: 1 branch
BranchTrueFalseTotal
if ($hello->{"code"} // "") eq "locked" 3 1 4
Condition100%2/2
$hello->{"code"} // ""
l!l
31
MC/DC100%1/1
$hello->{"code"} // ""
$hello->{"code"}
Truth table100%2/2
A
A= $hello->{"code"}
Aresult
11
00
932 1 $self->_throw('client.refused', { reason => $reason });
933 }
934  
935 161 ▶ my $policy = $hello->{policy} || {};
Condition50%1/2
$hello->{'policy'} || {}
l!l
1610
MC/DC0%0/1
$hello->{'policy'} || {}
$hello->{'policy'}
Truth table50%1/2
A
A= $hello->{'policy'}
Aresult
11
00
936 161 ▶ my $patterns = _with_reserved($policy->{ignore} || []);
Condition50%1/2
$policy->{'ignore'} || []
l!l
1610
MC/DC0%0/1
$policy->{'ignore'} || []
$policy->{'ignore'}
Truth table50%1/2
A
A= $policy->{'ignore'}
Aresult
11
00
937 161 ▶ my $ignore = App::FileSync::Ignore->new(patterns => $patterns, case_insensitive => $hello->{case_insensitive} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$hello->{'case_insensitive'} ? : 0 161 161
938  
939 161 App::FileSync::Scan::clean_stale_temps(root => $root);
940 my ($manifest, $stats, $skipped) = @{ App::FileSync::Scan::scan(
941 root => $root,
942 ignore => $ignore,
943 cache => $self->cache()->{entries},
944 161 ) }{qw(manifest stats skipped)};
945  
946 161 $self->_send_manifest($connection, $manifest);
947  
948 161 my $plan = $self->_request($connection, { cmd => 'plan' }, 'client.req.plan', {});
949 155 ▶ my @actions = @{ $plan->{actions} || [] };
Condition50%1/2
$plan->{'actions'} || []
l!l
1550
MC/DC0%0/1
$plan->{'actions'} || []
$plan->{'actions'}
Truth table50%1/2
A
A= $plan->{'actions'}
Aresult
11
00
950 155 ▶ my @warnings = (@{ $plan->{warnings} || [] },
Condition50%1/2
$plan->{'warnings'} || []
l!l
1550
MC/DC0%0/1
$plan->{'warnings'} || []
$plan->{'warnings'}
Truth table50%1/2
A
A= $plan->{'warnings'}
Aresult
11
00
951 155 map { $self->i18n('client.skipped', { path => $_, reason => $skipped->{$_} }) } sort keys %{$skipped});
952  
953 my %planned = (
954 341 pulled => scalar(grep { $_->{a} eq 'pull' } @actions),
955 341 pushed => scalar(grep { $_->{a} eq 'push' } @actions),
956 341 deleted => scalar(grep { $_->{a} =~ /\Adelete_/ } @actions),
957 155 conflicts => scalar(grep { $_->{a} eq 'conflict' } @actions),
958 );
959 $self->{logger}->debug('plan received', {
960 repo => $self->{name}, actions => scalar @actions, deletions => $planned{deleted},
961 155 ▶ conflicts => $planned{conflicts}, dry_run => $opts->{dry_run} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'dry_run'} ? : 8 147 155
962 });
963  
964 155 my $summary = { (map { $_ => 0 } qw(pulled pushed deleted conflicts delta_pulled delta_pushed)), skipped => scalar(keys %{$skipped}) };
965 155 my %result = (repo => $self->{name}, ok => 1, summary => $summary, warnings => \@warnings, stats => $stats);
966  
967 155 ▶ if ($opts->{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"dry_run"}) 8 147 155
968 8 $self->_request($connection, { cmd => 'done' }, 'client.req.end', {});
969 # Nothing but headers and control messages has crossed the connection.
970 8 %{$summary} = (%{$summary}, %planned, bytes_sent => $connection->bytes_sent, bytes_received => $connection->bytes_received);
971 8 ▶ return { %result, exit => @warnings ? $EXIT_WARNINGS : $EXIT_OK, dry_run => 1, actions => \@actions };
Branch: 1 branch
BranchTrueFalseTotal
@warnings ? : 1 7 8
972 }
973  
974 147 ▶ if ($opts->{verbose}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"verbose"}) 1 146 147
975 1 for my $action (@actions) {
976 0 (my $verb = $action->{a}) =~ tr/_/ /;
977 0 print $self->i18n('client.verbose_action', { verb => $verb, path => $action->{p} }), "\n";
978 }
979 }
980  
981 147 my %after = %{$manifest};
982 147 $self->_apply($connection, $_, \%after, $summary) for @actions;
983  
984 147 $self->_request($connection, { cmd => 'done' }, 'client.req.end', {});
985 147 ▶ @{$summary}{qw(delta_pulled delta_pushed)} = map { $self->{$_} || 0 } qw(delta_pulled delta_pushed);
Condition100%2/2
$self->{$_} || 0
l!l
2292
MC/DC100%1/1
$self->{$_} || 0
$self->{$_}
Truth table100%2/2
A
A= $self->{$_}
Aresult
11
00
986 147 @{$summary}{qw(bytes_sent bytes_received)} = ($connection->bytes_sent, $connection->bytes_received);
987  
988 147 $self->_save_cache(\%after, $summary, $patterns);
989 147 ▶ $self->_prune_local_trash($repo) unless $opts->{no_prune};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"no_prune"} 147 0 147
990  
991 147 ▶ return { %result, exit => @warnings ? $EXIT_WARNINGS : $EXIT_OK };
Branch: 1 branch
BranchTrueFalseTotal
@warnings ? : 21 126 147
992 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
993  
994 # _apply
995 # Purpose: carry out one planned action.
996 # Entry: $after is the manifest being turned into the new base.
997 # Exit: returns 1.
998 # Side effects: transfers, deletes or resolves; counts it in $summary.
999 326 ▶sub _apply :Private {
Subroutine _apply: called CC=6 SCAR=17.9
1000 326 my ($self, $connection, $action, $after, $summary) = @_;
1001  
1002 326 my ($type, $path) = @{$action}{qw(a p)};
1003 326 ▶ if ($type eq 'pull') {
Branch: 5 branches
BranchTrueFalseTotal
if ($type eq 'pull') { } 89 237 326
elsif ($type eq 'push') { } 177 60 237
elsif ($type eq 'delete_remote') { } 17 43 60
elsif ($type eq 'delete_local') { } 33 10 43
elsif ($type eq 'conflict') { } 10 0 10
1004 89 $self->_pull($connection, $action, $after);
1005 89 $summary->{pulled}++;
1006 } elsif ($type eq 'push') {
1007 177 $self->_push($connection, $action);
1008 177 $summary->{pushed}++;
1009 } elsif ($type eq 'delete_remote') {
1010 17 $self->_request($connection, { cmd => 'del', p => $path }, 'client.req.delete', { path => $path });
1011 17 delete $after->{$path};
1012 17 $summary->{deleted}++;
1013 } elsif ($type eq 'delete_local') {
1014 33 $self->_delete_local($path);
1015 33 $self->_request($connection, { cmd => 'ack', p => $path, deleted => 1 }, 'client.req.ack_delete', { path => $path });
1016 33 delete $after->{$path};
1017 33 $summary->{deleted}++;
1018 } elsif ($type eq 'conflict') {
1019 10 $self->_resolve_conflict($connection, $action, $after);
1020 10 $summary->{conflicts}++;
1021 } else {
1022 0 $self->_throw('client.unknown_action', { action => $type, path => $path });
1023 }
1024  
1025 326 return 1;
1026 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1027  
1028 # _send_manifest
1029 # Purpose: send the scanned manifest in parts.
1030 # Entry: $manifest maps paths to entries.
1031 # Exit: returns 1.
1032 # Side effects: one request per $MANIFEST_CHUNK entries (at least one, so an
1033 # empty tree still sends an empty manifest).
1034 161 ▶sub _send_manifest :Private {
Subroutine _send_manifest: called CC=3 SCAR=11.0
1035 161 my ($self, $connection, $manifest) = @_;
1036  
1037 161 my @entries = map { { p => $_, %{ $manifest->{$_} } } } sort keys %{$manifest};
1038 161 ▶ my $parts = @entries ? int((@entries - 1) / $MANIFEST_CHUNK) + 1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
@entries ? : 149 12 161
1039  
1040 161 for my $part (0 .. $parts - 1) {
1041 161 my @slice = splice(@entries, 0, $MANIFEST_CHUNK);
1042 161 $self->_request($connection, { cmd => 'manifest', part => $part, of => $parts, entries => \@slice },
1043 'client.req.manifest', {});
1044 }
1045  
1046 161 return 1;
1047 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1048  
1049 # _pull
1050 # Purpose: fetch a master file (or directory) the plan says to pull.
1051 # Entry: $action has p, t and maybe h (the expected hash).
1052 # Exit: returns 1.
1053 # Side effects: replaces the local path; acknowledges it; records it in
1054 # $after. Tries a delta first when there is a local version.
1055 95 ▶sub _pull :Private {
Subroutine _pull: called CC=4 SCAR=13.9
1056 95 my ($self, $connection, $action, $after) = @_;
1057  
1058 95 my $path = $action->{p};
1059 95 my $abs = $self->_abs($path);
1060  
1061 95 ▶ if (($action->{t} || $TYPE_FILE) eq $TYPE_DIR) {
Branch: 1 branch
BranchTrueFalseTotal
if (($action->{"t"} || $App::FileSync::Client::TYPE_FILE) eq $App::FileSync::Client::TYPE_DIR) 6 89 95
Condition33%1/3
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
9500
MC/DC0%0/2
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
$action->{'t'} $App::FileSync::Client::TYPE_FILE
Truth table33%1/3
A || B
A= $action->{'t'}B= $App::FileSync::Client::TYPE_FILE
ABresult
1X1
011
000
1062 6 ensure_dir($abs);
1063 6 $self->_request($connection, { cmd => 'ack', p => $path, t => $TYPE_DIR }, 'client.req.ack_dir', { path => $path });
1064 6 $after->{$path} = { t => $TYPE_DIR };
1065 6 return 1;
1066 }
1067  
1068 89 ▶ return 1 if $self->_pull_delta($connection, $action, $after, $abs);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_pull_delta($connection, $action, $after, $abs) 1 88 89
1069  
1070 88 ▶ my $receipt = $self->_receive($abs, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1071 88 my ($write) = @_;
1072 88 my ($offset, %server) = (0);
1073 88 while (1) {
1074 89 my $header = $self->_request($connection, { cmd => 'get', p => $path, off => $offset, max => $CHUNK },
1075 'client.req.get', { path => $path });
1076 89 my $bytes = $connection->read_data($header);
1077 89 $write->($bytes);
1078 89 $offset += length $bytes;
1079 89 $server{$_} = $header->{$_} for grep { defined $header->{$_} } qw(s m mode h);
1080 89 ▶ last if $header->{eof};
Branch: 1 branch
BranchTrueFalseTotal
if $header->{"eof"} 88 1 89
1081 }
1082 88 return \%server;
1083 88 });
1084  
1085 88 return $self->_finish_pull($connection, $action, $after, $abs, $receipt);
1086 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1087  
1088 # _pull_delta
1089 # Purpose: receive only the blocks that differ from the local copy.
1090 # Entry: $abs is the local path.
1091 # Exit: returns 1 if the file was pulled as a delta, 0 (without
1092 # touching the connection beyond the signature) when a
1093 # whole-file pull is the right answer.
1094 # Side effects: as _pull.
1095 89 ▶sub _pull_delta :Private {
Subroutine _pull_delta: called CC=8 SCAR=20.9
1096 89 my ($self, $connection, $action, $after, $abs) = @_;
1097  
1098 89 ▶ return 0 if $self->{opts}{no_delta} || !-f $abs || -l $abs;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"opts"}{"no_delta"} or not -f $abs or -l $abs 81 8 89
Condition66%4/6
$self->{"opts"}{"no_delta"} or not -f $abs or -l $abs
l!l&&r!l&&!r
8108
$self->{"opts"}{"no_delta"} or not -f $abs
l!l&&r!l&&!r
0818
MC/DC33%1/3
$self->{"opts"}{"no_delta"} or not -f $abs or -l $abs
$self->{"opts"}{"no_delta"} not -f $abs -l $abs
Truth table50%2/4
A or not(B) or C
A= $self->{"opts"}{"no_delta"}B= not -f $absC= -l $abs
ABCresult
1XX1
01X1
0011
0000
1099 8 my $local_size = -s $abs;
1100 8 ▶ return 0 if $local_size < $App::FileSync::Delta::MIN_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if $local_size < $App::FileSync::Delta::MIN_SIZE 7 1 8
1101  
1102 1 my $path = $action->{p};
1103 1 my $block = App::FileSync::Delta::block_size($local_size);
1104 1 ▶ my $signature = App::FileSync::Delta::signature($abs, $block) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $signature = App::FileSync::Delta::signature($abs, $block) or return 0 1 0 1
1105  
1106 my $reply = $self->_request($connection, {
1107 cmd => 'dsig',
1108 p => $path,
1109 s => $local_size,
1110 b => $block,
1111 1 ▶ n => scalar @{ $signature->{blocks} },
Branch: 1 branch
BranchTrueFalseTotal
defined $action->{'h'} ? : 1 0 1
1112 1 (defined $action->{h} ? (h => $action->{h}) : ()),
1113 }, 'client.req.signature', { path => $path }, App::FileSync::Delta::encode_signature($signature));
1114 1 ▶ return 0 unless $reply->{delta};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"delta"} 0 1 1
1115  
1116 1 my $old = open_file($abs, '<:raw');
1117 1 ▶ my $receipt = $self->_receive($abs, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1118 1 my ($write) = @_;
1119 1 while (1) {
1120 26 my $op = $self->_request($connection, { cmd => 'dop', p => $path }, 'client.req.get', { path => $path });
1121 26 ▶ last if $op->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"done"} 1 25 26
1122 25 $write->($self->_delta_bytes($connection, $op, $old, $abs, $path, $local_size));
1123 }
1124 1 return { map { $_ => $reply->{$_} } grep { defined $reply->{$_} } qw(s m mode h) };
1125 1 }, $old);
1126  
1127 1 $self->_finish_pull($connection, $action, $after, $abs, $receipt);
1128 1 $self->{delta_pulled}++;
1129 1 return 1;
1130 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1131  
1132 # _delta_bytes
1133 # Purpose: the bytes one pull-delta record stands for.
1134 # Entry: $op is a reply with op copy (off, len) or lit (data follows).
1135 # Exit: returns the bytes.
1136 # Side effects: reads the local old version or the connection; raises
1137 # client.bad_copy or client.bad_op for anything malformed.
1138 25 ▶sub _delta_bytes :Private {
Subroutine _delta_bytes: called CC=10 SCAR=27.3
1139 25 my ($self, $connection, $op, $old, $abs, $path, $local_size) = @_;
1140  
1141 25 ▶ my $kind = $op->{op} // '';
Condition50%1/2
$op->{"op"} // ""
l!l
250
MC/DC0%0/1
$op->{"op"} // ""
$op->{"op"}
Truth table50%1/2
A
A= $op->{"op"}
Aresult
11
00
1142 25 ▶ return $connection->read_data($op) if $kind eq 'lit';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "lit" 2 23 25
1143 23 ▶ $self->_throw('client.bad_op', { path => $path }) unless $kind eq 'copy';
Branch: 1 branch
BranchTrueFalseTotal
unless $kind eq "copy" 0 23 23
1144  
1145 23 my ($offset, $length) = @{$op}{qw(off len)};
1146 23 ▶ $self->_throw('client.bad_copy', { path => $path })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $offset and $offset =~ /\A\d+\z/ and defined $length and $length =~ /\A\d+\z/ and $offset + $length <= $local_size 0 23 23
Condition33%4/12
defined $offset and $offset =~ /\A\d+\z/ and defined $length and $length =~ /\A\d+\z/ and $offset + $length <= $local_size
!ll&&!rl&&r
0023
defined $offset and $offset =~ /\A\d+\z/ and defined $length and $length =~ /\A\d+\z/
!ll&&!rl&&r
0023
defined $offset and $offset =~ /\A\d+\z/ and defined $length
!ll&&!rl&&r
0023
defined $offset and $offset =~ /\A\d+\z/
!ll&&!rl&&r
0023
MC/DC0%0/5
defined $offset and $offset =~ /\A\d+\z/ and defined $length and $length =~ /\A\d+\z/ and $offset + $length <= $local_size
defined $offset $offset =~ /\A\d+\z/ defined $length $length =~ /\A\d+\z/ $offset + $length <= $local_size
Truth table16%1/6
A and B and C and D and E
A= defined $offsetB= $offset =~ /\A\d+\z/C= defined $lengthD= $length =~ /\A\d+\z/E= $offset + $length <= $local_size
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1147 unless defined $offset && $offset =~ /\A\d+\z/ && defined $length && $length =~ /\A\d+\z/
1148 && $offset + $length <= $local_size;
1149  
1150 23 ▶ return '' unless $length;
Branch: 1 branch
BranchTrueFalseTotal
unless $length 0 23 23
1151 23 seek($old, $offset, 0);
1152 23 return App::FileSync::Delta::read_exact($old, $length, $abs);
1153 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1154  
1155 # _receive
1156 # Purpose: the shared body of every pull: a temporary file beside the
1157 # target, a running hash, and cleanup on failure.
1158 # Entry: $fill->($write) reads from the server, calling $write->($bytes)
1159 # for each piece, and returns what the server said about the
1160 # file ({ s, m, mode, h }); @close are extra handles to close.
1161 # Exit: returns { temp, hash, written, server }.
1162 # Side effects: creates the temporary file; on any error removes it, closes
1163 # @close and re-raises.
1164 89 ▶sub _receive :Private {
Subroutine _receive: called CC=3 SCAR=11.4
1165 89 my ($self, $abs, $fill, @close) = @_;
1166  
1167 89 my ($out, $temp) = @{ temp_file(dirname($abs)) };
1168 89 my $sha = Digest::SHA->new($SHA_BITS);
1169 89 my $written = 0;
1170  
1171 89 my $server = eval {
1172 114 ▶ my $info = $fill->(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1173 114 my ($bytes) = @_;
1174 114 ▶ print {$out} $bytes or $self->_throw('io.write', { path => $temp, error => os_error() });
Branch: 1 branch
BranchTrueFalseTotal
print {$out;} $bytes or $self->_throw("io.write", {"path", $temp, "error", os_error()}) 114 0 114
1175 114 $sha->add($bytes);
1176 114 $written += length $bytes;
1177 89 });
1178 89 close $out;
1179 89 $info;
1180 };
1181 89 my $error = $@;
1182 89 eval { close $_ } for grep { defined } @close;
1183  
1184 89 ▶ unless ($server) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server) 0 89 89
1185 0 eval { close $out };
1186 0 eval { unlink $temp };
1187 0 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
1188 }
1189  
1190 89 return { temp => $temp, hash => $sha->hexdigest(), written => $written, server => $server };
1191 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1192  
1193 # _finish_pull
1194 # Purpose: verify a received file, install it, and acknowledge it.
1195 # Entry: $receipt is from _receive.
1196 # Exit: returns 1.
1197 # Side effects: replaces the local path (whatever was there: a file, a
1198 # symlink or an empty directory); records the new entry in
1199 # $after. A mismatch removes the temporary file and raises.
1200 89 ▶sub _finish_pull :Private {
Subroutine _finish_pull: called CC=7 SCAR=23.8
1201 89 my ($self, $connection, $action, $after, $abs, $receipt) = @_;
1202  
1203 89 my ($path, $server, $got) = ($action->{p}, $receipt->{server}, $receipt->{hash});
1204 89 ▶ my $expected = $action->{h} // $server->{h};
Condition33%1/3
$action->{"h"} // $server->{"h"}
l!l&&r!l&&!r
8900
MC/DC0%0/2
$action->{"h"} // $server->{"h"}
$action->{"h"} $server->{"h"}
Truth table33%1/3
A // B
A= $action->{"h"}B= $server->{"h"}
ABresult
1X1
011
000
1205  
1206 my ($key, %args) =
1207 (defined $expected && $got ne $expected) ? ('client.hash_mismatch', expected => $expected, got => $got)
1208 : (defined $server->{s} && $receipt->{written} != $server->{s}) ? ('client.size_mismatch', expected => $server->{s}, got => $receipt->{written})
1209 89 ▶ : ();
Branch: 2 branches
BranchTrueFalseTotal
defined $expected && $got ne $expected ? : 0 89 89
defined $server->{'s'} && $receipt->{'written'} != $server->{'s'} ? : 0 89 89
Condition33%2/6
defined $expected and $got ne $expected
!ll&&!rl&&r
0890
defined $server->{"s"} and $receipt->{"written"} != $server->{"s"}
!ll&&!rl&&r
0890
MC/DC0%0/2
defined $expected and $got ne $expected
defined $expected $got ne $expected
MC/DC0%0/2
defined $server->{"s"} and $receipt->{"written"} != $server->{"s"}
defined $server->{"s"} $receipt->{"written"} != $server->{"s"}
Truth table33%1/3
A and B
A= defined $expectedB= $got ne $expected
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= defined $server->{"s"}B= $receipt->{"written"} != $server->{"s"}
ABresult
0X0
100
111
1210 89 ▶ if ($key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key) 0 89 89
1211 0 eval { unlink $receipt->{temp} };
1212 0 $self->_throw($key, { path => $path, %args });
1213 }
1214  
1215 89 install_file($receipt->{temp}, $abs, $server->{m}, $server->{mode});
1216  
1217 89 my %entry = (h => $got, s => $receipt->{written}, m => $server->{m}, mode => $server->{mode});
1218 89 $self->_request($connection, { cmd => 'ack', p => $path, %entry }, 'client.req.ack', { path => $path });
1219 89 $after->{$path} = { t => $TYPE_FILE, %entry };
1220 89 return 1;
1221 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1222  
1223 # _push
1224 # Purpose: send a local file (or directory) the plan says to push.
1225 # Entry: $action has p, t, h and, for a conflict this side won,
1226 # loser_name.
1227 # Exit: returns 1.
1228 # Side effects: transfers the file, as a delta when that is cheaper (never
1229 # for a conflict, where the server must first move its version
1230 # aside).
1231 181 ▶sub _push :Private {
Subroutine _push: called CC=8 SCAR=20.9
1232 181 my ($self, $connection, $action) = @_;
1233  
1234 181 my $path = $action->{p};
1235 181 my $abs = $self->_abs($path);
1236  
1237 181 ▶ if (($action->{t} || $TYPE_FILE) eq $TYPE_DIR) {
Branch: 1 branch
BranchTrueFalseTotal
if (($action->{"t"} || $App::FileSync::Client::TYPE_FILE) eq $App::FileSync::Client::TYPE_DIR) 5 176 181
Condition33%1/3
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
18100
MC/DC0%0/2
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
$action->{'t'} $App::FileSync::Client::TYPE_FILE
Truth table33%1/3
A || B
A= $action->{'t'}B= $App::FileSync::Client::TYPE_FILE
ABresult
1X1
011
000
1238 5 $self->_request($connection, { cmd => 'mkdir', p => $path }, 'client.req.mkdir', { path => $path });
1239 5 return 1;
1240 }
1241  
1242 176 my @stat = Time::HiRes::stat($abs);
1243 176 ▶ $self->_throw('client.cannot_stat', { path => $abs, error => os_error() }) unless @stat;
Branch: 1 branch
BranchTrueFalseTotal
unless @stat 0 176 176
1244 176 my %file = (s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK);
1245  
1246 176 ▶ return 1 if !$action->{loser_name} && $self->_push_delta($connection, $path, $abs, \%file, $action->{h});
Branch: 1 branch
BranchTrueFalseTotal
if not $action->{"loser_name"} and $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"}) 1 175 176
Condition100%3/3
not $action->{"loser_name"} and $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"})
!ll&&!rl&&r
41711
MC/DC100%2/2
not $action->{"loser_name"} and $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"})
not $action->{"loser_name"} $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"})
Truth table100%3/3
not(A) and B
A= not $action->{"loser_name"}B= $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"})
ABresult
0X0
100
111
1247  
1248 175 my $in = open_file($abs, '<:raw');
1249  
1250 # The server acknowledges the header before any chunk is sent; reading it
1251 # here keeps the lock-step protocol aligned.
1252 $self->_request($connection, {
1253 cmd => 'put', p => $path, t => $TYPE_FILE, %file, h => $action->{h},
1254 175 ▶ ($action->{loser_name} ? (conflict_name => $action->{loser_name}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$action->{'loser_name'} ? : 4 171 175
1255 }, 'client.req.put', { path => $path });
1256  
1257 175 ▶ while (read($in, my $buffer, $CHUNK)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&App::FileSync::Client::read($in, \my $buffer, $App::FileSync::Client::CHUNK)) 180 175 355
1258 180 $self->_request($connection, { cmd => 'chunk', p => $path }, 'client.req.chunk', { path => $path }, $buffer);
1259 }
1260 175 close $in;
1261  
1262 175 $self->_request($connection, { cmd => 'chunk_end', p => $path }, 'client.req.store', { path => $path });
1263 175 return 1;
1264 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1265  
1266 # _push_delta
1267 # Purpose: send only the blocks that changed since the master's version.
1268 # Entry: %{$file} has s, m, mode; $hash is the planned hash.
1269 # Exit: returns 1 if pushed as a delta, 0 when a whole-file put is
1270 # cheaper or there is nothing to reuse.
1271 # Side effects: spools the delta to a temporary file beside $abs.
1272 172 ▶sub _push_delta :Private {
Subroutine _push_delta: called CC=8 SCAR=20.8
1273 172 my ($self, $connection, $path, $abs, $file, $hash) = @_;
1274  
1275 172 ▶ return 0 if $self->{opts}{no_delta} || !defined $hash || $file->{s} < $App::FileSync::Delta::MIN_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"opts"}{"no_delta"} or not defined $hash or $file->{"s"} < $App::FileSync::Delta::MIN_SIZE 168 4 172
Condition83%5/6
$self->{"opts"}{"no_delta"} or not defined $hash or $file->{"s"} < $App::FileSync::Delta::MIN_SIZE
l!l&&r!l&&!r
11674
$self->{"opts"}{"no_delta"} or not defined $hash
l!l&&r!l&&!r
10171
MC/DC66%2/3
$self->{"opts"}{"no_delta"} or not defined $hash or $file->{"s"} < $App::FileSync::Delta::MIN_SIZE
$self->{"opts"}{"no_delta"} not defined $hash $file->{"s"} < $App::FileSync::Delta::MIN_SIZE
Truth table75%3/4
A or not(B) or C
A= $self->{"opts"}{"no_delta"}B= not defined $hashC= $file->{"s"} < $App::FileSync::Delta::MIN_SIZE
ABCresult
1XX1
01X1
0011
0000
1276  
1277 4 my $reply = $self->_request($connection, { cmd => 'sig', p => $path }, 'client.req.signature', { path => $path });
1278 4 ▶ return 0 unless $reply->{delta};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"delta"} 3 1 4
1279  
1280 1 my $blocks = App::FileSync::Delta::decode_signature($connection->read_data($reply), $reply->{n});
1281  
1282 1 my $spool = File::Temp->new(TEMPLATE => "${TEMP_PREFIX}delta-XXXXXXXX", DIR => dirname($abs), UNLINK => 1);
1283 1 binmode $spool;
1284 1 my $stats = App::FileSync::Delta::diff($abs, { size => $reply->{s}, blocklen => $reply->{b}, blocks => $blocks }, $spool);
1285  
1286 1 my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;
1287 1 ▶ return 0 if $estimated >= $file->{s};
Branch: 1 branch
BranchTrueFalseTotal
if $estimated >= $file->{"s"} 0 1 1
1288  
1289 1 $self->_request($connection, { cmd => 'delta', p => $path, %{$file}, h => $hash }, 'client.req.delta', { path => $path });
1290  
1291 1 seek($spool, 0, 0);
1292 1 ▶ while (my ($type, @rest) = App::FileSync::Delta::read_op($spool)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = App::FileSync::Delta::read_op($spool)) 25 1 26
1293 25 ▶ my ($message, $bytes) = $type eq 'copy'
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'copy' ? : 23 2 25
1294 ? ({ cmd => 'dcopy', p => $path, off => $rest[0], len => $rest[1] })
1295 : ({ cmd => 'dlit', p => $path }, $rest[0]);
1296 25 $self->_request($connection, $message, 'client.req.delta_data', { path => $path }, $bytes);
1297 }
1298  
1299 1 $self->_request($connection, { cmd => 'delta_end', p => $path }, 'client.req.store', { path => $path });
1300 1 $self->{delta_pushed}++;
1301 1 return 1;
1302 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1303  
1304 # _resolve_conflict
1305 # Purpose: carry out a conflict resolution.
1306 # Entry: $action has p, winner (client or remote), winner_type, h,
1307 # loser_name (when the losing side is a file).
1308 # Exit: returns 1.
1309 # Side effects: when the master won, moves the local version aside under
1310 # loser_name and pulls; when this side won, pushes (the server
1311 # moves its version aside).
1312 10 ▶sub _resolve_conflict :Private {
Subroutine _resolve_conflict: called CC=10 SCAR=26.0
1313 10 my ($self, $connection, $action, $after) = @_;
1314  
1315 10 my ($path, $loser) = @{$action}{qw(p loser_name)};
1316 10 ▶ my %winner = (p => $path, t => $action->{winner_type} || $TYPE_FILE, (defined $action->{h} ? (h => $action->{h}) : ()));
Branch: 1 branch
BranchTrueFalseTotal
defined $action->{'h'} ? : 10 0 10
Condition33%1/3
$action->{'winner_type'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
1000
MC/DC0%0/2
$action->{'winner_type'} || $App::FileSync::Client::TYPE_FILE
$action->{'winner_type'} $App::FileSync::Client::TYPE_FILE
Truth table33%1/3
A || B
A= $action->{'winner_type'}B= $App::FileSync::Client::TYPE_FILE
ABresult
1X1
011
000
1317  
1318 10 ▶ return $self->_push($connection, { %winner, loser_name => $loser }) if $action->{winner} ne 'remote';
Branch: 1 branch
BranchTrueFalseTotal
if $action->{"winner"} ne "remote" 4 6 10
1319  
1320 6 my $abs = $self->_abs($path);
1321 6 ▶ if ((-e $abs || -l $abs) && defined $loser) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $abs || -l $abs and defined $loser) 6 0 6
Condition33%2/6
-e $abs || -l $abs and defined $loser
!ll&&!rl&&r
006
-e $abs or -l $abs
l!l&&r!l&&!r
600
MC/DC0%0/3
-e $abs || -l $abs and defined $loser
-e $abs -l $abs defined $loser
Truth table20%1/5
A or B and C
A= -e $absB= -l $absC= defined $loser
ABCresult
00X0
1X00
0100
1X11
0111
1322 6 my $conflict = $self->_abs($loser);
1323 6 ▶ $self->_throw('client.conflict_exists', { path => $conflict }) if -e $conflict || -l $conflict;
Branch: 1 branch
BranchTrueFalseTotal
if -e $conflict or -l $conflict 0 6 6
Condition33%1/3
-e $conflict or -l $conflict
l!l&&r!l&&!r
006
MC/DC0%0/2
-e $conflict or -l $conflict
-e $conflict -l $conflict
Truth table33%1/3
A or B
A= -e $conflictB= -l $conflict
ABresult
1X1
011
000
1324 6 ensure_dir(dirname($conflict));
1325 6 ▶ eval { rename $abs, $conflict; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &App::FileSync::Client::rename($abs, $conflict); 1 } } or $self->_throw("client.conflict_move", {"path", $path, "to", $loser, "error", os_error($@)}) 6 0 6
1326 or $self->_throw('client.conflict_move', { path => $path, to => $loser, error => os_error($@) });
1327 6 $after->{$loser} = delete $after->{$path};
1328 }
1329  
1330 6 return $self->_pull($connection, \%winner, $after);
1331 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1332  
1333 # _delete_local
1334 # Purpose: remove a local path the master deleted.
1335 # Entry: $path is relative.
1336 # Exit: returns 1.
1337 # Side effects: moves the path into this repo's local trash.
1338 33 ▶sub _delete_local :Private {
Subroutine _delete_local: called CC=3 SCAR=12.0
1339 33 my ($self, $path) = @_;
1340  
1341 # A file already gone needs nothing; a dangling symlink is still moved.
1342 33 my $abs = $self->_abs($path);
1343 33 ▶ App::FileSync::Trash::move_to_trash(src => $abs, rel => $path, root => $self->_trash_root(), epoch => time)
Branch: 1 branch
BranchTrueFalseTotal
if -e $abs or -l $abs 33 0 33
Condition33%1/3
-e $abs or -l $abs
l!l&&r!l&&!r
3300
MC/DC0%0/2
-e $abs or -l $abs
-e $abs -l $abs
Truth table33%1/3
A or B
A= -e $absB= -l $abs
ABresult
1X1
011
000
1344 if -e $abs || -l $abs;
1345  
1346 33 return 1;
1347 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1348  
1349 # _request
1350 # Purpose: one lock-step exchange: send, receive, insist on ok.
1351 # Entry: $key is the catalogue key for a refusal, $args its arguments;
1352 # $bytes, when defined, is sent as a data payload.
1353 # Exit: returns the reply.
1354 # Side effects: raises $key with the server's reason.
1355 1304 ▶sub _request :Private {
Subroutine _request: called CC=4 SCAR=14.0
1356 1304 my ($self, $connection, $message, $key, $args, $bytes) = @_;
1357  
1358 1304 ▶ defined $bytes ? $connection->send_data($message, $bytes) : $connection->send($message);
Branch: 1 branch
BranchTrueFalseTotal
defined $bytes ? : 183 1121 1304
1359 1304 my $reply = $connection->recv();
1360 6 ▶ $self->_throw($key, { %{$args}, reason => $reply->{error} || $self->i18n('client.unknown_reason') })
Condition33%1/3
$reply->{'error'} || $self->i18n('client.unknown_reason')
l!l&&r!l&&!r
600
MC/DC0%0/2
$reply->{'error'} || $self->i18n('client.unknown_reason')
$reply->{'error'} $self->i18n('client.unknown_reason')
Truth table33%1/3
A || B
A= $reply->{'error'}B= $self->i18n('client.unknown_reason')
ABresult
1X1
011
000
1361 1304 ▶ unless $reply->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"ok"} 6 1298 1304
1362  
1363 1298 return $reply;
1364 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1365  
1366 # _abs
1367 # Purpose: the local path for a relative path from the server.
1368 # Entry: $path came over the wire.
1369 # Exit: returns ROOT/path.
1370 # Side effects: raises client.unsafe for a path that could escape the root.
1371 321 ▶sub _abs :Private {
Subroutine _abs: called CC=3 SCAR=12.5
1372 321 my ($self, $path) = @_;
1373  
1374 321 my ($ok, $reason) = validate_relpath($path);
1375 321 ▶ $self->_throw('client.unsafe', { path => $path // '', reason => $reason }) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 321 321
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
1376 321 return File::Spec->catfile($self->_repo_config()->{root}, split m{/}, $path);
1377 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1378  
1379 # _transport
1380 # Purpose: build the transport the repo's config asks for.
1381 # Entry: $repo is this repo's client config.
1382 # Exit: returns a started transport.
1383 # Side effects: starts the server (locally or over ssh). Per-repo SSH
1384 # settings fall back to the process settings.
1385 167 ▶sub _transport :Private {
Subroutine _transport: called CC=12 SCAR=29.1
1386 167 my ($self, $repo) = @_;
1387  
1388 167 ▶ my $type = $repo->{transport} || ($repo->{server_root} ? 'local' : 'ssh');
Branch: 1 branch
BranchTrueFalseTotal
$repo->{'server_root'} ? : 0 0 0
Condition33%1/3
$repo->{'transport'} || ($repo->{'server_root'} ? 'local' : 'ssh')
l!l&&r!l&&!r
16700
MC/DC0%0/2
$repo->{'transport'} || ($repo->{'server_root'} ? 'local' : 'ssh')
$repo->{'transport'} ($repo->{'server_root'} ? 'local' : 'ssh')
Truth table33%1/3
A || B
A= $repo->{'transport'}B= ($repo->{'server_root'} ? 'local' : 'ssh')
ABresult
1X1
011
000
1389 my %common = (
1390 repo => $repo->{remote_repo} || $self->{name},
1391 client => $self->{config}{client_id},
1392 167 ▶ role => $repo->{role} || $ROLE_CLIENT,
Condition33%2/6
$repo->{'remote_repo'} || $self->{'name'}
l!l&&r!l&&!r
16700
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
l!l&&r!l&&!r
16700
MC/DC0%0/2
$repo->{'remote_repo'} || $self->{'name'}
$repo->{'remote_repo'} $self->{'name'}
MC/DC0%0/2
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
$repo->{'role'} $App::FileSync::Client::ROLE_CLIENT
Truth table33%1/3
A || B
A= $repo->{'remote_repo'}B= $self->{'name'}
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= $repo->{'role'}B= $App::FileSync::Client::ROLE_CLIENT
ABresult
1X1
011
000
1393 );
1394  
1395 167 ▶ if ($type eq 'local') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "local") 158 9 167
1396 $self->_throw('client.need_server_root', { repo => $self->{name} })
1397 158 ▶ unless defined $repo->{server_root} && length $repo->{server_root};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $repo->{"server_root"} and length $repo->{"server_root"} 0 158 158
Condition33%1/3
defined $repo->{"server_root"} and length $repo->{"server_root"}
!ll&&!rl&&r
00158
MC/DC0%0/2
defined $repo->{"server_root"} and length $repo->{"server_root"}
defined $repo->{"server_root"} length $repo->{"server_root"}
Truth table33%1/3
A and B
A= defined $repo->{"server_root"}B= length $repo->{"server_root"}
ABresult
0X0
100
111
1398 158 return App::FileSync::Transport::Local->new(%common, root => $repo->{server_root}, server_bin => $repo->{server_bin});
1399 }
1400  
1401 9 ▶ $self->_throw('client.bad_transport', { transport => $type, repo => $self->{name} }) unless $type eq 'ssh';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "ssh" 0 9 9
1402 9 ▶ $self->_throw('client.need_server', { repo => $self->{name} }) unless defined $repo->{server} && length $repo->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $repo->{"server"} and length $repo->{"server"} 0 9 9
Condition33%1/3
defined $repo->{"server"} and length $repo->{"server"}
!ll&&!rl&&r
009
MC/DC0%0/2
defined $repo->{"server"} and length $repo->{"server"}
defined $repo->{"server"} length $repo->{"server"}
Truth table33%1/3
A and B
A= defined $repo->{"server"}B= length $repo->{"server"}
ABresult
0X0
100
111
1403  
1404 9 ▶ my $ssh = ref($self->{config}{ssh}) eq 'HASH' ? $self->{config}{ssh} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'config'}{'ssh'} eq 'HASH' ? : 9 0 9
1405 9 my $settings = $self->_settings();
1406 9 ▶ my $either = sub { my ($own, $fallback) = @_; (defined $own && length $own) ? $own : (defined $fallback && length $fallback) ? $fallback : undef };
Subroutine __ANON__: called CC=5 SCAR=16.3
Branch: 2 branches
BranchTrueFalseTotal
defined $own && length $own ? : 9 18 27
defined $fallback && length $fallback ? : 10 8 18
Condition66%4/6
defined $own and length $own
!ll&&!rl&&r
1809
defined $fallback and length $fallback
!ll&&!rl&&r
0810
MC/DC50%1/2
defined $own and length $own
defined $own length $own
MC/DC50%1/2
defined $fallback and length $fallback
defined $fallback length $fallback
Truth table66%2/3
A and B
A= defined $ownB= length $own
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $fallbackB= length $fallback
ABresult
0X0
100
111
1407  
1408 return App::FileSync::Transport::SSH->new(
1409 %common,
1410 server => $repo->{server},
1411 port => $repo->{port},
1412 identity => $either->($repo->{identity}, $settings->{ssh_identity}),
1413 known_hosts => $either->($repo->{known_hosts}, $settings->{ssh_known_hosts}),
1414 server_command => $either->($repo->{server_command}, $settings->{server_command}),
1415 host_key_checking => $repo->{host_key_checking},
1416 command => $ssh->{command},
1417 extra_args => $ssh->{extra_args},
1418 9 );
1419 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1420  
1421 # _settings
1422 # Purpose: the process settings, read once per client.
1423 # Entry: none.
1424 # Exit: returns a hashref.
1425 # Side effects: reads the settings file the first time. A bad settings
1426 # file is reported here rather than ignored: it decides which
1427 # key and program a sync uses.
1428 9 ▶sub _settings :Private {
Subroutine _settings: called CC=3 SCAR=11.7
1429 9 my ($self) = @_;
1430  
1431 9 ▶ $self->{settings} = App::FileSync::Settings::load() unless exists $self->{settings};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"settings"} 9 0 9
1432 9 ▶ return $self->{settings} || {};
Condition50%1/2
$self->{'settings'} || {}
l!l
90
MC/DC0%0/1
$self->{'settings'} || {}
$self->{'settings'}
Truth table50%1/2
A
A= $self->{'settings'}
Aresult
11
00
1433 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1434  
1435 # _record_run
1436 # Purpose: append one line per attempt to the run log, so "filesync log"
1437 # can audit what cron tried even when it failed or never got
1438 # the lock.
1439 # Entry: $result is a sync result or { exit, error }.
1440 # Exit: returns 1 if recorded, 0 if not.
1441 # Side effects: appends (on a fresh line, if a killed run left a torn one)
1442 # and trims the log. A failure is logged as a warning: losing
1443 # the audit line must not fail the sync.
1444 175 ▶sub _record_run :Private {
Subroutine _record_run: called CC=10 SCAR=23.2
1445 175 my ($self, $result) = @_;
1446  
1447 175 ▶ my $summary = ref($result->{summary}) eq 'HASH' ? $result->{summary} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $result->{'summary'} eq 'HASH' ? : 158 17 175
1448 my $entry = {
1449 ts => time,
1450 exit => ($result->{exit} // $EXIT_OK) + 0,
1451 dry_run => $result->{dry_run} ? 1 : 0,
1452 1575 ▶ summary => { map { $_ => ($summary->{$_} || 0) } @SUMMARY_KEYS },
Condition100%2/2
$summary->{$_} || 0
l!l
2501325
MC/DC100%1/1
$summary->{$_} || 0
$summary->{$_}
Truth table100%2/2
A
A= $summary->{$_}
Aresult
11
00
1453 40 ▶ warnings => [ map { strip_location($_) } @{ $result->{warnings} || [] } ],
Branch: 1 branch
BranchTrueFalseTotal
$result->{'locked'} ? : 8 167 175
Condition100%2/2
$result->{'warnings'} || []
l!l
15520
MC/DC100%1/1
$result->{'warnings'} || []
$result->{'warnings'}
Truth table100%2/2
A
A= $result->{'warnings'}
Aresult
11
00
1454 175 ▶ ($result->{locked} ? (locked => 1) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$result->{'dry_run'} ? : 8 167 175
Condition33%1/3
$result->{"exit"} // $App::FileSync::Client::EXIT_OK
l!l&&r!l&&!r
17500
MC/DC0%0/2
$result->{"exit"} // $App::FileSync::Client::EXIT_OK
$result->{"exit"} $App::FileSync::Client::EXIT_OK
Truth table33%1/3
A // B
A= $result->{"exit"}B= $App::FileSync::Client::EXIT_OK
ABresult
1X1
011
000
1455 };
1456 175 my $error = strip_location($result->{error});
1457 175 ▶ $entry->{error} = $error if length $error;
Branch: 1 branch
BranchTrueFalseTotal
if length $error 20 155 175
1458  
1459 175 my $path = $self->log_path();
1460 175 my $ok = eval { append_line($path, json_encode($entry)); $self->_trim_log($path); 1 };
1461 175 ▶ $self->{logger}->warn($self->i18n('client.record_failed', { path => $path, error => strip_location($@) })) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 175 175
1462  
1463 175 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 175 0 175
1464 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1465  
1466 # _trim_log
1467 # Purpose: keep only the newest $LOG_LIMIT lines.
1468 # Entry: $path exists.
1469 # Exit: returns 1 if trimmed, else 0.
1470 # Side effects: rewrites the log atomically when it is too long.
1471 175 ▶sub _trim_log :Private {
Subroutine _trim_log: called CC=3 SCAR=11.0
1472 175 my ($self, $path) = @_;
1473  
1474 175 my @lines = split /^/m, read_text($path);
1475 175 my $too_long = @lines > $LOG_LIMIT;
1476 175 ▶ write_atomic($path, join('', @lines[ -$LOG_LIMIT .. -1 ])) if $too_long;
Branch: 1 branch
BranchTrueFalseTotal
if $too_long 2 173 175
1477  
1478 175 ▶ return $too_long ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$too_long ? : 2 173 175
1479 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1480  
1481 # _save_cache
1482 # Purpose: record the new base after a successful sync.
1483 # Entry: $entries is the post-sync manifest; $patterns the ignore list
1484 # used.
1485 # Exit: returns 1.
1486 # Side effects: rewrites the cache atomically. The ignore list is kept so
1487 # verify can scan with the same exclusions when it runs offline.
1488 147 ▶sub _save_cache :Private {
Subroutine _save_cache: called CC=1 SCAR=0.0
1489 147 my ($self, $entries, $summary, $patterns) = @_;
1490  
1491 147 write_atomic($self->cache_path(), json_encode({
1492 version => 1,
1493 entries => $entries,
1494 ignore => $patterns,
1495 last_run => { ts => time, summary => $summary },
1496 }) . "\n");
1497  
1498 147 return 1;
1499 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1500  
1501 # _prune_local_trash
1502 # Purpose: drop this repo's trashed files older than local_trash_days.
1503 # Entry: $repo is this repo's client config.
1504 # Exit: returns 1.
1505 # Side effects: removes old day buckets from this repo's trash, and from
1506 # the legacy shared trash with the default retention (it can
1507 # no longer be attributed to one repo's setting).
1508 147 ▶sub _prune_local_trash :Private {
Subroutine _prune_local_trash: called CC=2 SCAR=7.4
1509 147 my ($self, $repo) = @_;
1510  
1511 147 ▶ App::FileSync::Trash::prune(root => $self->_trash_root(), days => $repo->{local_trash_days} // $TRASH_DAYS, now => time);
Condition33%1/3
$repo->{"local_trash_days"} // $App::FileSync::Client::TRASH_DAYS
l!l&&r!l&&!r
14700
MC/DC0%0/2
$repo->{"local_trash_days"} // $App::FileSync::Client::TRASH_DAYS
$repo->{"local_trash_days"} $App::FileSync::Client::TRASH_DAYS
Truth table33%1/3
A // B
A= $repo->{"local_trash_days"}B= $App::FileSync::Client::TRASH_DAYS
ABresult
1X1
011
000
1512 147 App::FileSync::Trash::prune(root => $self->_legacy_trash_root(), days => $TRASH_DAYS, now => time);
1513 147 return 1;
1514 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1515  
1516 # _repo_config
1517 # Purpose: this repo's entry in the client config.
1518 # Entry: none.
1519 # Exit: returns the hashref.
1520 # Side effects: raises client.no_repo.
1521 526 ▶sub _repo_config :Private {
Subroutine _repo_config: called CC=2 SCAR=7.0
1522 526 my ($self) = @_;
1523  
1524 526 my $repo = $self->{config}{repos}{ $self->{name} };
1525 526 ▶ $self->_throw('client.no_repo', { repo => $self->{name}, path => App::FileSync::Config::client_config_path() })
Branch: 1 branch
BranchTrueFalseTotal
unless ref $repo eq "HASH" 0 526 526
1526 unless ref($repo) eq 'HASH';
1527 526 return $repo;
1528 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1529  
1530 # _checked_root
1531 # Purpose: the sync root, after checking it is safe to sync.
1532 # Entry: $repo is this repo's client config.
1533 # Exit: returns the root.
1534 # Side effects: raises client.bad_root or client.no_marker. The marker
1535 # guards against syncing an unmounted drive's empty mount
1536 # point, which would look like every file was deleted.
1537 185 ▶sub _checked_root :Private {
Subroutine _checked_root: called CC=6 SCAR=21.4
1538 185 my ($self, $repo) = @_;
1539  
1540 185 my $root = $repo->{root};
1541 185 ▶ $self->_throw('client.bad_root', { repo => $self->{name}, root => $root // '(unset)' })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $root and length $root and -d $root 0 185 185
Condition25%2/8
defined $root and length $root and -d $root
!ll&&!rl&&r
00185
defined $root and length $root
!ll&&!rl&&r
00185
$root // "(unset)"
l!l
00
MC/DC0%0/3
defined $root and length $root and -d $root
defined $root length $root -d $root
MC/DC0%0/1
$root // "(unset)"
$root
Truth table25%1/4
A and B and C
A= defined $rootB= length $rootC= -d $root
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $root
Aresult
11
00
1542 unless defined $root && length $root && -d $root;
1543 185 ▶ $self->_throw('client.no_marker', { root => $root }) unless -e File::Spec->catfile($root, $ROOT_MARKER);
Branch: 1 branch
BranchTrueFalseTotal
unless -e "File::Spec"->catfile($root, $App::FileSync::Client::ROOT_MARKER) 3 182 185
1544 182 return $root;
1545 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1546  
1547 # _lock / _locked_result
1548 # Purpose: take this repo's run lock; describe a refusal.
1549 # Entry: $reason optionally overrides the refusal text.
1550 # Exit: _lock returns the held handle or undef; _locked_result a
1551 # result with exit 2.
1552 # Side effects: _lock creates the lock file.
1553 177 ▶sub _lock :Private {
Subroutine _lock: called CC=1 SCAR=0.0
1554 177 my ($self) = @_;
1555  
1556 177 return App::FileSync::Lock::acquire(path => $self->_home_file('locks', "$self->{name}.lock"), nonblock => 1);
1557 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1558  
1559 8 ▶sub _locked_result :Private {
Subroutine _locked_result: called CC=2 SCAR=7.1
1560 8 my ($self, $reason) = @_;
1561  
1562 return {
1563 repo => $self->{name},
1564 ok => 0,
1565 exit => $EXIT_LOCKED,
1566 locked => 1,
1567 8 ▶ error => $reason // $self->i18n('client.locked', { repo => $self->{name} }),
Condition66%2/3
$reason // $self->i18n("client.locked", {"repo", $self->{"name"}})
l!l&&r!l&&!r
350
MC/DC0%0/2
$reason // $self->i18n("client.locked", {"repo", $self->{"name"}})
$reason $self->i18n("client.locked", {"repo", $self->{"name"}})
Truth table66%2/3
A // B
A= $reasonB= $self->i18n("client.locked", {"repo", $self->{"name"}})
ABresult
1X1
011
000
1568 };
1569 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1570  
1571 # _home_file
1572 # Purpose: a file under the client's home directory.
1573 # Entry: directory and file names.
1574 # Exit: returns the path.
1575 # Side effects: raises config.no_home when there is no home.
1576 742 ▶sub _home_file :Private {
Subroutine _home_file: called CC=1 SCAR=0.0
1577 742 my ($self, @parts) = @_;
1578  
1579 742 return File::Spec->catfile(App::FileSync::Config::home_dir(), @parts);
1580 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1581  
1582 # _trash_root / _legacy_trash_root
1583 # Purpose: this repo's local trash, and the shared one older releases used.
1584 # Entry: none.
1585 # Exit: returns the directory.
1586 # Side effects: none.
1587 194 ▶sub _trash_root :Private {
Subroutine _trash_root: called CC=1 SCAR=0.0
1588 194 my ($self) = @_;
1589  
1590 194 return File::Spec->catdir(App::FileSync::Config::home_dir(), 'trash', $TRASH_REPOS, $self->{name});
1591 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1592  
1593 159 ▶sub _legacy_trash_root :Private {
Subroutine _legacy_trash_root: called CC=1 SCAR=0.0
1594 159 return File::Spec->catdir(App::FileSync::Config::home_dir(), 'trash');
1595 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1596  
1597 # _with_reserved
1598 # Purpose: an ignore list that always covers the snapshot directory.
1599 # Entry: $patterns is an arrayref (not changed).
1600 # Exit: returns a new arrayref.
1601 # Side effects: none. A replica's snapshots live inside its root; the
1602 # pattern is reserved so it applies even to a repo created
1603 # before snapshots existed, whose stored list lacks it.
1604 171 ▶sub _with_reserved :Private {
Subroutine _with_reserved: called CC=2 SCAR=6.9
1605 171 my ($patterns) = @_;
1606  
1607 171 ▶ return [ @{$patterns}, (any { $_ eq $SNAPSHOT_DIR } @{$patterns}) ? () : $SNAPSHOT_DIR ];
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
&any(sub { $_ eq $App::FileSync::Client::SNAPSHOT_DIR; } , @{$patterns;}) ? : 170 1 171
1608 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1609  
1610 # _has_warnings
1611 # Purpose: whether a logged run carried a warning.
1612 # Entry: $entry is a run-log entry.
1613 # Exit: returns 1 or 0.
1614 # Side effects: none. Older entries may predate one of the fields, so a
1615 # warning, a conflict or a skipped path each count.
1616 38 ▶sub _has_warnings :Private {
Subroutine _has_warnings: called CC=8 SCAR=21.8
1617 38 my ($entry) = @_;
1618  
1619 38 ▶ my $summary = $entry->{summary} || {};
Condition100%2/2
$entry->{'summary'} || {}
l!l
344
MC/DC100%1/1
$entry->{'summary'} || {}
$entry->{'summary'}
Truth table100%2/2
A
A= $entry->{'summary'}
Aresult
11
00
1620 38 ▶ return ((ref($entry->{warnings}) eq 'ARRAY' && @{ $entry->{warnings} })
Condition50%2/4
$summary->{'conflicts'} || 0
l!l
021
$summary->{'skipped'} || 0
l!l
021
MC/DC0%0/1
$summary->{'conflicts'} || 0
$summary->{'conflicts'}
MC/DC0%0/1
$summary->{'skipped'} || 0
$summary->{'skipped'}
Truth table50%1/2
A
A= $summary->{'conflicts'}
Aresult
11
00
Truth table50%1/2
A
A= $summary->{'skipped'}
Aresult
11
00
1621 || ($summary->{conflicts} || 0) > 0
1622 38 ▶ || ($summary->{skipped} || 0) > 0) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'warnings'} eq 'ARRAY' && @{$entry->{'warnings'};} || ($summary->{'conflicts'} || 0) > 0 || ($summary->{'skipped'} || 0) > 0 ? : 17 21 38
Condition66%6/9
ref $entry->{"warnings"} eq "ARRAY" and @{$entry->{"warnings"};} or ($summary->{"conflicts"} || 0) > 0 or ($summary->{"skipped"} || 0) > 0
l!l&&r!l&&!r
17021
ref $entry->{"warnings"} eq "ARRAY" and @{$entry->{"warnings"};} or ($summary->{"conflicts"} || 0) > 0
l!l&&r!l&&!r
17021
ref $entry->{"warnings"} eq "ARRAY" and @{$entry->{"warnings"};}
!ll&&!rl&&r
02117
MC/DC25%1/4
ref $entry->{"warnings"} eq "ARRAY" and @{$entry->{"warnings"};} or ($summary->{"conflicts"} || 0) > 0 or ($summary->{"skipped"} || 0) > 0
ref $entry->{"warnings"} eq "ARRAY" @{$entry->{"warnings"};} ($summary->{"conflicts"} || 0) > 0 ($summary->{"skipped"} || 0) > 0
Truth table28%2/7
A and B or C or D
A= ref $entry->{"warnings"} eq "ARRAY"B= @{$entry->{"warnings"};}C= ($summary->{"conflicts"} || 0) > 0D= ($summary->{"skipped"} || 0) > 0
ABCDresult
11XX1
0X1X1
101X1
0X011
10011
0X000
10000
1623 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1624  
1625 # _read_jsonl
1626 # Purpose: the JSON objects in a line-per-record file.
1627 # Entry: $path may not exist.
1628 # Exit: returns an arrayref of hashrefs.
1629 # Side effects: reads the file; lines that are not objects (a torn last
1630 # line) are skipped.
1631 69 ▶sub _read_jsonl :Private {
Subroutine _read_jsonl: called CC=3 SCAR=11.0
1632 69 my ($path) = @_;
1633  
1634 69 ▶ my @lines = -e $path ? split(/\n/, read_text($path)) : ();
Branch: 1 branch
BranchTrueFalseTotal
-e $path ? : 64 5 69
1635 69 ▶ return [ grep { ref($_) eq 'HASH' } map { length ? eval { json_decode($_) } : () } @lines ];
Branch: 1 branch
BranchTrueFalseTotal
length $_ ? : 206 0 206
1636 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1637  
1638 # _case_insensitive
1639 # Purpose: whether the sync root's filesystem folds case.
1640 # Entry: $root is a directory.
1641 # Exit: returns 1 or 0; when the probe cannot be written, guesses
1642 # from the OS (Windows folds case).
1643 # Side effects: creates and removes a probe file.
1644 167 ▶sub _case_insensitive :Private {
Subroutine _case_insensitive: called CC=4 SCAR=14.5
1645 167 my ($root) = @_;
1646  
1647 167 my $probe = File::Spec->catfile($root, $CASE_PROBE);
1648 167 my $created = eval { close(open_file($probe, '>')); 1 };
1649 167 ▶ return $^O eq 'MSWin32' ? 1 : 0 unless $created;
Branch: 2 branches
BranchTrueFalseTotal
unless $created 0 167 167
$^O eq 'MSWin32' ? : 0 0 0
1650  
1651 167 ▶ my $insensitive = -e File::Spec->catfile($root, uc $CASE_PROBE) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-e 'File::Spec'->catfile($root, uc $CASE_PROBE) ? : 0 167 167
1652 167 eval { unlink $probe };
1653 167 return $insensitive;
1654 326 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1655  
1656 326 1;
1657  
1658 __END__
« blib/lib/App/FileSync/Scan.pm ↑ Summary blib/lib/App/FileSync/Settings.pm »