blib/lib/App/FileSync.pm

filter: Statementstmt 97.0% 132 / 136 Branchbran 92.3% 72 / 78 Conditioncond 73.3% 11 / 15 MC/DCmcdc 50.0% 4 / 8 Subroutinesub 96.9% 32 / 33 Podpod 100% 11 / 11 totaltotal 93.2% 262 / 281 CC 50 SCAR 20.0
CC
50
Cov
94%
validate_relpath
18.0
__ANON__
11.0
_validate_id
7.0
CRAP 7.4
« blib/lib/App/FileSync/Scan.pm ↑ Summary blib/lib/App/FileSync/Ignore.pm »
1 package App::FileSync;
2  
3 # The pieces shared by the client, the server and the admin tools:
4 # byte-transparent JSON, path and id validation, conflict-copy naming, date
5 # parsing and (re-exported from App::FileSync::IO) atomic file writes.
6  
7 # TODO: open work from the 0.002.0 gap analysis. None of it blocks a
8 # release: 0.002.1 and 0.002.2 shipped with it.
9 #
10 # Mutation testing:
11 # TODO: Server.pm's remaining survivors (about 80 of its 154 mutants) all
12 # negate or undef a return value nothing reads: _loop discards every
13 # command handler's, and the upload, journal and _reply helpers' callers
14 # ignore theirs. Either test them white-box or stop promising "returns 1".
15 # TODO: kill the two survivors: nothing checks the return value of
16 # Platform::use_plain_end_of_scope_hook.
17 #
18 # Documentation:
19 # TODO: =head3 PSEUDOCODE for the 24 public routines over 15 lines without it
20 # (Server::new, Client::new, Trash::move_to_trash and prune,
21 # Merge::check_delete_limit, Scan::clean_stale_temps, Ignore::new, ...).
22 # TODO: UTF-8 notes in Scan, Ignore, Trash, Snapshot and Store: names are
23 # bytes, and NFC and NFD forms of a name are different files.
24 # TODO: warn when the client cache is damaged: the run silently re-hashes
25 # every file (no data is at risk; the merge base is on the server).
26 #
27 # Post-release roadmap: features.
28 # TODO: incremental manifests (a change journal or Merkle summary), so an
29 # idle run costs almost nothing instead of O(files).
30 # TODO: "filesync watch": sync on file changes (inotify, FSEvents,
31 # ReadDirectoryChangesW), with cron as the fallback.
32 # TODO: let a client restore from the server's trash (admin-only today).
33 # TODO: selective sync: a client takes only a subtree of a repo.
34 # TODO: --bwlimit and a quiet-hours window for metered links.
35 # TODO: monitoring output: a node-exporter textfile, or a status --json health
36 # summary that alerts on repeated exit codes 3 or 4.
37 # TODO: reconcile NFC and NFD forms of a name (the macOS/Linux gap).
38 # TODO: a conflict review command to list and resolve conflict copies.
39 #
40 # Post-release roadmap: technical debt.
41 # TODO: mutation-test Trash, Store and Client next (Merge, Delta and Server
42 # are done, and t/mutation.t holds them to their scores), and gate CI
43 # on condition coverage (57% now). CI's mutation workflow is shared by
44 # every repo and pins App::Test::Generator 0.50, which drops every
45 # module that loads another App::FileSync module; it needs 0.51.
46 # TODO: pipeline the protocol: one request in flight bounds throughput by the
47 # round-trip time.
48 # TODO: stream the plan as JSON lines instead of one huge line, which also
49 # bounds message size.
50 # TODO: fsync: renames are atomic between processes but not durable across a
51 # power cut.
52 # TODO: an optional native rolling checksum (Inline::C or XS) to lift the
53 # 8 MiB scan window; pure Perl manages about 2.5 MB/s when nothing matches.
54  
55 435 ▶use App::FileSync::Platform;
Subroutine BEGIN: called CC=1 SCAR=0.0
56  
57 435 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 435 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 435 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
60 435 ▶use feature 'current_sub';
Subroutine BEGIN: called CC=1 SCAR=0.0
61  
62 435 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
63 435 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
64 435 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
65 435 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 435 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
67 435 ▶use Time::Local ();
Subroutine BEGIN: called CC=1 SCAR=0.0
68  
69 435 ▶use App::FileSync::Constants qw($MAX_ID_LENGTH $SECONDS_PER_DAY);
Subroutine BEGIN: called CC=1 SCAR=0.0
70 435 ▶use App::FileSync::I18N qw(message throw);
Subroutine BEGIN: called CC=1 SCAR=0.0
71 435 ▶use App::FileSync::IO qw(write_atomic read_text set_mtime);
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 435 ▶use version; our $VERSION = version->declare('0.002.2');
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 435 our @EXPORT_OK = qw(
76 json_encode json_decode
77 validate_relpath validate_repo_name validate_client_id
78 conflict_name name_with_suffix split_name
79 format_utc parse_since parse_until
80 write_atomic read_text set_mtime
81 );
82  
83 # Limits on paths as they travel on the wire. Package variables rather than
84 # Readonly because they document the protocol and tests read them.
85 435 our $MAX_PATH_BYTES = 4096;
86 435 our $MAX_COMPONENT_BYTES = 255;
87  
88 # A conflict-copy name is kept this far inside the common 255-byte limit, and
89 # never trims the original stem below the minimum.
90 435 Readonly::Scalar my $CONFLICT_NAME_BYTES => 200;
91 435 Readonly::Scalar my $MIN_STEM_BYTES => 16;
92  
93 # The alphabet of a repo or client id: it becomes a directory name.
94 435 Readonly my $ID_PATTERN => qr/\A[A-Za-z0-9][A-Za-z0-9._-]*\z/;
95  
96 # What an unusable client id is replaced with in a conflict-copy name.
97 435 Readonly::Scalar my $UNKNOWN_CLIENT => 'unknown';
98  
99 # format_utc's ISO 8601 basic format: 20261104T014157Z.
100 435 Readonly::Scalar my $UTC_STAMP => '%Y%m%dT%H%M%SZ';
101  
102 # JSON::MaybeXS picks Cpanel::JSON::XS, then JSON::XS, then the core JSON::PP,
103 # and installing it pulls in Cpanel::JSON::XS wherever there is a compiler. On
104 # a 100,000-file manifest Cpanel::JSON::XS decodes in 0.2s where JSON::PP takes
105 # about 15s. All three read any valid JSON, so a client and a server using
106 # different backends still understand each other. The text differs only in
107 # number formatting (Cpanel::JSON::XS writes a whole-valued float as 1000.0),
108 # which decodes to the same value everywhere.
109 #
110 # Deliberately utf8(0): paths are byte strings on the wire, and both ends of the
111 # protocol are this implementation.
112 435 my $JSON = JSON::MaybeXS->new->canonical->allow_nonref;
113  
114 # Both backends return UTF8-flagged strings even though paths are byte strings on
115 # disk. Left alone, the flag makes -e/stat encode the name a second time and
116 # every non-ASCII file "disappears". This downgrades back to the original
117 # bytes; only a genuine wide-character string is encoded as UTF-8.
118 #
119 # Hash keys need the same treatment, and manifests are keyed by path, but a key
120 # cannot be changed in place: a non-ASCII key is deleted and stored again as
121 # bytes. An ASCII key names the same file flagged or not, so it is left alone,
122 # which keeps the cost to one pattern match per key.
123 #
124 # A lexical coderef rather than a named sub: it runs once per JSON value (six
125 # times per manifest entry), and the Sub::Private enforce wrapper would cost
126 # more than the work. Being lexical, nothing outside this file can reach it.
127 82505 ▶my $to_bytes = sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
128 # Work through @_ aliases: copying the scalar would rewrite the copy only.
129 82505 ▶ if (ref($_[0]) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 14761 67744 82505
elsif (ref $_[0] eq 'ARRAY') { } 2322 65422 67744
elsif (defined $_[0] and not ref $_[0] and utf8::is_utf8($_[0])) { } 9 66572 66581
130 14761 my $hash = $_[0];
131 14761 for my $key (grep { /[^\x00-\x7f]/ } keys %{$hash}) {
132 13 my $bytes = $key;
133 13 ▶ utf8::encode($bytes) unless utf8::downgrade($bytes, 1);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::downgrade($bytes, 1) 0 13 13
134 # delete first: a flagged key and its bytes are the same hash key.
135 13 my $value = delete $hash->{$key};
136 13 $hash->{$bytes} = $value;
137 }
138 14761 __SUB__->($_) for values %{$hash};
139 } elsif (ref($_[0]) eq 'ARRAY') {
140 2322 __SUB__->($_) for @{ $_[0] };
141 ▶ } elsif (defined($_[0]) && !ref($_[0]) && utf8::is_utf8($_[0])) {
Condition100%6/6
defined $_[0] and not ref $_[0] and utf8::is_utf8($_[0])
!ll&&!rl&&r
1159642549
defined $_[0] and not ref $_[0]
!ll&&!rl&&r
10114964263
MC/DC100%3/3
defined $_[0] and not ref $_[0] and utf8::is_utf8($_[0])
defined $_[0] not ref $_[0] utf8::is_utf8($_[0])
Truth table100%4/4
A and not(B) and C
A= defined $_[0]B= not ref $_[0]C= utf8::is_utf8($_[0])
ABCresult
0XX0
10X0
1100
1111
142 9 ▶ utf8::encode($_[0]) unless utf8::downgrade($_[0], 1);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::downgrade($_[0], 1) 0 9 9
143 }
144 82505 return 1;
145 435 };
146  
147 =encoding utf8
148  
149 =head1 NAME
150  
151 App::FileSync - cron-driven file synchronisation without a daemon
152  
153 =head1 VERSION
154  
155 0.002.2
156  
157 =head1 SYNOPSIS
158  
159 filesync-admin --root ~/filesync repo create documents
160 filesync init --repo documents --root ~/Documents \
161 --transport local --server-root ~/filesync --remote-repo documents
162 filesync sync --repo documents --dry-run
163 filesync sync --repo documents
164  
165 =head1 DESCRIPTION
166  
167 App::FileSync keeps a directory on each client in step with one master copy on
168 the server. Clients never talk to each other: each pushes its changes to the
169 master and pulls everyone else's from it, so a change made on one client - a
170 new file, an edit or a deletion - reaches the others on their next run. Any
171 number of clients can share a repo this way.
172  
173 A separate machine can hold a replica of the master. Every run is a
174 short-lived CLI process suitable for cron or the Windows Task Scheduler: there
175 is no daemon, no database and no web interface.
176  
177 Only files whose content changed are transferred. Data frames are deflated when that
178 makes them smaller, and files of at least 64 KiB are sent as rsync-style block deltas
179 when the other side already holds an older copy, so an edit moves the changed blocks
180 rather than the whole file. C<filesync sync --no-delta> forces whole files. Each run
181 reports the payload bytes it sent and received and how many files moved as a delta, and
182 C<filesync log> repeats those figures for past runs.
183  
184 Every message the tools print is looked up in a catalogue
185 (L<App::FileSync::I18N>), so a translation is one new catalogue.
186  
187 This module holds the pieces shared by the client, the server and the admin tools:
188 byte-transparent JSON, path validation, conflict-copy naming and atomic file writes.
189  
190 =head1 FUNCTIONS
191  
192 =head2 json_encode
193  
194 Purpose: encode a structure as one line of canonical JSON.
195  
196 Args: C<$data>, any JSON-encodable value.
197  
198 Returns: the JSON text, keys sorted, with no trailing newline.
199  
200 Side Effects: none.
201  
202 Usage:
203  
204 print {$fh} json_encode($event), "\n";
205  
206 =head3 EXAMPLE
207  
208 print json_encode({ b => 1, a => [ 'x' ] }), "\n"; # {"a":["x"],"b":1}
209  
210 =head3 API SPECIFICATION
211  
212 =head4 INPUT
213  
214 [ { name => 'data', type => 'scalar', optional => 1 } ]
215  
216 =head4 OUTPUT
217  
218 { type => 'string', min => 1 }
219  
220 =head3 MESSAGES
221  
222 The JSON backend's own error for a value it cannot encode (a code reference,
223 say). L<JSON::MaybeXS> chooses the backend: L<Cpanel::JSON::XS>, else
224 L<JSON::XS>, else L<JSON::PP>.
225  
226 =head3 FORMAL SPECIFICATION
227  
228 json_encode : VALUE → TEXT
229 json_decode(json_encode(v)) = v
230  
231 =cut
232  
233 6470 ▶sub json_encode {
Subroutine json_encode: called CC=1 SCAR=0.0
Pod documented
234 6470 my ($data) = @_;
235  
236 6470 return $JSON->encode($data);
237 }
238  
239 =head2 json_decode
240  
241 Purpose: decode one JSON document, keeping strings as byte strings.
242  
243 Args: C<$text>.
244  
245 Returns: the decoded structure. Strings that fit in bytes are downgraded, so a
246 path read back from JSON names the same file as the bytes it was written from.
247  
248 Side Effects: none.
249  
250 Usage:
251  
252 my $config = json_decode(read_text($path));
253  
254 =head3 EXAMPLE
255  
256 my $entry = json_decode('{"p":"caf\u00e9.txt"}');
257 print length($entry->{p}), "\n"; # 8 (bytes), not 9
258  
259 =head3 API SPECIFICATION
260  
261 =head4 INPUT
262  
263 [ { name => 'text', type => 'string' } ]
264  
265 =head4 OUTPUT
266  
267 { type => 'scalar', optional => 1 }
268  
269 =head3 MESSAGES
270  
271 The JSON backend's own error for malformed JSON, so its wording depends on
272 which backend L<JSON::MaybeXS> chose (L<Cpanel::JSON::XS>, else L<JSON::XS>,
273 else L<JSON::PP>).
274  
275 =head3 FORMAL SPECIFICATION
276  
277 json_decode : TEXT ↛ VALUE
278 ∀ s : STRING in result • ¬ utf8_flag(s) ∨ ∃ c ∈ s • ord c > 255
279  
280 =cut
281  
282 6806 ▶sub json_decode {
Subroutine json_decode: called CC=1 SCAR=0.0
Pod documented
283 6806 my ($text) = @_;
284  
285 6806 my $data = $JSON->decode($text);
286 6802 $to_bytes->($data);
287  
288 6802 return $data;
289 }
290  
291 =head2 validate_relpath
292  
293 Purpose: decide whether a path is safe to join to a sync root.
294  
295 Args: C<$path>, a relative path as it travels on the wire.
296  
297 Returns: a two-element list C<(1, undef)> for a usable path, or
298 C<(0, $reason)> where C<$reason> is a translated explanation. (A list rather
299 than a reference because every caller destructures it at once, and it is
300 called once per path in the tree.)
301  
302 Side Effects: none.
303  
304 Usage:
305  
306 my ($ok, $reason) = validate_relpath($path);
307  
308 =head3 EXAMPLE
309  
310 my ($ok, $why) = validate_relpath('notes/../secret');
311 print "$why\n" unless $ok; # parent path component
312  
313 =head3 API SPECIFICATION
314  
315 =head4 INPUT
316  
317 [ { name => 'path', type => 'scalar', optional => 1 } ]
318  
319 =head4 OUTPUT
320  
321 { type => 'arrayref', min => 2, max => 2 }
322  
323 =head3 MESSAGES
324  
325 Key Meaning
326 path.missing no path was given
327 path.not_text the path is a reference
328 path.empty the path is empty
329 path.too_long longer than 4096 bytes
330 path.absolute starts with /
331 path.drive starts with a drive letter
332 path.backslash contains a backslash
333 path.nul contains a NUL byte
334 path.control contains a control character
335 path.empty_component contains //, or starts or ends with /
336 path.dot_component has a . component
337 path.parent_component has a .. component
338 path.component_too_long a component is longer than 255 bytes
339  
340 Resolution: rename the file on the side that holds it.
341  
342 =head3 FORMAL SPECIFICATION
343  
344 SafePath == { p : seq BYTE |
345 0 < #p ≤ 4096 ∧ head p ≠ '/' ∧ ¬ drive(p) ∧
346 '\' ∉ ran p ∧ ran p ∩ CONTROL = ∅ ∧
347 ∀ c : split('/', p) • c ∉ {⟨⟩, ".", ".."} ∧ #c ≤ 255 }
348 validate_relpath(p) = (1, ⊥) if p ∈ SafePath
349 = (0, reason) otherwise
350  
351 =head3 PSEUDOCODE
352  
353 reject undef, references and empty strings
354 reject paths over 4096 bytes
355 reject absolute, drive-relative, backslash, NUL and control characters
356 for each "/"-separated component:
357 reject empty, ".", ".." and components over 255 bytes
358 accept
359  
360 =cut
361  
362 2664 ▶sub validate_relpath {
Subroutine validate_relpath: called CC=18 SCAR=28.9
Pod documented
363 2664 my ($path) = @_;
364  
365 # One key per rejection, checked in order: the first problem found is
366 # the one reported.
367 2664 ▶ my $problem =
Branch: 9 branches
BranchTrueFalseTotal
!defined($path) ? : 1 2663 2664
ref $path ? : 2 2661 2663
!length($path) ? : 1 2660 2661
length $path > $App::FileSync::MAX_PATH_BYTES ? : 1 2659 2660
$path =~ m[\A/] ? : 2 2657 2659
$path =~ /\A[A-Za-z]:/ ? : 1 2656 2657
$path =~ /\\/ ? : 1 2655 2656
$path =~ /\0/ ? : 2 2653 2655
$path =~ /[\x01-\x1f\x7f]/ ? : 2 2651 2653
368 !defined $path ? 'path.missing'
369 : ref $path ? 'path.not_text'
370 : !length $path ? 'path.empty'
371 : length($path) > $MAX_PATH_BYTES ? 'path.too_long'
372 : $path =~ m{\A/} ? 'path.absolute'
373 : $path =~ /\A[A-Za-z]:/ ? 'path.drive'
374 : $path =~ /\\/ ? 'path.backslash'
375 : $path =~ /\0/ ? 'path.nul'
376 : $path =~ /[\x01-\x1f\x7f]/ ? 'path.control'
377 : undef;
378  
379 # Components are only worth checking once the whole path is plausible.
380 2664 ▶ unless (defined $problem) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $problem) 2651 13 2664
381 2651 for my $part (split m{/}, $path, -1) {
382 2940 ▶ $problem =
Branch: 4 branches
BranchTrueFalseTotal
$part eq '' ? : 2 2938 2940
$part eq '.' ? : 1 2937 2938
$part eq '..' ? : 2 2935 2937
length $part > $App::FileSync::MAX_COMPONENT_BYTES ? : 1 2934 2935
383 $part eq '' ? 'path.empty_component'
384 : $part eq '.' ? 'path.dot_component'
385 : $part eq '..' ? 'path.parent_component'
386 : length($part) > $MAX_COMPONENT_BYTES ? 'path.component_too_long'
387 : undef;
388 2940 ▶ last if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 6 2934 2940
389 }
390 }
391  
392 2664 ▶ return defined $problem ? (0, message($problem)) : (1, undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $problem ? : 19 2645 2664
393 }
394  
395 =head2 validate_repo_name
396  
397 Documented with L</validate_client_id> below.
398  
399 =head2 validate_client_id
400  
401 Purpose: decide whether a repo name or client id is usable as a directory name.
402  
403 Args: C<$value>.
404  
405 Returns: C<(1, undef)>, or C<(0, $reason)> with a translated reason. The
406 alphabet is C<[A-Za-z0-9][A-Za-z0-9._-]*>, at most 64 characters.
407  
408 Side Effects: none.
409  
410 Usage:
411  
412 my ($ok, $reason) = validate_client_id($id);
413  
414 =head3 EXAMPLE
415  
416 my ($ok, $why) = validate_repo_name('../etc');
417 print "$why\n"; # bad repo name '../etc'
418  
419 =head3 API SPECIFICATION
420  
421 =head4 INPUT
422  
423 [ { name => 'value', type => 'scalar', optional => 1 } ]
424  
425 =head4 OUTPUT
426  
427 { type => 'arrayref', min => 2, max => 2 }
428  
429 =head3 MESSAGES
430  
431 Key Meaning Resolution
432 id.missing no value was given supply one
433 id.not_text the value is a reference pass a string
434 id.empty the value is empty supply one
435 id.too_long longer than 64 characters shorten it
436 id.bad outside the allowed alphabet use letters, digits, . _ -
437  
438 =head3 FORMAL SPECIFICATION
439  
440 Id == { s : seq CHAR | 0 < #s ≤ 64 ∧ head s ∈ ALNUM ∧ ran s ⊆ ALNUM ∪ {'.','_','-'} }
441 validate(s) = (1, ⊥) if s ∈ Id, (0, reason) otherwise
442  
443 =cut
444  
445 1655 ▶sub validate_repo_name {
Subroutine validate_repo_name: called CC=1 SCAR=0.0
Pod documented
446 1655 my ($value) = @_;
447  
448 1655 return _validate_id('id.repo_name', $value);
449 }
450  
451 869 ▶sub validate_client_id {
Subroutine validate_client_id: called CC=1 SCAR=0.0
Pod documented
452 869 my ($value) = @_;
453  
454 869 return _validate_id('id.client_id', $value);
455 }
456  
457 # _validate_id
458 # Purpose: shared check for repo names and client ids.
459 # Entry: $what_key is the catalogue key naming the kind of id;
460 # $value is the candidate.
461 # Exit: returns (1, undef) or (0, translated reason).
462 # Side effects: none.
463 2524 ▶sub _validate_id :Private {
Subroutine _validate_id: called CC=7 SCAR=19.5
464 2524 my ($what_key, $value) = @_;
465  
466 2524 ▶ my $problem =
Branch: 5 branches
BranchTrueFalseTotal
!defined($value) ? : 1 2523 2524
ref $value ? : 1 2522 2523
!length($value) ? : 2 2520 2522
length $value > $App::FileSync::MAX_ID_LENGTH ? : 2 2518 2520
!($value =~ /$ID_PATTERN/) ? : 13 2505 2518
467 !defined $value ? 'id.missing'
468 : ref $value ? 'id.not_text'
469 : !length $value ? 'id.empty'
470 : length($value) > $MAX_ID_LENGTH ? 'id.too_long'
471 : $value !~ $ID_PATTERN ? 'id.bad'
472 : undef;
473  
474 2524 ▶ return defined $problem
Branch: 1 branch
BranchTrueFalseTotal
defined $problem ? : 19 2505 2524
475 ? (0, message($problem, { what => message($what_key), value => $value }))
476 : (1, undef);
477 435 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
478  
479 =head2 parse_since
480  
481 Purpose: the start of a time window.
482  
483 Args: C<$value> (C<YYYY-MM-DD> or an epoch), optional C<$option> naming the
484 command-line option for the error message (default C<--since>).
485  
486 Returns: the epoch, or C<undef> when C<$value> is undef. A date means
487 midnight UTC that day.
488  
489 Side Effects: none.
490  
491 Usage:
492  
493 my $since = parse_since($opts{since});
494  
495 =head3 EXAMPLE
496  
497 print parse_since('2026-10-22'), "\n"; # 1792627200
498  
499 =head3 API SPECIFICATION
500  
501 =head4 INPUT
502  
503 [
504 { name => 'value', type => 'string', optional => 1 },
505 { name => 'option', type => 'string', optional => 1 },
506 ]
507  
508 =head4 OUTPUT
509  
510 { type => 'integer', optional => 1, min => 0 }
511  
512 =head3 MESSAGES
513  
514 Key Meaning Resolution
515 when.bad neither a date nor an epoch use YYYY-MM-DD or digits
516  
517 =head3 FORMAL SPECIFICATION
518  
519 parse_since : (DATE ∪ ℕ ∪ {⊥}) ↛ ℕ ∪ {⊥}
520 parse_since(n) = n ; parse_since(d) = midnight_utc(d) ; parse_since(⊥) = ⊥
521  
522 =cut
523  
524 34 ▶sub parse_since {
Subroutine parse_since: called CC=2 SCAR=7.0
Pod documented
525 34 my ($value, $option) = @_;
526  
527 34 ▶ my ($epoch) = @{ _parse_when($value, $option || '--since') };
Condition50%1/2
$option || '--since'
l!l
034
MC/DC0%0/1
$option || '--since'
$option
Truth table50%1/2
A
A= $option
Aresult
11
00
528 30 return $epoch;
529 }
530  
531 =head2 parse_until
532  
533 Purpose: the end of a time window.
534  
535 Args: as for L</parse_since> (default option name C<--until>).
536  
537 Returns: the epoch, or C<undef>. A date means the last second of that day, so
538 C<--until 2026-10-22> includes that day's runs.
539  
540 Side Effects: none.
541  
542 Usage:
543  
544 my $until = parse_until($opts{until});
545  
546 =head3 EXAMPLE
547  
548 print parse_until('2026-10-22'), "\n"; # 1792713599
549  
550 =head3 API SPECIFICATION
551  
552 =head4 INPUT
553  
554 [
555 { name => 'value', type => 'string', optional => 1 },
556 { name => 'option', type => 'string', optional => 1 },
557 ]
558  
559 =head4 OUTPUT
560  
561 { type => 'integer', optional => 1, min => 0 }
562  
563 =head3 MESSAGES
564  
565 Key Meaning Resolution
566 when.bad neither a date nor an epoch use YYYY-MM-DD or digits
567  
568 =head3 FORMAL SPECIFICATION
569  
570 parse_until(n) = n ; parse_until(d) = midnight_utc(d) + 86399 ; parse_until(⊥) = ⊥
571  
572 =cut
573  
574 33 ▶sub parse_until {
Subroutine parse_until: called CC=4 SCAR=14.1
Pod documented
575 33 my ($value, $option) = @_;
576  
577 33 ▶ my ($epoch, $is_date) = @{ _parse_when($value, $option || '--until') };
Condition50%1/2
$option || '--until'
l!l
033
MC/DC0%0/1
$option || '--until'
$option
Truth table50%1/2
A
A= $option
Aresult
11
00
578 31 ▶ return (defined $epoch && $is_date) ? $epoch + $SECONDS_PER_DAY - 1 : $epoch;
Branch: 1 branch
BranchTrueFalseTotal
defined $epoch && $is_date ? : 18 13 31
Condition66%2/3
defined $epoch and $is_date
!ll&&!rl&&r
01318
MC/DC50%1/2
defined $epoch and $is_date
defined $epoch $is_date
Truth table66%2/3
A and B
A= defined $epochB= $is_date
ABresult
0X0
100
111
579 }
580  
581 # _parse_when
582 # Purpose: parse "YYYY-MM-DD" or an epoch.
583 # Entry: $value may be undef; $option names the option for errors.
584 # Exit: returns [ $epoch_or_undef, $is_date ]; a date cutoff means a
585 # different instant at each end of a range, hence the flag.
586 # Side effects: raises when.bad for anything else.
587 67 ▶sub _parse_when :Private {
Subroutine _parse_when: called CC=5 SCAR=16.1
588 67 my ($value, $option) = @_;
589  
590 67 ▶ my $parsed =
Branch: 3 branches
BranchTrueFalseTotal
!defined($value) ? : 1 66 67
$value =~ /\A\d+\z/ ? : 36 30 66
$value =~ /\A(\d{4})-(\d{2})-(\d{2})\z/ ? : 24 6 30
591 !defined $value ? [ undef, 0 ]
592 : $value =~ /\A\d+\z/ ? [ $value + 0, 0 ]
593 : $value =~ /\A(\d{4})-(\d{2})-(\d{2})\z/ ? [ Time::Local::timegm(0, 0, 0, $3, $2 - 1, $1), 1 ]
594 : undef;
595  
596 67 ▶ throw('when.bad', { option => $option, value => $value }) unless $parsed;
Branch: 1 branch
BranchTrueFalseTotal
unless $parsed 6 61 67
597 61 return $parsed;
598 435 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
599  
600 =head2 format_utc
601  
602 Purpose: a compact UTC timestamp.
603  
604 Args: optional C<$epoch> (default now).
605  
606 Returns: C<YYYYMMDDTHHMMSSZ>.
607  
608 Side Effects: none.
609  
610 Usage:
611  
612 my $stamp = format_utc($run->{ts});
613  
614 =head3 EXAMPLE
615  
616 print format_utc(0), "\n"; # 19700101T000000Z
617  
618 =head3 API SPECIFICATION
619  
620 =head4 INPUT
621  
622 [ { name => 'epoch', type => 'number', optional => 1 } ]
623  
624 =head4 OUTPUT
625  
626 { type => 'string', matches => qr/\A\d{8}T\d{6}Z\z/ }
627  
628 =head3 MESSAGES
629  
630 None.
631  
632 =head3 FORMAL SPECIFICATION
633  
634 format_utc : ℕ → STAMP
635 format_utc(e) = yyyy mm dd 'T' HH MM SS 'Z' of gmtime(e)
636  
637 =cut
638  
639 228 ▶sub format_utc {
Subroutine format_utc: called CC=2 SCAR=7.2
Pod documented
640 228 my ($epoch) = @_;
641  
642 228 ▶ return strftime($UTC_STAMP, gmtime($epoch // time));
Condition50%1/2
$epoch // time
l!l
2280
MC/DC0%0/1
$epoch // time
$epoch
Truth table50%1/2
A
A= $epoch
Aresult
11
00
643 }
644  
645 =head2 split_name
646  
647 Purpose: split a relative path into directory, stem and extension.
648  
649 Args: C<$path>.
650  
651 Returns: an arrayref C<[ $dir, $stem, $ext ]>; C<$dir> has no trailing slash
652 and is empty at the top level, C<$ext> includes its dot and is empty when there
653 is none. A leading dot (C<.profile>) is part of the stem.
654  
655 Side Effects: none.
656  
657 Usage:
658  
659 my ($dir, $stem, $ext) = @{ split_name('a/b/report.txt') };
660  
661 =head3 EXAMPLE
662  
663 my $parts = split_name('notes/plan.v2.txt'); # ['notes', 'plan.v2', '.txt']
664  
665 =head3 API SPECIFICATION
666  
667 =head4 INPUT
668  
669 [ { name => 'path', type => 'string', min => 1 } ]
670  
671 =head4 OUTPUT
672  
673 { type => 'arrayref', min => 3, max => 3 }
674  
675 =head3 MESSAGES
676  
677 None.
678  
679 =head3 FORMAL SPECIFICATION
680  
681 split_name(p) = (d, s, e) where p = d ⁀ "/" ⁀ s ⁀ e ∨ (d = ⟨⟩ ∧ p = s ⁀ e)
682 e = ⟨⟩ ∨ (head e = '.' ∧ '.' ∉ ran(tail e)) ; s ≠ ⟨⟩
683  
684 =cut
685  
686 92 ▶sub split_name {
Subroutine split_name: called CC=3 SCAR=11.0
Pod documented
687 92 my ($path) = @_;
688  
689 92 ▶ my ($dir, $base) = $path =~ m{\A(.*)/([^/]+)\z} ? ($1, $2) : ('', $path);
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A(.*)/([^/]+)\z] ? : 2 90 92
690 92 ▶ my ($stem, $ext) = $base =~ /\A(.+)(\.[^.]+)\z/ ? ($1, $2) : ($base, '');
Branch: 1 branch
BranchTrueFalseTotal
$base =~ /\A(.+)(\.[^.]+)\z/ ? : 86 6 92
691  
692 92 return [ $dir, $stem, $ext ];
693 }
694  
695 =head2 name_with_suffix
696  
697 Purpose: make a name unique by numbering it before its extension.
698  
699 Args: C<$path>, C<$suffix> (a number).
700  
701 Returns: C<report-2.txt> for C<report.txt> and 2, keeping the directory.
702  
703 Side Effects: none.
704  
705 Usage:
706  
707 my $candidate = name_with_suffix($loser_name, $n);
708  
709 =head3 EXAMPLE
710  
711 print name_with_suffix('a/b.txt', 3), "\n"; # a/b-3.txt
712  
713 =head3 API SPECIFICATION
714  
715 =head4 INPUT
716  
717 [
718 { name => 'path', type => 'string', min => 1 },
719 { name => 'suffix', type => 'integer', min => 1 },
720 ]
721  
722 =head4 OUTPUT
723  
724 { type => 'string', min => 1 }
725  
726 =head3 MESSAGES
727  
728 None.
729  
730 =head3 FORMAL SPECIFICATION
731  
732 let (d, s, e) = split_name(p)
733 name_with_suffix(p, n) = join(d, s ⁀ "-" ⁀ n ⁀ e)
734  
735 =cut
736  
737 0 ▶sub name_with_suffix {
Subroutine name_with_suffix: not called CC=1 SCAR=6.9
Pod documented
738 0 my ($path, $suffix) = @_;
739  
740 0 my ($dir, $stem, $ext) = @{ split_name($path) };
741 0 return _join_dir($dir, "$stem-$suffix$ext");
742 }
743  
744 =head2 conflict_name
745  
746 Purpose: the name a losing version is kept under.
747  
748 Args: C<$path>, C<$client_id> (may be undef), C<$epoch> (default now).
749  
750 Returns: the original name with C<.conflict-CLIENT-TIMESTAMP> inserted before
751 the extension, kept within 200 bytes so it fits common filesystems.
752  
753 Side Effects: none.
754  
755 Usage:
756  
757 my $name = conflict_name('notes.txt', 'laptop-1', time);
758  
759 =head3 EXAMPLE
760  
761 print conflict_name('report.txt', 'laptop-1', 1_792_664_100), "\n";
762 # report.conflict-laptop-1-20261022T101500Z.txt
763  
764 =head3 API SPECIFICATION
765  
766 =head4 INPUT
767  
768 [
769 { name => 'path', type => 'string', min => 1 },
770 { name => 'client_id', type => 'string', optional => 1 },
771 { name => 'epoch', type => 'number', optional => 1 },
772 ]
773  
774 =head4 OUTPUT
775  
776 { type => 'string', min => 1 }
777  
778 =head3 MESSAGES
779  
780 None.
781  
782 =head3 FORMAL SPECIFICATION
783  
784 let (d, s, e) = split_name(p) ; id = sanitise(c) ; t = format_utc(when)
785 let room = max(16, 200 − #(".conflict-" ⁀ id ⁀ "-" ⁀ t ⁀ e))
786 conflict_name(p, c, when) = join(d, s[1..room] ⁀ ".conflict-" ⁀ id ⁀ "-" ⁀ t ⁀ e)
787  
788 =cut
789  
790 92 ▶sub conflict_name {
Subroutine conflict_name: called CC=5 SCAR=16.6
Pod documented
791 92 my ($path, $client_id, $epoch) = @_;
792  
793 92 my ($dir, $stem, $ext) = @{ split_name($path) };
794  
795 # The id lands in a file name, so anything outside the id alphabet is
796 # flattened rather than trusted.
797 92 ▶ my $id = defined $client_id ? $client_id : $UNKNOWN_CLIENT;
Branch: 1 branch
BranchTrueFalseTotal
defined $client_id ? : 92 0 92
798 92 $id =~ s/[^A-Za-z0-9._-]+/_/g;
799 92 ▶ $id = $UNKNOWN_CLIENT unless length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless length $id 0 92 92
800  
801 92 my $tail = ".conflict-$id-" . format_utc($epoch) . $ext;
802  
803 # Keep the whole name inside the 255-byte limit of common filesystems.
804 92 my $room = $CONFLICT_NAME_BYTES - length($tail);
805 92 ▶ $room = $MIN_STEM_BYTES if $room < $MIN_STEM_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
if $room < $MIN_STEM_BYTES 0 92 92
806 92 ▶ $stem = substr($stem, 0, $room) if length($stem) > $room;
Branch: 1 branch
BranchTrueFalseTotal
if length $stem > $room 0 92 92
807  
808 92 return _join_dir($dir, $stem . $tail);
809 }
810  
811 # _join_dir
812 # Purpose: put a relative directory and a name back together.
813 # Entry: $dir may be empty (top level).
814 # Exit: returns "dir/name" or "name".
815 # Side effects: none.
816 92 ▶sub _join_dir :Private {
Subroutine _join_dir: called CC=2 SCAR=6.9
817 92 my ($dir, $name) = @_;
818  
819 92 ▶ return length($dir) ? "$dir/$name" : $name;
Branch: 1 branch
BranchTrueFalseTotal
length $dir ? : 2 90 92
820 435 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
821  
822 =head2 write_atomic
823  
824 Documented with L</set_mtime> below.
825  
826 =head2 read_text
827  
828 Documented with L</set_mtime> below.
829  
830 =head2 set_mtime
831  
832 Re-exported from L<App::FileSync::IO>, where they are documented.
833  
834 =cut
835  
836 435 1;
837  
838 __END__
« blib/lib/App/FileSync/Scan.pm ↑ Summary blib/lib/App/FileSync/Ignore.pm »