blib/lib/App/FileSync/Client.pm

filter: Statementstmt 98.3% 651 / 662 Branchbran 79.9% 195 / 244 Conditioncond 55.9% 127 / 227 MC/DCmcdc 25.5% 33 / 129 Subroutinesub 100% 113 / 113 Podpod 100% 11 / 11 totaltotal 81.5% 1130 / 1386 CC 211 SCAR 22.0
CC
211
Cov
86%
_session
27.6
log
21.1
_transport
18.3
CRAP 9.0
« blib/lib/App/FileSync/Verify.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 428 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 428 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 428 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 428 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 428 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 428 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 428 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 428 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 428 ▶use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 428 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 428 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
21 428 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 428 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 428 ▶use parent 'App::FileSync::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 428 ▶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 428 ▶use App::FileSync::Args qw(named);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 428 ▶use App::FileSync::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 428 ▶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 428 );
35 428 ▶use App::FileSync::Delta;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 428 ▶use App::FileSync::I18N qw(os_error strip_location);
Subroutine BEGIN: called CC=1 SCAR=0.0
37 428 ▶use App::FileSync::IO qw(append_line ensure_dir install_file list_dir open_file read_text temp_file write_atomic);
Subroutine BEGIN: called CC=1 SCAR=0.0
38 428 ▶use App::FileSync::Ignore;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 428 ▶use App::FileSync::Lock;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 428 ▶use App::FileSync::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 428 ▶use App::FileSync::Scan;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 428 ▶use App::FileSync::Settings;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 428 ▶use App::FileSync::Snapshot;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 428 ▶use App::FileSync::Transport::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 428 ▶use App::FileSync::Transport::SSH;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 428 ▶use App::FileSync::Trash;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 428 ▶use App::FileSync::Verify;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 428 ▶use version; our $VERSION = version->declare('0.002.2');
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 # Tunables, kept as package variables so tests can localise them.
52 428 our $CHUNK = 262_144;
53 428 our $MANIFEST_CHUNK = 2_000;
54  
55 # How many run summaries the local log keeps before trimming the oldest.
56 428 our $LOG_LIMIT = 500;
57  
58 # How many runs "filesync log" shows when no limit is given.
59 428 Readonly::Scalar my $LOG_DEFAULT_LIMIT => 20;
60  
61 # Wire cost of one delta record (see the server's identical estimate).
62 428 Readonly::Scalar my $DELTA_OP_BYTES => 12;
63 428 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 428 Readonly::Scalar my $TRASH_REPOS => 'repos';
69  
70 # Names probed to discover whether the sync root's filesystem folds case.
71 428 Readonly::Scalar my $CASE_PROBE => "${TEMP_PREFIX}caseprobe";
72  
73 # Summary counters, in the order the run log records them.
74 428 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.2
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 322 ▶sub new {
Subroutine new: called CC=6 SCAR=18.1
Pod documented
164 322 my $class = shift;
165 322 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 322 ▶ App::FileSync::I18N::throw('client.no_config') unless $args->{config};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"config"} 0 322 322
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 322 my ($ok, $reason) = validate_repo_name($args->{name});
179 322 ▶ App::FileSync::I18N::throw('client.bad_name', { reason => $reason }) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 3 319 322
180  
181 319 ▶ my $opts = $args->{opts} || {};
Condition100%2/2
$args->{'opts'} || {}
l!l
25366
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 319 ▶ 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
123070
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 319 ▶ $self->{settings} = $args->{settings} if exists $args->{settings};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"settings"} 0 319 319
193 319 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 217 ▶sub sync {
Subroutine sync: called CC=6 SCAR=17.9
Pod documented
268 217 my ($self) = @_;
269  
270 217 my $repo = $self->_repo_config();
271 217 my $result = eval { $self->_run_session($repo) };
272  
273 217 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 17 200 217
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 17 my $error = $@;
277 17 $self->_record_run({ exit => $EXIT_FATAL, error => strip_location($error) });
278 17 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
279 }
280  
281 200 $self->_record_run($result);
282  
283 200 ▶ if ($result->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"ok"}) 192 8 200
284 $self->{logger}->info('sync finished', {
285 repo => $self->{name},
286 1344 ▶ (map { $_ => ($result->{summary}{$_} || 0) } qw(pulled pushed deleted conflicts skipped bytes_sent bytes_received)),
Branch: 1 branch
BranchTrueFalseTotal
$result->{'dry_run'} ? : 8 184 192
Condition80%4/5
$result->{'summary'}{$_} || 0
l!l
3081036
$result->{'exit'} || $App::FileSync::Client::EXIT_OK
l!l&&r!l&&!r
230169
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 192 dry_run => $result->{dry_run} ? 1 : 0,
289 });
290 }
291  
292 200 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 399 ▶sub cache_path {
Subroutine cache_path: called CC=1 SCAR=0.0
Pod documented
807 399 my ($self) = @_;
808  
809 399 return $self->_home_file('cache', "$self->{name}.json");
810 }
811  
812 286 ▶sub log_path {
Subroutine log_path: called CC=1 SCAR=0.0
Pod documented
813 286 my ($self) = @_;
814  
815 286 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 215 ▶sub cache {
Subroutine cache: called CC=4 SCAR=13.9
Pod documented
859 215 my ($self) = @_;
860  
861 215 my $path = $self->cache_path();
862 215 ▶ my $cache = -e $path ? eval { json_decode(read_text($path)) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $path ? : 130 85 215
863 215 ▶ $cache = {} unless ref($cache) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cache eq "HASH" 85 130 215
864 215 ▶ $cache->{entries} = {} unless ref($cache->{entries}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cache->{"entries"} eq "HASH" 85 130 215
865  
866 215 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 217 ▶sub _run_session :Private {
Subroutine _run_session: called CC=6 SCAR=18.0
879 217 my ($self, $repo) = @_;
880  
881 217 my $root = $self->_checked_root($repo);
882 214 ▶ my $lock = $self->_lock() or return $self->_locked_result();
Branch: 1 branch
BranchTrueFalseTotal
my $lock = $self->_lock or return $self->_locked_result 209 5 214
883  
884 209 my $transport = $self->_transport($repo);
885 208 my $connection = App::FileSync::Protocol->new(in => $transport->reader(), out => $transport->writer());
886  
887 208 my $result = eval { $self->_session($connection, $repo, $root) };
888 208 my $error = $@;
889 208 $transport->close();
890 208 ▶ return $result if $result;
Branch: 1 branch
BranchTrueFalseTotal
if $result 195 13 208
891  
892 13 ▶ if ($connection->transport_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($connection->transport_failed) 2 11 13
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 13 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
897 428 ▶}
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 208 ▶sub _session :Private {
Subroutine _session: called CC=25 SCAR=33.2
906 208 my ($self, $connection, $repo, $root) = @_;
907  
908 208 my $opts = $self->{opts};
909 208 my $client_id = $self->{config}{client_id};
910 208 ▶ $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 208 208
Condition33%1/3
defined $client_id and length $client_id
!ll&&!rl&&r
00208
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 208 ▶ force => $opts->{force} ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
$opts->{'dry_run'} ? : 9 199 208
$opts->{'force'} ? : 8 200 208
Condition33%2/6
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
l!l&&r!l&&!r
20800
$repo->{'remote_repo'} || $self->{'name'}
l!l&&r!l&&!r
20800
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 208 my $hello = $connection->recv();
927 206 ▶ unless ($hello->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hello->{"ok"}) 4 202 206
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 202 ▶ my $policy = $hello->{policy} || {};
Condition50%1/2
$hello->{'policy'} || {}
l!l
2020
MC/DC0%0/1
$hello->{'policy'} || {}
$hello->{'policy'}
Truth table50%1/2
A
A= $hello->{'policy'}
Aresult
11
00
936 202 ▶ my $patterns = _with_reserved($policy->{ignore} || []);
Condition50%1/2
$policy->{'ignore'} || []
l!l
2020
MC/DC0%0/1
$policy->{'ignore'} || []
$policy->{'ignore'}
Truth table50%1/2
A
A= $policy->{'ignore'}
Aresult
11
00
937 202 ▶ my $ignore = App::FileSync::Ignore->new(patterns => $patterns, case_insensitive => $hello->{case_insensitive} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$hello->{'case_insensitive'} ? : 0 202 202
938  
939 202 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 202 ) }{qw(manifest stats skipped)};
945  
946 202 $self->_send_manifest($connection, $manifest);
947  
948 202 my $plan = $self->_request($connection, { cmd => 'plan' }, 'client.req.plan', {});
949 193 ▶ my @actions = @{ $plan->{actions} || [] };
Condition50%1/2
$plan->{'actions'} || []
l!l
1930
MC/DC0%0/1
$plan->{'actions'} || []
$plan->{'actions'}
Truth table50%1/2
A
A= $plan->{'actions'}
Aresult
11
00
950 193 ▶ my @warnings = (@{ $plan->{warnings} || [] },
Condition50%1/2
$plan->{'warnings'} || []
l!l
1930
MC/DC0%0/1
$plan->{'warnings'} || []
$plan->{'warnings'}
Truth table50%1/2
A
A= $plan->{'warnings'}
Aresult
11
00
951 193 map { $self->i18n('client.skipped', { path => $_, reason => $skipped->{$_} }) } sort keys %{$skipped});
952  
953 my %planned = (
954 460 pulled => scalar(grep { $_->{a} eq 'pull' } @actions),
955 460 pushed => scalar(grep { $_->{a} eq 'push' } @actions),
956 460 deleted => scalar(grep { $_->{a} =~ /\Adelete_/ } @actions),
957 193 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 193 ▶ conflicts => $planned{conflicts}, dry_run => $opts->{dry_run} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'dry_run'} ? : 8 185 193
962 });
963  
964 193 my $summary = { (map { $_ => 0 } qw(pulled pushed deleted conflicts delta_pulled delta_pushed)), skipped => scalar(keys %{$skipped}) };
965 193 my %result = (repo => $self->{name}, ok => 1, summary => $summary, warnings => \@warnings, stats => $stats);
966  
967 193 ▶ if ($opts->{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"dry_run"}) 8 185 193
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 185 ▶ if ($opts->{verbose}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"verbose"}) 1 184 185
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 185 my %after = %{$manifest};
982 185 $self->_apply($connection, $_, \%after, $summary) for @actions;
983  
984 184 $self->_request($connection, { cmd => 'done' }, 'client.req.end', {});
985 184 ▶ @{$summary}{qw(delta_pulled delta_pushed)} = map { $self->{$_} || 0 } qw(delta_pulled delta_pushed);
Condition100%2/2
$self->{$_} || 0
l!l
3365
MC/DC100%1/1
$self->{$_} || 0
$self->{$_}
Truth table100%2/2
A
A= $self->{$_}
Aresult
11
00
986 184 @{$summary}{qw(bytes_sent bytes_received)} = ($connection->bytes_sent, $connection->bytes_received);
987  
988 184 $self->_save_cache(\%after, $summary, $patterns);
989 184 ▶ $self->_prune_local_trash($repo) unless $opts->{no_prune};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"no_prune"} 184 0 184
990  
991 184 ▶ return { %result, exit => @warnings ? $EXIT_WARNINGS : $EXIT_OK };
Branch: 1 branch
BranchTrueFalseTotal
@warnings ? : 22 162 184
992 428 ▶}
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 445 ▶sub _apply :Private {
Subroutine _apply: called CC=6 SCAR=17.9
1000 445 my ($self, $connection, $action, $after, $summary) = @_;
1001  
1002 445 my ($type, $path) = @{$action}{qw(a p)};
1003 445 ▶ if ($type eq 'pull') {
Branch: 5 branches
BranchTrueFalseTotal
if ($type eq 'pull') { } 92 353 445
elsif ($type eq 'push') { } 271 82 353
elsif ($type eq 'delete_remote') { } 36 46 82
elsif ($type eq 'delete_local') { } 35 11 46
elsif ($type eq 'conflict') { } 11 0 11
1004 92 $self->_pull($connection, $action, $after);
1005 92 $summary->{pulled}++;
1006 } elsif ($type eq 'push') {
1007 271 $self->_push($connection, $action);
1008 270 $summary->{pushed}++;
1009 } elsif ($type eq 'delete_remote') {
1010 36 $self->_request($connection, { cmd => 'del', p => $path }, 'client.req.delete', { path => $path });
1011 36 delete $after->{$path};
1012 36 $summary->{deleted}++;
1013 } elsif ($type eq 'delete_local') {
1014 35 $self->_delete_local($path);
1015 35 $self->_request($connection, { cmd => 'ack', p => $path, deleted => 1 }, 'client.req.ack_delete', { path => $path });
1016 35 delete $after->{$path};
1017 35 $summary->{deleted}++;
1018 } elsif ($type eq 'conflict') {
1019 11 $self->_resolve_conflict($connection, $action, $after);
1020 11 $summary->{conflicts}++;
1021 } else {
1022 0 $self->_throw('client.unknown_action', { action => $type, path => $path });
1023 }
1024  
1025 444 return 1;
1026 428 ▶}
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 202 ▶sub _send_manifest :Private {
Subroutine _send_manifest: called CC=3 SCAR=11.0
1035 202 my ($self, $connection, $manifest) = @_;
1036  
1037 202 my @entries = map { { p => $_, %{ $manifest->{$_} } } } sort keys %{$manifest};
1038 202 ▶ my $parts = @entries ? int((@entries - 1) / $MANIFEST_CHUNK) + 1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
@entries ? : 189 13 202
1039  
1040 202 for my $part (0 .. $parts - 1) {
1041 202 my @slice = splice(@entries, 0, $MANIFEST_CHUNK);
1042 202 $self->_request($connection, { cmd => 'manifest', part => $part, of => $parts, entries => \@slice },
1043 'client.req.manifest', {});
1044 }
1045  
1046 202 return 1;
1047 428 ▶}
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 99 ▶sub _pull :Private {
Subroutine _pull: called CC=4 SCAR=13.9
1056 99 my ($self, $connection, $action, $after) = @_;
1057  
1058 99 my $path = $action->{p};
1059 99 my $abs = $self->_abs($path);
1060  
1061 99 ▶ 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 93 99
Condition33%1/3
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
9900
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 93 ▶ return 1 if $self->_pull_delta($connection, $action, $after, $abs);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_pull_delta($connection, $action, $after, $abs) 1 92 93
1069  
1070 92 ▶ my $receipt = $self->_receive($abs, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1071 92 my ($write) = @_;
1072 92 my ($offset, %server) = (0);
1073 92 while (1) {
1074 93 my $header = $self->_request($connection, { cmd => 'get', p => $path, off => $offset, max => $CHUNK },
1075 'client.req.get', { path => $path });
1076 93 my $bytes = $connection->read_data($header);
1077 93 $write->($bytes);
1078 93 $offset += length $bytes;
1079 93 $server{$_} = $header->{$_} for grep { defined $header->{$_} } qw(s m mode h);
1080 93 ▶ last if $header->{eof};
Branch: 1 branch
BranchTrueFalseTotal
if $header->{"eof"} 92 1 93
1081 }
1082 92 return \%server;
1083 92 });
1084  
1085 92 return $self->_finish_pull($connection, $action, $after, $abs, $receipt);
1086 428 ▶}
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 93 ▶sub _pull_delta :Private {
Subroutine _pull_delta: called CC=8 SCAR=20.9
1096 93 my ($self, $connection, $action, $after, $abs) = @_;
1097  
1098 93 ▶ 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 85 8 93
Condition66%4/6
$self->{"opts"}{"no_delta"} or not -f $abs or -l $abs
l!l&&r!l&&!r
8508
$self->{"opts"}{"no_delta"} or not -f $abs
l!l&&r!l&&!r
0858
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 428 ▶}
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 428 ▶}
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 93 ▶sub _receive :Private {
Subroutine _receive: called CC=3 SCAR=11.4
1165 93 my ($self, $abs, $fill, @close) = @_;
1166  
1167 93 my ($out, $temp) = @{ temp_file(dirname($abs)) };
1168 93 my $sha = Digest::SHA->new($SHA_BITS);
1169 93 my $written = 0;
1170  
1171 93 my $server = eval {
1172 118 ▶ my $info = $fill->(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1173 118 my ($bytes) = @_;
1174 118 ▶ 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()}) 118 0 118
1175 118 $sha->add($bytes);
1176 118 $written += length $bytes;
1177 93 });
1178 93 close $out;
1179 93 $info;
1180 };
1181 93 my $error = $@;
1182 93 eval { close $_ } for grep { defined } @close;
1183  
1184 93 ▶ unless ($server) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server) 0 93 93
1185 0 eval { close $out };
1186 0 eval { unlink $temp };
1187 0 die $error; ## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
1188 }
1189  
1190 93 return { temp => $temp, hash => $sha->hexdigest(), written => $written, server => $server };
1191 428 ▶}
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; a directory that still holds
1199 # untracked files goes to the local trash); records the new
1200 # entry in $after. A mismatch removes the temporary file and
1201 # raises.
1202 93 ▶sub _finish_pull :Private {
Subroutine _finish_pull: called CC=11 SCAR=27.4
1203 93 my ($self, $connection, $action, $after, $abs, $receipt) = @_;
1204  
1205 93 my ($path, $server, $got) = ($action->{p}, $receipt->{server}, $receipt->{hash});
1206 93 ▶ my $expected = $action->{h} // $server->{h};
Condition33%1/3
$action->{"h"} // $server->{"h"}
l!l&&r!l&&!r
9300
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
1207  
1208 my ($key, %args) =
1209 (defined $expected && $got ne $expected) ? ('client.hash_mismatch', expected => $expected, got => $got)
1210 : (defined $server->{s} && $receipt->{written} != $server->{s}) ? ('client.size_mismatch', expected => $server->{s}, got => $receipt->{written})
1211 93 ▶ : ();
Branch: 2 branches
BranchTrueFalseTotal
defined $expected && $got ne $expected ? : 0 93 93
defined $server->{'s'} && $receipt->{'written'} != $server->{'s'} ? : 0 93 93
Condition33%2/6
defined $expected and $got ne $expected
!ll&&!rl&&r
0930
defined $server->{"s"} and $receipt->{"written"} != $server->{"s"}
!ll&&!rl&&r
0930
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
1212 93 ▶ if ($key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key) 0 93 93
1213 0 eval { unlink $receipt->{temp} };
1214 0 $self->_throw($key, { path => $path, %args });
1215 }
1216  
1217 # A directory where the file goes still holds what the sync does not list
1218 # (ignored files): its listed contents were deleted earlier in this plan.
1219 # Keep it in the local trash rather than refuse the file, which would fail
1220 # this and every later sync.
1221 93 ▶ if (-d $abs && !-l $abs && @{ list_dir($abs) || [$abs] }) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $abs and not -l $abs and @{list_dir($abs) or [$abs];}) 1 92 93
Condition75%6/8
-d $abs and not -l $abs and @{list_dir($abs) or [$abs];}
!ll&&!rl&&r
9111
-d $abs and not -l $abs
!ll&&!rl&&r
9102
list_dir($abs) || [$abs]
l!l
20
MC/DC66%2/3
-d $abs and not -l $abs and @{list_dir($abs) or [$abs];}
-d $abs not -l $abs @{list_dir($abs) or [$abs];}
MC/DC0%0/1
list_dir($abs) || [$abs]
list_dir($abs)
Truth table75%3/4
A and not(B) and C
A= -d $absB= not -l $absC= @{list_dir($abs) or [$abs];}
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= list_dir($abs)
Aresult
11
00
1222 1 $self->_delete_local($path);
1223 1 $self->{logger}->warn($self->i18n('client.dir_replaced', { path => $path, trash => $self->_trash_root() }));
1224 }
1225  
1226 93 install_file($receipt->{temp}, $abs, $server->{m}, $server->{mode});
1227  
1228 93 my %entry = (h => $got, s => $receipt->{written}, m => $server->{m}, mode => $server->{mode});
1229 93 $self->_request($connection, { cmd => 'ack', p => $path, %entry }, 'client.req.ack', { path => $path });
1230 93 $after->{$path} = { t => $TYPE_FILE, %entry };
1231 93 return 1;
1232 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1233  
1234 # _push
1235 # Purpose: send a local file (or directory) the plan says to push.
1236 # Entry: $action has p, t, h and, for a conflict this side won,
1237 # loser_name.
1238 # Exit: returns 1.
1239 # Side effects: transfers the file, as a delta when that is cheaper (never
1240 # for a conflict, where the server must first move its version
1241 # aside).
1242 275 ▶sub _push :Private {
Subroutine _push: called CC=8 SCAR=20.9
1243 275 my ($self, $connection, $action) = @_;
1244  
1245 275 my $path = $action->{p};
1246 275 my $abs = $self->_abs($path);
1247  
1248 275 ▶ 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) 7 268 275
Condition33%1/3
$action->{'t'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
27500
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
1249 7 $self->_request($connection, { cmd => 'mkdir', p => $path }, 'client.req.mkdir', { path => $path });
1250 7 return 1;
1251 }
1252  
1253 268 my @stat = Time::HiRes::stat($abs);
1254 268 ▶ $self->_throw('client.cannot_stat', { path => $abs, error => os_error() }) unless @stat;
Branch: 1 branch
BranchTrueFalseTotal
unless @stat 0 268 268
1255 268 my %file = (s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK);
1256  
1257 268 ▶ 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"}) 2 266 268
Condition100%3/3
not $action->{"loser_name"} and $self->_push_delta($connection, $path, $abs, \%file, $action->{"h"})
!ll&&!rl&&r
42622
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
1258  
1259 266 my $in = open_file($abs, '<:raw');
1260  
1261 # The server acknowledges the header before any chunk is sent; reading it
1262 # here keeps the lock-step protocol aligned.
1263 $self->_request($connection, {
1264 cmd => 'put', p => $path, t => $TYPE_FILE, %file, h => $action->{h},
1265 266 ▶ ($action->{loser_name} ? (conflict_name => $action->{loser_name}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$action->{'loser_name'} ? : 4 262 266
1266 }, 'client.req.put', { path => $path });
1267  
1268 265 ▶ while (read($in, my $buffer, $CHUNK)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&App::FileSync::Client::read($in, \my $buffer, $App::FileSync::Client::CHUNK)) 270 265 535
1269 270 $self->_request($connection, { cmd => 'chunk', p => $path }, 'client.req.chunk', { path => $path }, $buffer);
1270 }
1271 265 close $in;
1272  
1273 265 $self->_request($connection, { cmd => 'chunk_end', p => $path }, 'client.req.store', { path => $path });
1274 265 return 1;
1275 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1276  
1277 # _push_delta
1278 # Purpose: send only the blocks that changed since the master's version.
1279 # Entry: %{$file} has s, m, mode; $hash is the planned hash.
1280 # Exit: returns 1 if pushed as a delta, 0 when a whole-file put is
1281 # cheaper or there is nothing to reuse.
1282 # Side effects: spools the delta to a temporary file beside $abs.
1283 264 ▶sub _push_delta :Private {
Subroutine _push_delta: called CC=8 SCAR=20.8
1284 264 my ($self, $connection, $path, $abs, $file, $hash) = @_;
1285  
1286 264 ▶ 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 258 6 264
Condition83%5/6
$self->{"opts"}{"no_delta"} or not defined $hash or $file->{"s"} < $App::FileSync::Delta::MIN_SIZE
l!l&&r!l&&!r
12576
$self->{"opts"}{"no_delta"} or not defined $hash
l!l&&r!l&&!r
10263
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
1287  
1288 6 my $reply = $self->_request($connection, { cmd => 'sig', p => $path }, 'client.req.signature', { path => $path });
1289 6 ▶ return 0 unless $reply->{delta};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"delta"} 4 2 6
1290  
1291 2 my $blocks = App::FileSync::Delta::decode_signature($connection->read_data($reply), $reply->{n});
1292  
1293 2 my $spool = File::Temp->new(TEMPLATE => "${TEMP_PREFIX}delta-XXXXXXXX", DIR => dirname($abs), UNLINK => 1);
1294 2 binmode $spool;
1295 2 my $stats = App::FileSync::Delta::diff($abs, { size => $reply->{s}, blocklen => $reply->{b}, blocks => $blocks }, $spool);
1296  
1297 2 my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;
1298 2 ▶ return 0 if $estimated >= $file->{s};
Branch: 1 branch
BranchTrueFalseTotal
if $estimated >= $file->{"s"} 0 2 2
1299  
1300 2 $self->_request($connection, { cmd => 'delta', p => $path, %{$file}, h => $hash }, 'client.req.delta', { path => $path });
1301  
1302 2 seek($spool, 0, 0);
1303 2 ▶ while (my ($type, @rest) = App::FileSync::Delta::read_op($spool)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = App::FileSync::Delta::read_op($spool)) 30 2 32
1304 30 ▶ my ($message, $bytes) = $type eq 'copy'
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'copy' ? : 27 3 30
1305 ? ({ cmd => 'dcopy', p => $path, off => $rest[0], len => $rest[1] })
1306 : ({ cmd => 'dlit', p => $path }, $rest[0]);
1307 30 $self->_request($connection, $message, 'client.req.delta_data', { path => $path }, $bytes);
1308 }
1309  
1310 2 $self->_request($connection, { cmd => 'delta_end', p => $path }, 'client.req.store', { path => $path });
1311 2 $self->{delta_pushed}++;
1312 2 return 1;
1313 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1314  
1315 # _resolve_conflict
1316 # Purpose: carry out a conflict resolution.
1317 # Entry: $action has p, winner (client or remote), winner_type, h,
1318 # loser_name (when the losing side is a file).
1319 # Exit: returns 1.
1320 # Side effects: when the master won, moves the local version aside under
1321 # loser_name and pulls; when this side won, pushes (the server
1322 # moves its version aside).
1323 11 ▶sub _resolve_conflict :Private {
Subroutine _resolve_conflict: called CC=10 SCAR=26.0
1324 11 my ($self, $connection, $action, $after) = @_;
1325  
1326 11 my ($path, $loser) = @{$action}{qw(p loser_name)};
1327 11 ▶ my %winner = (p => $path, t => $action->{winner_type} || $TYPE_FILE, (defined $action->{h} ? (h => $action->{h}) : ()));
Branch: 1 branch
BranchTrueFalseTotal
defined $action->{'h'} ? : 11 0 11
Condition33%1/3
$action->{'winner_type'} || $App::FileSync::Client::TYPE_FILE
l!l&&r!l&&!r
1100
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
1328  
1329 11 ▶ return $self->_push($connection, { %winner, loser_name => $loser }) if $action->{winner} ne 'remote';
Branch: 1 branch
BranchTrueFalseTotal
if $action->{"winner"} ne "remote" 4 7 11
1330  
1331 7 my $abs = $self->_abs($path);
1332 7 ▶ if ((-e $abs || -l $abs) && defined $loser) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $abs || -l $abs and defined $loser) 7 0 7
Condition33%2/6
-e $abs || -l $abs and defined $loser
!ll&&!rl&&r
007
-e $abs or -l $abs
l!l&&r!l&&!r
700
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
1333 7 my $conflict = $self->_abs($loser);
1334 7 ▶ $self->_throw('client.conflict_exists', { path => $conflict }) if -e $conflict || -l $conflict;
Branch: 1 branch
BranchTrueFalseTotal
if -e $conflict or -l $conflict 0 7 7
Condition33%1/3
-e $conflict or -l $conflict
l!l&&r!l&&!r
007
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
1335 7 ensure_dir(dirname($conflict));
1336 7 ▶ 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($@)}) 7 0 7
1337 or $self->_throw('client.conflict_move', { path => $path, to => $loser, error => os_error($@) });
1338 7 $after->{$loser} = delete $after->{$path};
1339 }
1340  
1341 7 return $self->_pull($connection, \%winner, $after);
1342 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1343  
1344 # _delete_local
1345 # Purpose: remove a local path the master deleted.
1346 # Entry: $path is relative.
1347 # Exit: returns 1.
1348 # Side effects: moves the path into this repo's local trash.
1349 36 ▶sub _delete_local :Private {
Subroutine _delete_local: called CC=3 SCAR=12.0
1350 36 my ($self, $path) = @_;
1351  
1352 # A file already gone needs nothing; a dangling symlink is still moved.
1353 36 my $abs = $self->_abs($path);
1354 36 ▶ 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 36 0 36
Condition33%1/3
-e $abs or -l $abs
l!l&&r!l&&!r
3600
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
1355 if -e $abs || -l $abs;
1356  
1357 36 return 1;
1358 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1359  
1360 # _request
1361 # Purpose: one lock-step exchange: send, receive, insist on ok.
1362 # Entry: $key is the catalogue key for a refusal, $args its arguments;
1363 # $bytes, when defined, is sent as a data payload.
1364 # Exit: returns the reply.
1365 # Side effects: raises $key with the server's reason.
1366 1734 ▶sub _request :Private {
Subroutine _request: called CC=4 SCAR=14.0
1367 1734 my ($self, $connection, $message, $key, $args, $bytes) = @_;
1368  
1369 1734 ▶ defined $bytes ? $connection->send_data($message, $bytes) : $connection->send($message);
Branch: 1 branch
BranchTrueFalseTotal
defined $bytes ? : 274 1460 1734
1370 1734 my $reply = $connection->recv();
1371 10 ▶ $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
1000
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
1372 1734 ▶ unless $reply->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"ok"} 10 1724 1734
1373  
1374 1724 return $reply;
1375 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1376  
1377 # _abs
1378 # Purpose: the local path for a relative path from the server.
1379 # Entry: $path came over the wire.
1380 # Exit: returns ROOT/path.
1381 # Side effects: raises client.unsafe for a path that could escape the root.
1382 424 ▶sub _abs :Private {
Subroutine _abs: called CC=3 SCAR=12.5
1383 424 my ($self, $path) = @_;
1384  
1385 424 my ($ok, $reason) = validate_relpath($path);
1386 424 ▶ $self->_throw('client.unsafe', { path => $path // '', reason => $reason }) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 424 424
Condition0%0/2
$path // ""
l!l
00
MC/DC0%0/1
$path // ""
$path
Truth table0%0/2
A
A= $path
Aresult
11
00
1387 424 return File::Spec->catfile($self->_repo_config()->{root}, split m{/}, $path);
1388 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1389  
1390 # _transport
1391 # Purpose: build the transport the repo's config asks for.
1392 # Entry: $repo is this repo's client config.
1393 # Exit: returns a started transport.
1394 # Side effects: starts the server (locally or over ssh). Per-repo SSH
1395 # settings fall back to the process settings.
1396 209 ▶sub _transport :Private {
Subroutine _transport: called CC=12 SCAR=29.1
1397 209 my ($self, $repo) = @_;
1398  
1399 209 ▶ 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
20900
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
1400 my %common = (
1401 repo => $repo->{remote_repo} || $self->{name},
1402 client => $self->{config}{client_id},
1403 209 ▶ role => $repo->{role} || $ROLE_CLIENT,
Condition33%2/6
$repo->{'remote_repo'} || $self->{'name'}
l!l&&r!l&&!r
20900
$repo->{'role'} || $App::FileSync::Client::ROLE_CLIENT
l!l&&r!l&&!r
20900
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
1404 );
1405  
1406 209 ▶ if ($type eq 'local') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "local") 198 11 209
1407 $self->_throw('client.need_server_root', { repo => $self->{name} })
1408 198 ▶ unless defined $repo->{server_root} && length $repo->{server_root};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $repo->{"server_root"} and length $repo->{"server_root"} 0 198 198
Condition33%1/3
defined $repo->{"server_root"} and length $repo->{"server_root"}
!ll&&!rl&&r
00198
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
1409 198 return App::FileSync::Transport::Local->new(%common, root => $repo->{server_root}, server_bin => $repo->{server_bin});
1410 }
1411  
1412 11 ▶ $self->_throw('client.bad_transport', { transport => $type, repo => $self->{name} }) unless $type eq 'ssh';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "ssh" 0 11 11
1413 11 ▶ $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 11 11
Condition33%1/3
defined $repo->{"server"} and length $repo->{"server"}
!ll&&!rl&&r
0011
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
1414  
1415 11 ▶ my $ssh = ref($self->{config}{ssh}) eq 'HASH' ? $self->{config}{ssh} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'config'}{'ssh'} eq 'HASH' ? : 11 0 11
1416 11 my $settings = $self->_settings();
1417 11 ▶ 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 ? : 15 18 33
defined $fallback && length $fallback ? : 10 8 18
Condition66%4/6
defined $own and length $own
!ll&&!rl&&r
18015
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
1418  
1419 return App::FileSync::Transport::SSH->new(
1420 %common,
1421 server => $repo->{server},
1422 port => $repo->{port},
1423 identity => $either->($repo->{identity}, $settings->{ssh_identity}),
1424 known_hosts => $either->($repo->{known_hosts}, $settings->{ssh_known_hosts}),
1425 server_command => $either->($repo->{server_command}, $settings->{server_command}),
1426 host_key_checking => $repo->{host_key_checking},
1427 command => $ssh->{command},
1428 extra_args => $ssh->{extra_args},
1429 11 );
1430 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1431  
1432 # _settings
1433 # Purpose: the process settings, read once per client.
1434 # Entry: none.
1435 # Exit: returns a hashref.
1436 # Side effects: reads the settings file the first time. A bad settings
1437 # file is reported here rather than ignored: it decides which
1438 # key and program a sync uses.
1439 11 ▶sub _settings :Private {
Subroutine _settings: called CC=3 SCAR=11.7
1440 11 my ($self) = @_;
1441  
1442 11 ▶ $self->{settings} = App::FileSync::Settings::load() unless exists $self->{settings};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"settings"} 11 0 11
1443 11 ▶ return $self->{settings} || {};
Condition50%1/2
$self->{'settings'} || {}
l!l
110
MC/DC0%0/1
$self->{'settings'} || {}
$self->{'settings'}
Truth table50%1/2
A
A= $self->{'settings'}
Aresult
11
00
1444 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1445  
1446 # _record_run
1447 # Purpose: append one line per attempt to the run log, so "filesync log"
1448 # can audit what cron tried even when it failed or never got
1449 # the lock.
1450 # Entry: $result is a sync result or { exit, error }.
1451 # Exit: returns 1 if recorded, 0 if not.
1452 # Side effects: appends (on a fresh line, if a killed run left a torn one)
1453 # and trims the log. A failure is logged as a warning: losing
1454 # the audit line must not fail the sync.
1455 217 ▶sub _record_run :Private {
Subroutine _record_run: called CC=10 SCAR=23.2
1456 217 my ($self, $result) = @_;
1457  
1458 217 ▶ my $summary = ref($result->{summary}) eq 'HASH' ? $result->{summary} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $result->{'summary'} eq 'HASH' ? : 195 22 217
1459 my $entry = {
1460 ts => time,
1461 exit => ($result->{exit} // $EXIT_OK) + 0,
1462 dry_run => $result->{dry_run} ? 1 : 0,
1463 1953 ▶ summary => { map { $_ => ($summary->{$_} || 0) } @SUMMARY_KEYS },
Condition100%2/2
$summary->{$_} || 0
l!l
3111642
MC/DC100%1/1
$summary->{$_} || 0
$summary->{$_}
Truth table100%2/2
A
A= $summary->{$_}
Aresult
11
00
1464 41 ▶ warnings => [ map { strip_location($_) } @{ $result->{warnings} || [] } ],
Branch: 1 branch
BranchTrueFalseTotal
$result->{'locked'} ? : 8 209 217
Condition100%2/2
$result->{'warnings'} || []
l!l
19225
MC/DC100%1/1
$result->{'warnings'} || []
$result->{'warnings'}
Truth table100%2/2
A
A= $result->{'warnings'}
Aresult
11
00
1465 217 ▶ ($result->{locked} ? (locked => 1) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$result->{'dry_run'} ? : 8 209 217
Condition33%1/3
$result->{"exit"} // $App::FileSync::Client::EXIT_OK
l!l&&r!l&&!r
21700
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
1466 };
1467 217 my $error = strip_location($result->{error});
1468 217 ▶ $entry->{error} = $error if length $error;
Branch: 1 branch
BranchTrueFalseTotal
if length $error 25 192 217
1469  
1470 217 my $path = $self->log_path();
1471 217 my $ok = eval { append_line($path, json_encode($entry)); $self->_trim_log($path); 1 };
1472 217 ▶ $self->{logger}->warn($self->i18n('client.record_failed', { path => $path, error => strip_location($@) })) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 217 217
1473  
1474 217 ▶ return $ok ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 217 0 217
1475 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1476  
1477 # _trim_log
1478 # Purpose: keep only the newest $LOG_LIMIT lines.
1479 # Entry: $path exists.
1480 # Exit: returns 1 if trimmed, else 0.
1481 # Side effects: rewrites the log atomically when it is too long.
1482 217 ▶sub _trim_log :Private {
Subroutine _trim_log: called CC=3 SCAR=11.0
1483 217 my ($self, $path) = @_;
1484  
1485 217 my @lines = split /^/m, read_text($path);
1486 217 my $too_long = @lines > $LOG_LIMIT;
1487 217 ▶ write_atomic($path, join('', @lines[ -$LOG_LIMIT .. -1 ])) if $too_long;
Branch: 1 branch
BranchTrueFalseTotal
if $too_long 2 215 217
1488  
1489 217 ▶ return $too_long ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$too_long ? : 2 215 217
1490 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1491  
1492 # _save_cache
1493 # Purpose: record the new base after a successful sync.
1494 # Entry: $entries is the post-sync manifest; $patterns the ignore list
1495 # used.
1496 # Exit: returns 1.
1497 # Side effects: rewrites the cache atomically. The ignore list is kept so
1498 # verify can scan with the same exclusions when it runs offline.
1499 184 ▶sub _save_cache :Private {
Subroutine _save_cache: called CC=1 SCAR=0.0
1500 184 my ($self, $entries, $summary, $patterns) = @_;
1501  
1502 184 write_atomic($self->cache_path(), json_encode({
1503 version => 1,
1504 entries => $entries,
1505 ignore => $patterns,
1506 last_run => { ts => time, summary => $summary },
1507 }) . "\n");
1508  
1509 184 return 1;
1510 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1511  
1512 # _prune_local_trash
1513 # Purpose: drop this repo's trashed files older than local_trash_days.
1514 # Entry: $repo is this repo's client config.
1515 # Exit: returns 1.
1516 # Side effects: removes old day buckets from this repo's trash, and from
1517 # the legacy shared trash with the default retention (it can
1518 # no longer be attributed to one repo's setting).
1519 184 ▶sub _prune_local_trash :Private {
Subroutine _prune_local_trash: called CC=2 SCAR=7.4
1520 184 my ($self, $repo) = @_;
1521  
1522 184 ▶ 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
18400
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
1523 184 App::FileSync::Trash::prune(root => $self->_legacy_trash_root(), days => $TRASH_DAYS, now => time);
1524 184 return 1;
1525 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1526  
1527 # _repo_config
1528 # Purpose: this repo's entry in the client config.
1529 # Entry: none.
1530 # Exit: returns the hashref.
1531 # Side effects: raises client.no_repo.
1532 671 ▶sub _repo_config :Private {
Subroutine _repo_config: called CC=2 SCAR=7.0
1533 671 my ($self) = @_;
1534  
1535 671 my $repo = $self->{config}{repos}{ $self->{name} };
1536 671 ▶ $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 671 671
1537 unless ref($repo) eq 'HASH';
1538 671 return $repo;
1539 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1540  
1541 # _checked_root
1542 # Purpose: the sync root, after checking it is safe to sync.
1543 # Entry: $repo is this repo's client config.
1544 # Exit: returns the root.
1545 # Side effects: raises client.bad_root or client.no_marker. The marker
1546 # guards against syncing an unmounted drive's empty mount
1547 # point, which would look like every file was deleted.
1548 227 ▶sub _checked_root :Private {
Subroutine _checked_root: called CC=6 SCAR=21.4
1549 227 my ($self, $repo) = @_;
1550  
1551 227 my $root = $repo->{root};
1552 227 ▶ $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 227 227
Condition25%2/8
defined $root and length $root and -d $root
!ll&&!rl&&r
00227
defined $root and length $root
!ll&&!rl&&r
00227
$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
1553 unless defined $root && length $root && -d $root;
1554 227 ▶ $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 224 227
1555 224 return $root;
1556 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1557  
1558 # _lock / _locked_result
1559 # Purpose: take this repo's run lock; describe a refusal.
1560 # Entry: $reason optionally overrides the refusal text.
1561 # Exit: _lock returns the held handle or undef; _locked_result a
1562 # result with exit 2.
1563 # Side effects: _lock creates the lock file.
1564 219 ▶sub _lock :Private {
Subroutine _lock: called CC=1 SCAR=0.0
1565 219 my ($self) = @_;
1566  
1567 219 return App::FileSync::Lock::acquire(path => $self->_home_file('locks', "$self->{name}.lock"), nonblock => 1);
1568 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1569  
1570 8 ▶sub _locked_result :Private {
Subroutine _locked_result: called CC=2 SCAR=7.1
1571 8 my ($self, $reason) = @_;
1572  
1573 return {
1574 repo => $self->{name},
1575 ok => 0,
1576 exit => $EXIT_LOCKED,
1577 locked => 1,
1578 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
1579 };
1580 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1581  
1582 # _home_file
1583 # Purpose: a file under the client's home directory.
1584 # Entry: directory and file names.
1585 # Exit: returns the path.
1586 # Side effects: raises config.no_home when there is no home.
1587 904 ▶sub _home_file :Private {
Subroutine _home_file: called CC=1 SCAR=0.0
1588 904 my ($self, @parts) = @_;
1589  
1590 904 return File::Spec->catfile(App::FileSync::Config::home_dir(), @parts);
1591 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1592  
1593 # _trash_root / _legacy_trash_root
1594 # Purpose: this repo's local trash, and the shared one older releases used.
1595 # Entry: none.
1596 # Exit: returns the directory.
1597 # Side effects: none.
1598 235 ▶sub _trash_root :Private {
Subroutine _trash_root: called CC=1 SCAR=0.0
1599 235 my ($self) = @_;
1600  
1601 235 return File::Spec->catdir(App::FileSync::Config::home_dir(), 'trash', $TRASH_REPOS, $self->{name});
1602 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1603  
1604 196 ▶sub _legacy_trash_root :Private {
Subroutine _legacy_trash_root: called CC=1 SCAR=0.0
1605 196 return File::Spec->catdir(App::FileSync::Config::home_dir(), 'trash');
1606 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1607  
1608 # _with_reserved
1609 # Purpose: an ignore list that always covers the snapshot directory.
1610 # Entry: $patterns is an arrayref (not changed).
1611 # Exit: returns a new arrayref.
1612 # Side effects: none. A replica's snapshots live inside its root; the
1613 # pattern is reserved so it applies even to a repo created
1614 # before snapshots existed, whose stored list lacks it.
1615 212 ▶sub _with_reserved :Private {
Subroutine _with_reserved: called CC=2 SCAR=6.9
1616 212 my ($patterns) = @_;
1617  
1618 212 ▶ 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;}) ? : 211 1 212
1619 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1620  
1621 # _has_warnings
1622 # Purpose: whether a logged run carried a warning.
1623 # Entry: $entry is a run-log entry.
1624 # Exit: returns 1 or 0.
1625 # Side effects: none. Older entries may predate one of the fields, so a
1626 # warning, a conflict or a skipped path each count.
1627 38 ▶sub _has_warnings :Private {
Subroutine _has_warnings: called CC=8 SCAR=21.8
1628 38 my ($entry) = @_;
1629  
1630 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
1631 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
1632 || ($summary->{conflicts} || 0) > 0
1633 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
1634 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1635  
1636 # _read_jsonl
1637 # Purpose: the JSON objects in a line-per-record file.
1638 # Entry: $path may not exist.
1639 # Exit: returns an arrayref of hashrefs.
1640 # Side effects: reads the file; lines that are not objects (a torn last
1641 # line) are skipped.
1642 69 ▶sub _read_jsonl :Private {
Subroutine _read_jsonl: called CC=3 SCAR=11.0
1643 69 my ($path) = @_;
1644  
1645 69 ▶ my @lines = -e $path ? split(/\n/, read_text($path)) : ();
Branch: 1 branch
BranchTrueFalseTotal
-e $path ? : 64 5 69
1646 69 ▶ return [ grep { ref($_) eq 'HASH' } map { length ? eval { json_decode($_) } : () } @lines ];
Branch: 1 branch
BranchTrueFalseTotal
length $_ ? : 206 0 206
1647 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1648  
1649 # _case_insensitive
1650 # Purpose: whether the sync root's filesystem folds case.
1651 # Entry: $root is a directory.
1652 # Exit: returns 1 or 0; when the probe cannot be written, guesses
1653 # from the OS (Windows folds case).
1654 # Side effects: creates and removes a probe file.
1655 208 ▶sub _case_insensitive :Private {
Subroutine _case_insensitive: called CC=4 SCAR=14.5
1656 208 my ($root) = @_;
1657  
1658 208 my $probe = File::Spec->catfile($root, $CASE_PROBE);
1659 208 my $created = eval { close(open_file($probe, '>')); 1 };
1660 208 ▶ return $^O eq 'MSWin32' ? 1 : 0 unless $created;
Branch: 2 branches
BranchTrueFalseTotal
unless $created 0 208 208
$^O eq 'MSWin32' ? : 0 0 0
1661  
1662 208 ▶ 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 208 208
1663 208 eval { unlink $probe };
1664 208 return $insensitive;
1665 428 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1666  
1667 428 1;
1668  
1669 __END__
« blib/lib/App/FileSync/Verify.pm ↑ Summary blib/lib/App/FileSync/Settings.pm »