App-FileSync
view release on metacpan or search on metacpan
is(read_text($path), 'first', 'missing parents are created and the data written');
write_atomic($path, 'second');
is(read_text($path), 'second', 'an existing file is replaced');
my $parent = File::Basename::dirname($path);
is_deeply([ grep { /\A\Q$CONFIG{temp_prefix}\E/ } @{ list_dir($parent) } ], [], 'no temporary file is left');
covered('IO::write_atomic/1');
# The target is a non-empty directory, which no rename can replace.
my $blocked = File::Spec->catdir($dir, 'blocked');
make_path(File::Spec->catdir($blocked, 'child'));
like(error_of(sub { write_atomic($blocked, 'x') }), qr/\ACannot move \S+ to \Q$blocked\E: \S/, 'io.rename');
is_deeply([ grep { /\A\Q$CONFIG{temp_prefix}\E/ } @{ list_dir($dir) } ], [], '... and the temporary file is removed');
covered('IO::write_atomic/io.rename');
SKIP: {
skip_states("no $CONFIG{dev_full}", 2, 'IO::write_atomic/io.write') unless -c $CONFIG{dev_full};
# A full disk: the temporary file is a handle on /dev/full, whose
# write fails when the buffer is flushed at close.
my $temp = File::Spec->catfile($dir, "$CONFIG{temp_prefix}full");
write_atomic($temp, '');
my $guard = mock_scoped 'App::FileSync::IO::temp_file' => sub {
open my $full, '>', $CONFIG{dev_full} or die "open $CONFIG{dev_full}: $!";
return [ $full, $temp ];
};
like(error_of(sub { write_atomic(File::Spec->catfile($dir, 'never'), 'data') }),
qr/\ACannot write \Q$temp\E: \S/, 'io.write');
ok(!-e $temp, '... and the temporary file is removed');
covered('IO::write_atomic/io.write');
}
SKIP: {
skip_states('permissions are not enforced here', 2, 'IO::write_atomic/io.temp') unless $CAN_DENY;
my $locked = read_only_dir('write-locked');
my $target = File::Spec->catfile($locked, 'file');
like(error_of(sub { write_atomic($target, 'x') }), qr/\ACannot create a temporary file in \Q$locked\E: \S/, 'io.temp');
ok(!-e $target, '... and nothing is written');
covered('IO::write_atomic/io.temp');
chmod $CONFIG{writable}, $locked;
}
};
subtest 'IO::install_file' => sub {
# The temp file takes the mode and mtime, replaces a file or an empty
# directory, and is removed if it cannot be moved into place.
my $dir = tempdir(DIR => $SCRATCH);
my $make_temp = sub {
my ($fh, $temp) = @{ temp_file($dir) };
print {$fh} $_[0];
close $fh;
return $temp;
};
my $target = File::Spec->catfile($dir, 'target');
write_atomic($target, 'old');
my $temp = $make_temp->('new');
my ($got) = keeps_globals('install_file', sub { install_file($temp, $target, $CONFIG{mtime}, $CONFIG{file_mode}) });
is($got, $target, 'returns the target');
returns_ok($got, { type => 'string', min => 1 }, 'a path');
is(read_text($target), 'new', 'the new contents are in place');
ok(!-e $temp, 'the temporary file has gone');
cmp_ok(abs((Time::HiRes::stat($target))[9] - $CONFIG{mtime}), '<', $CONFIG{mtime_slack} + 1, 'the mtime was set');
SKIP: {
skip 'no permission bits on Windows', 1 if $^O eq $CONFIG{win32};
is((stat $target)[2] & $CONFIG{mode_mask}, $CONFIG{file_mode}, 'the mode was set');
}
my $empty_dir = File::Spec->catdir($dir, 'was-a-dir');
make_path($empty_dir);
install_file($make_temp->('file now'), $empty_dir);
is(read_text($empty_dir), 'file now', 'an empty directory is replaced');
covered('IO::install_file/target');
my $full_dir = File::Spec->catdir($dir, 'full-dir');
make_path(File::Spec->catdir($full_dir, 'child'));
is(error_of(sub { install_file($make_temp->('x'), $full_dir) }), "Cannot replace non-empty directory $full_dir", 'io.replace_dir');
ok(-d File::Spec->catdir($full_dir, 'child'), '... and the directory is untouched');
covered('IO::install_file/io.replace_dir');
my $nowhere = File::Spec->catfile($dir, 'no', 'parent');
my $orphan = $make_temp->('x');
like(error_of(sub { install_file($orphan, $nowhere) }), qr/\ACannot move \Q$orphan\E to \Q$nowhere\E: \S/, 'io.rename');
ok(!-e $orphan, '... and the temporary file is removed');
covered('IO::install_file/io.rename');
SKIP: {
skip_states('permissions are not enforced here', 1, 'IO::install_file/io.remove') unless $CAN_DENY;
my $locked = read_only_dir('install-locked');
chmod $CONFIG{writable}, $locked;
my $victim = File::Spec->catfile($locked, 'victim');
write_atomic($victim, 'keep');
chmod $CONFIG{read_only}, $locked;
like(error_of(sub { install_file($make_temp->('x'), $victim) }), qr/\ACannot remove \Q$victim\E: \S/, 'io.remove');
covered('IO::install_file/io.remove');
chmod $CONFIG{writable}, $locked;
}
};
subtest 'IO::clear_target' => sub {
my $dir = tempdir(DIR => $SCRATCH);
my $file = File::Spec->catfile($dir, 'file');
my $empty = File::Spec->catdir($dir, 'empty');
write_atomic($file, 'x');
make_path($empty);
my ($got) = keeps_globals('clear_target', sub { clear_target($file) });
is($got, 1, 'returns 1');
ok(!-e $file, 'a file is removed');
clear_target($empty);
ok(!-e $empty, 'an empty directory is removed');
is(clear_target(File::Spec->catfile($dir, 'absent')), 1, 'nothing there is fine');
SKIP: {
skip 'no symlinks', 2 unless eval { symlink('', ''); 1 } && $^O ne $CONFIG{win32};
my $link = File::Spec->catfile($dir, 'link');
my $pointee = File::Spec->catdir($dir, 'pointee');
make_path(File::Spec->catdir($pointee, 'child'));
symlink $pointee, $link;
clear_target($link);
ok(!-l $link, 'a symlink is removed');
ok(-d File::Spec->catdir($pointee, 'child'), '... not what it points at');
}
covered('IO::clear_target/1');
my $full = File::Spec->catdir($dir, 'full');
make_path(File::Spec->catdir($full, 'child'));
is(error_of(sub { clear_target($full) }), "Cannot replace non-empty directory $full", 'io.replace_dir');
covered('IO::clear_target/io.replace_dir');
SKIP: {
skip_states('permissions are not enforced here', 1, 'IO::clear_target/io.remove') unless $CAN_DENY;
my $locked = read_only_dir('clear-locked');
chmod $CONFIG{writable}, $locked;
my $victim = File::Spec->catfile($locked, 'victim');
write_atomic($victim, 'keep');
chmod $CONFIG{read_only}, $locked;
like(error_of(sub { clear_target($victim) }), qr/\ACannot remove \Q$victim\E: \S/, 'io.remove');
covered('IO::clear_target/io.remove');
chmod $CONFIG{writable}, $locked;
}
};
subtest 'IO::set_mtime' => sub {
my $dir = tempdir(DIR => $SCRATCH);
my $path = File::Spec->catfile($dir, 'file');
write_atomic($path, 'x');
my ($got) = keeps_globals('set_mtime', sub { set_mtime($path, $CONFIG{mtime}) });
is($got, 1, 'returns 1');
cmp_ok(abs((Time::HiRes::stat($path))[9] - $CONFIG{mtime}), '<', $CONFIG{mtime_slack} + 1, 'sub-second mtime set');
covered('IO::set_mtime/1');
my $before = (stat $path)[9];
is(set_mtime($path, undef), 1, 'undef returns 1');
is((stat $path)[9], $before, '... and leaves the file alone');
covered('IO::set_mtime/undef_mtime');
# Where Time::HiRes::utime is unimplemented, whole seconds are stored.
{
my $guard = mock_scoped 'Time::HiRes::utime' => sub { die "Time::HiRes::utime(): unimplemented in this platform\n" };
is(set_mtime($path, $CONFIG{whole_mtime} + 0.7), 1, 'unimplemented: still 1');
}
is((stat $path)[9], $CONFIG{whole_mtime}, '... with whole seconds');
covered('IO::set_mtime/whole_seconds');
my $missing = File::Spec->catfile($dir, 'missing');
like(error_of(sub { set_mtime($missing, $CONFIG{mtime}) }), qr/\ACannot set the modification time of \Q$missing\E: \S/, 'io.utime');
{
my $guard = mock_scoped 'Time::HiRes::utime' => sub { die "something else broke\n" };
is(error_of(sub { set_mtime($path, $CONFIG{mtime}) }), "Cannot set the modification time of $path: something else broke",
'io.utime carries any other failure');
}
covered('IO::set_mtime/io.utime');
};
subtest 'IO::sha256_file' => sub {
my $dir = tempdir(DIR => $SCRATCH);
my $path = File::Spec->catfile($dir, 'file');
write_atomic($path, "abc\r\n");
my ($got) = keeps_globals('sha256_file', sub { sha256_file($path) });
is($got, Digest::SHA::sha256_hex("abc\r\n"), 'the SHA-256 of the bytes');
returns_ok($got, { type => 'string', matches => $CONFIG{sha_hex} }, 'lower-case hex');
covered('IO::sha256_file/hex');
is(sha256_file(File::Spec->catfile($dir, 'missing')), undef, 'a missing file: undef');
is(sha256_file($dir), undef, 'a directory: undef');
SKIP: {
skip 'permissions are not enforced here', 1 unless $CAN_DENY;
my $secret = File::Spec->catfile($dir, 'secret');
write_atomic($secret, 'x');
chmod 0, $secret;
is(sha256_file($secret), undef, 'an unreadable file: undef');
}
covered('IO::sha256_file/undef');
};
subtest 'IO::list_dir' => sub {
my $dir = tempdir(DIR => $SCRATCH);
write_atomic(File::Spec->catfile($dir, $_), '') for qw(b a .hidden);
make_path(File::Spec->catdir($dir, 'c'));
my ($got) = keeps_globals('list_dir', sub { list_dir($dir) });
is_deeply($got, [ '.hidden', 'a', 'b', 'c' ], 'sorted, without . and ..');
returns_ok($got, { type => 'arrayref' }, 'an arrayref');
is_deeply(list_dir(File::Spec->catdir($dir, 'c')), [], 'an empty directory is an empty list');
covered('IO::list_dir/arrayref');
$! = 0;
is(list_dir(File::Spec->catdir($dir, 'missing')), undef, 'a missing directory: undef');
my ($got) = keeps_globals('match', sub { $match->([ '*.tmp' ], 'a.tmp') });
is($got, 1, '* matches a name');
is($match->([ '*.tmp' ], 'deep/er/a.tmp'), 1, 'a slash-less pattern matches at any depth');
is($match->([ 'a?c' ], 'abc'), 1, '? matches one character');
is($match->([ 'docs/**/*.bak' ], 'docs/x/y/z.bak'), 1, '**/ matches several directories');
is($match->([ 'docs/**/*.bak' ], 'docs/z.bak'), 1, '... or none');
is($match->([ 'build/' ], 'src/build'), 1, 'a trailing slash still matches at any depth');
is($match->([ 'cache' ], 'cache/inner/file'), 1, 'a path inside an ignored directory');
is($match->([ '*.TMP' ], 'a.tmp', case_insensitive => 1), 1, 'case-insensitive when asked');
is($match->([ '*', '!keep', 'keep' ], 'keep'), 1, 'later patterns win');
covered('Ignore::match/1');
is($match->([ '*.tmp' ], 'a.txt'), 0, 'no match');
is($match->([ '*.tmp', '!keep.tmp' ], 'keep.tmp'), 0, '! re-includes');
is($match->([ '/top' ], 'sub/top'), 0, 'a leading slash anchors at the root');
is($match->([ '/top' ], 'top'), 1, '... and matches there');
is($match->([ '*.tmp' ], 'dir.tmp/x', ), 1, '(the directory itself matches)');
is($match->([ 'a*b' ], 'a/b'), 0, '* stays within one component');
is($match->([ 'a?b' ], 'a/b'), 0, '? does not match a slash');
is($match->([ '*.TMP' ], 'a.tmp'), 0, 'case-sensitive by default');
is($match->([ 'a.c' ], 'abc'), 0, 'other characters are literal');
is($match->([ '*' ], undef), 0, 'undef is never ignored');
is($match->([ '*' ], ''), 0, 'nor is an empty path');
covered('Ignore::match/0');
};
# ============================================================================
# App::FileSync::Scan
# ============================================================================
# make_tree($root, %files): write each relative path with its contents.
sub make_tree {
my ($root, %files) = @_;
write_atomic(File::Spec->catfile($root, split m{/}, $_), $files{$_}) for keys %files;
return $root;
}
subtest 'Scan::scan' => sub {
my $root = make_tree(tempdir(DIR => $SCRATCH), 'a.txt' => 'alpha', 'sub/b.bin' => "\0\1", 'skip/x.tmp' => 'x');
make_path(File::Spec->catdir($root, 'empty'), File::Spec->catdir($root, 'only-ignored'));
write_atomic(File::Spec->catfile($root, 'only-ignored', 'y.tmp'), 'y');
chmod $CONFIG{file_mode}, File::Spec->catfile($root, 'a.txt');
my $ignore = App::FileSync::Ignore->new(patterns => [ '*.tmp', 'skip' ]);
my ($scan) = keeps_globals('scan', sub { App::FileSync::Scan::scan(root => $root, ignore => $ignore) });
returns_ok($scan, {
type => 'hashref',
schema => {
manifest => { type => 'hashref' },
stats => { type => 'hashref' },
skipped => { type => 'hashref' },
unreadable => { type => 'hashref' },
},
}, 'the documented shape');
my $a = $scan->{manifest}{'a.txt'};
is($a->{t}, 'f', 'a file entry');
is($a->{s}, 5, '... its size');
is($a->{h}, Digest::SHA::sha256_hex('alpha'), '... its hash');
cmp_ok(abs($a->{m} - (Time::HiRes::stat(File::Spec->catfile($root, 'a.txt')))[9]), '<', $CONFIG{mtime_slack}, '... its mtime');
SKIP: {
skip 'no permission bits on Windows', 1 if $^O eq $CONFIG{win32};
is($a->{mode}, $CONFIG{file_mode}, '... and its mode');
}
ok($scan->{manifest}{'sub/b.bin'}, 'paths are relative and slash-separated');
ok(!exists $scan->{manifest}{sub}, 'a directory with files is not an entry');
is_deeply($scan->{stats}, { files => 2, dirs => 2, bytes => 7, hashed => 2, cached => 0, skipped => 0 }, 'the stats');
is_deeply($scan->{skipped}, {}, 'nothing skipped');
is_deeply($scan->{unreadable}, {}, 'nothing unreadable');
covered('Scan::scan/result');
is_deeply($scan->{manifest}{empty}, { t => 'd' }, 'an empty directory is an entry');
is_deeply($scan->{manifest}{'only-ignored'}, { t => 'd' }, 'so is one empty after ignores');
covered('Scan::scan/empty_dir');
ok(!exists $scan->{manifest}{'skip/x.tmp'} && !exists $scan->{manifest}{skip}, 'ignored paths are absent');
covered('Scan::scan/ignored');
# A cache entry whose size and mtime still match is trusted, hash and all.
my %cache = %{ $scan->{manifest} };
$cache{'a.txt'} = { %{$a}, h => 'from-the-cache' };
my $again = App::FileSync::Scan::scan(root => $root, ignore => $ignore, cache => \%cache);
is($again->{manifest}{'a.txt'}{h}, 'from-the-cache', 'a matching cache entry is reused');
is($again->{stats}{cached}, 2, 'counted as cached');
is($again->{stats}{hashed}, 0, 'nothing rehashed');
$cache{'a.txt'} = { %{$a}, h => 'from-the-cache', s => 99 };
is(App::FileSync::Scan::scan(root => $root, ignore => $ignore, cache => \%cache)->{manifest}{'a.txt'}{h},
Digest::SHA::sha256_hex('alpha'), 'a size mismatch rehashes');
covered('Scan::scan/cached');
is(error_of(sub { App::FileSync::Scan::scan() }), "Scan::scan: 'root' is required", 'args.missing');
covered('Scan::scan/args.missing');
};
subtest 'Scan::scan (skipped entries)' => sub {
# Each skip reason from the MESSAGES table, provoked for real where the
# platform allows it. Skipped entries are reported, never raised.
my $root = make_tree(tempdir(DIR => $SCRATCH), 'ok.txt' => 'ok', 'gone.txt' => 'x');
my $denied = $! = 0;
SKIP: {
skip_states('no symlinks on Windows', 1, 'Scan::scan/scan.symlink') if $^O eq $CONFIG{win32};
symlink 'ok.txt', File::Spec->catfile($root, 'link');
my $scan = App::FileSync::Scan::scan(root => $root);
is($scan->{skipped}{link}, 'symbolic link', 'scan.symlink');
covered('Scan::scan/scan.symlink');
unlink File::Spec->catfile($root, 'link');
}
SKIP: {
require POSIX;
my $fifo = File::Spec->catfile($root, 'fifo');
skip_states('no fifos here', 1, 'Scan::scan/scan.special') unless $^O ne $CONFIG{win32} && POSIX::mkfifo($fifo, oct('600'));
my $scan = App::FileSync::Scan::scan(root => $root);
is($scan->{skipped}{fifo}, 'not a regular file', 'scan.special');
ok(!$scan->{unreadable}{fifo}, '... which is not "unreadable"');
covered('Scan::scan/scan.special');
unlink $fifo;
}
my $young = File::Spec->catfile($root, "$CONFIG{temp_prefix}young");
my $other = File::Spec->catfile($root, 'old-but-ordinary');
write_atomic($_, 'x') for $old, $young, $other;
utime $CONFIG{whole_mtime}, $CONFIG{whole_mtime}, $old, $other;
my ($removed) = keeps_globals('clean_stale_temps', sub { App::FileSync::Scan::clean_stale_temps(root => $root) });
is($removed, 1, 'one stale temporary file removed');
returns_ok($removed, { type => 'integer', min => 0 }, 'a count');
ok(!-e $old, 'the old one, below the root');
ok(-e $young, 'a young one may belong to a running sync');
ok(-e $other, 'an ordinary file is never touched');
is(App::FileSync::Scan::clean_stale_temps(root => $root, max_age => 0), 1, 'max_age 0 removes the young one too');
ok(!-e $young, '... it has gone');
covered('Scan::clean_stale_temps/count');
is(App::FileSync::Scan::clean_stale_temps(root => File::Spec->catdir($root, 'missing')), 0, 'a missing root: 0');
is(App::FileSync::Scan::clean_stale_temps(), 0, 'no root: 0');
covered('Scan::clean_stale_temps/no_root');
};
# ============================================================================
# App::FileSync::Verify
# ============================================================================
subtest 'Verify::verify' => sub {
# Record a tree, then change it in each documented way.
my $root = make_tree(tempdir(DIR => $SCRATCH), 'a.txt' => 'alpha', 'b.txt' => 'bravo', 'c.txt' => 'charlie');
make_path(File::Spec->catdir($root, 'dir'));
my $record = App::FileSync::Scan::scan(root => $root)->{manifest};
my $verify = sub { App::FileSync::Verify::verify(root => $root, entries => $record, @_) };
my ($clean) = keeps_globals('verify', sub { $verify->() });
returns_ok($clean, {
type => 'hashref',
schema => {
root => { type => 'string', min => 1 },
ok => { type => 'integer', min => 0, max => 1 },
modified => { type => 'arrayref' },
missing => { type => 'arrayref' },
extra => { type => 'arrayref' },
deep => { type => 'integer', min => 0, max => 1 },
files => { type => 'integer', min => 0 },
known => { type => 'integer', min => 0 },
rehashed => { type => 'integer', min => 0 },
trusted => { type => 'integer', min => 0 },
sampled => { type => 'integer', min => 0 },
},
}, 'the documented shape');
is($clean->{ok}, 1, 'an unchanged tree is ok');
is($clean->{root}, $root, 'root is reported');
is($clean->{files}, 3, 'files found');
is($clean->{known}, 4, 'entries in the record');
is($clean->{trusted}, 3, 'unchanged-looking files are trusted');
is($clean->{rehashed}, 0, '... not rehashed');
is($clean->{deep}, 0, 'not deep');
is($clean->{sampled}, 0, 'nothing sampled');
covered('Verify::verify/ok');
# Same size and mtime, different bytes: only rehashing can see it.
my $b_path = File::Spec->catfile($root, 'b.txt');
my $mtime = (Time::HiRes::stat($b_path))[9];
write_atomic($b_path, 'BRAVO');
set_mtime($b_path, $mtime);
is($verify->()->{ok}, 1, 'a shallow verify trusts size and mtime');
my $deep = $verify->(deep => 1);
is($deep->{ok}, 0, 'deep finds the change');
is($deep->{deep}, 1, 'deep is reported');
is($deep->{rehashed}, 3, 'every file rehashed');
is_deeply($deep->{modified}, [ { p => 'b.txt', expected => Digest::SHA::sha256_hex('bravo'), got => Digest::SHA::sha256_hex('BRAVO') } ],
'modified: path, expected and got');
covered('Verify::verify/deep');
my %only_b = ('b.txt' => $record->{'b.txt'});
my $sampled = App::FileSync::Verify::verify(root => $root, entries => \%only_b, sample => 1);
is($sampled->{sampled}, 1, 'one file sampled');
is_deeply($sampled->{modified}, [ { p => 'b.txt', expected => Digest::SHA::sha256_hex('bravo'), got => Digest::SHA::sha256_hex('BRAVO'), sampled => 1 } ],
'a sampled change is marked as such');
covered('Verify::verify/sampled');
write_atomic(File::Spec->catfile($root, 'a.txt'), 'changed size');
is_deeply($verify->()->{modified}[0]{p}, 'a.txt', 'a size change is rehashed and reported shallowly');
covered('Verify::verify/modified');
rmdir File::Spec->catdir($root, 'dir');
write_atomic(File::Spec->catfile($root, 'dir'), 'now a file');
unlink File::Spec->catfile($root, 'c.txt');
write_atomic(File::Spec->catfile($root, 'z-new.txt'), 'new');
write_atomic(File::Spec->catfile($root, 'y.tmp'), 'ignored');
my $changed = $verify->(ignore => App::FileSync::Ignore->new(patterns => [ '*.tmp' ]));
is($changed->{ok}, 0, 'not ok');
is_deeply([ grep { $_->{p} eq 'dir' } @{ $changed->{modified} } ], [ { p => 'dir', reason => 'type changed' } ], 'verify.type_changed');
covered('Verify::verify/verify.type_changed');
is_deeply($changed->{missing}, [ { p => 'c.txt', t => 'f' } ], 'missing: path and type');
covered('Verify::verify/missing');
is_deeply($changed->{extra}, [ { p => 'z-new.txt', t => 'f' } ], 'extra: path and type, ignored paths left out');
covered('Verify::verify/extra');
is_deeply([ map { $_->{p} } @{ $changed->{modified} } ], [ sort map { $_->{p} } @{ $changed->{modified} } ], 'sorted by path');
my $file = File::Spec->catfile($root, 'a.txt');
is(error_of(sub { App::FileSync::Verify::verify(root => $file) }), "Verify: $file is not a directory", 'verify.no_root');
covered('Verify::verify/verify.no_root');
};
# ============================================================================
# App::FileSync::Merge
# ============================================================================
subtest 'Merge::plan (client)' => sub {
# One path per row of the FORMAL SPECIFICATION table. B, A and M are
# the base, client and master entries.
my $f = sub { { t => 'f', h => $_[0], s => 1, m => $_[1] // 0 } };
my $d = { t => 'd' };
my %base = (
gone => $f->('g'),
del_remote => $f->('r'),
del_local => $f->('l'),
pulled => $f->('p'),
pushed => $f->('u'),
same => $f->('s'),
restore_m => $f->('rm'),
return $real->(@_);
};
my $error = error_of(sub { $move->(src => $undo, rel => 'undo') });
like($error, qr/\ACannot move \Q$undo\E to \S+: No space left on device\z/, 'a failed copy is trash.move');
ok(-f File::Spec->catfile($undo, 'a') && -f File::Spec->catfile($undo, 'b'), '... leaving the source where it was');
ok(!-e File::Spec->catdir($trash, split(m{/}, $TRASH{bucket_one}), 'undo'), '... and undoing the partial copy');
covered('Trash::move_to_trash/undone');
}
my $missing = File::Spec->catfile($tree, 'missing');
like(error_of(sub { $move->(src => $missing, rel => 'missing') }), qr/\ACannot move \Q$missing\E to \S+: \S/, 'trash.move');
covered('Trash::move_to_trash/trash.move');
my $blocker = File::Spec->catfile($base, 'blocker');
write_atomic($blocker, '');
like(error_of(sub { App::FileSync::Trash::move_to_trash(src => $src, rel => 'x/y', root => $blocker) }),
qr/\ACannot create directory \S+: \S/, 'io.mkdir');
covered('Trash::move_to_trash/io.mkdir');
is(error_of(sub { $move->(src => $src, rel => '../escape') }), "Unsafe path '../escape': parent path component", 'path.unsafe');
is(error_of(sub { $move->(src => $src, rel => '/abs') }), "Unsafe path '/abs': absolute path", 'an absolute rel');
covered('Trash::move_to_trash/path.unsafe');
};
subtest 'Trash::versions, date_of and version_info' => sub {
my $trash = File::Spec->catdir(tempdir(DIR => $SCRATCH), 'trash');
my $tree = tempdir(DIR => $SCRATCH);
my $src = File::Spec->catfile($tree, 'r.txt');
my @stored;
for my $epoch ($TRASH{day_one}, $TRASH{day_one}, $TRASH{day_two}) {
write_atomic($src, "at $epoch");
push @stored, App::FileSync::Trash::move_to_trash(src => $src, rel => 'docs/r.txt', root => $trash, epoch => $epoch);
}
my ($versions) = keeps_globals('versions', sub { App::FileSync::Trash::versions(root => $trash, rel => 'docs/r.txt') });
is_deeply($versions, [ $stored[2], $stored[1], $stored[0] ], 'newest first: by day, then .1 before the first deletion');
returns_ok($versions, { type => 'arrayref' }, 'an arrayref');
covered('Trash::versions/newest_first');
is_deeply(App::FileSync::Trash::versions(root => $trash, rel => 'docs/other.txt'), [], 'a path never trashed: empty');
is_deeply(App::FileSync::Trash::versions(root => File::Spec->catdir($trash, 'none'), rel => 'x'), [], 'no trash at all: empty');
is_deeply(App::FileSync::Trash::versions(rel => 'x'), [], 'no root: empty');
covered('Trash::versions/none');
is(error_of(sub { App::FileSync::Trash::versions(root => $trash) }), "Trash::versions: 'rel' is required", 'args.missing');
covered('Trash::versions/args.missing');
is(error_of(sub { App::FileSync::Trash::versions(root => $trash, rel => 'a/../../etc') }),
"Unsafe path 'a/../../etc': parent path component", 'path.unsafe');
covered('Trash::versions/path.unsafe');
my ($date) = keeps_globals('date_of', sub { App::FileSync::Trash::date_of($stored[0]) });
is($date, $TRASH{date_one}, 'date_of: the day bucket');
is(App::FileSync::Trash::date_of('C:\\trash\\2026\\10\\23\\r.txt'), $TRASH{date_two}, 'backslashes are understood');
returns_ok($date, { type => 'string', matches => qr/\A\d{4}-\d{2}-\d{2}\z/ }, 'YYYY-MM-DD');
covered('Trash::date_of/date');
is(App::FileSync::Trash::date_of('/not/a/bucket'), undef, 'outside a bucket: undef');
is(App::FileSync::Trash::date_of(undef), undef, 'undef: undef');
covered('Trash::date_of/undef');
my ($info) = keeps_globals('version_info', sub { App::FileSync::Trash::version_info($stored[2]) });
is_deeply($info, { path => $stored[2], date => $TRASH{date_two}, size => length("at $TRASH{day_two}"),
mtime => (Time::HiRes::stat($stored[2]))[9] }, 'path, date, size and mtime');
covered('Trash::version_info/info');
unlink $stored[2];
is_deeply(App::FileSync::Trash::version_info($stored[2]), { path => $stored[2], date => $TRASH{date_two}, size => undef, mtime => undef },
'a version that has gone: no size or mtime');
covered('Trash::version_info/gone');
};
subtest 'Trash::prune' => sub {
my $trash = File::Spec->catdir(tempdir(DIR => $SCRATCH), 'trash');
my $old = File::Spec->catdir($trash, '2026', '01', '01');
my $new = File::Spec->catdir($trash, '2026', '10', '22');
write_atomic(File::Spec->catfile($_, 'f'), 'x') for $old, $new;
make_path(File::Spec->catdir($trash, 'not-a-year'));
my $now = $TRASH{day_one};
my ($dry) = keeps_globals('prune', sub { App::FileSync::Trash::prune(root => $trash, now => $now, dry_run => 1) });
is_deeply($dry, [ $old ], 'dry run: what would go');
ok(-d $old, '... and nothing goes');
covered('Trash::prune/dry_run');
is_deeply(App::FileSync::Trash::prune(root => $trash, now => $now), [ $old ], 'buckets older than 30 days are removed');
ok(!-e $old && -d $new, '... only those');
ok(-d File::Spec->catdir($trash, 'not-a-year'), 'other names are left alone');
is_deeply(App::FileSync::Trash::prune(root => $trash, now => $now + 365 * 86_400, days => 400), [], 'a longer retention keeps it');
returns_ok($dry, { type => 'arrayref' }, 'an arrayref');
covered('Trash::prune/removed');
is_deeply(App::FileSync::Trash::prune(root => $trash, now => $now * 2, days => 0), [], 'days 0 disables pruning');
is_deeply(App::FileSync::Trash::prune(root => $trash, now => $now * 2, days => -1), [], 'negative days too');
is_deeply(App::FileSync::Trash::prune(root => File::Spec->catdir($trash, 'missing')), [], 'a missing root: nothing');
is_deeply(App::FileSync::Trash::prune(), [], 'no root: nothing');
ok(-d $new, 'nothing was removed');
covered('Trash::prune/disabled');
SKIP: {
skip_states('permissions are not enforced here', 2, 'Trash::prune/unremovable') unless $CAN_DENY;
my $month = File::Spec->catdir($trash, '2026', '10');
chmod $CONFIG{read_only}, $month;
is_deeply(App::FileSync::Trash::prune(root => $trash, now => $now + 100 * 86_400), [], 'a bucket that cannot be removed is not reported');
ok(-d $new, '... and is left');
chmod $CONFIG{writable}, $month;
covered('Trash::prune/unremovable');
}
};
subtest 'Trash::restore' => sub {
my $base = tempdir(DIR => $SCRATCH);
my $trash = File::Spec->catdir($base, 'trash');
my $tree = make_tree(File::Spec->catdir($base, 'tree'), 'f.txt' => 'file', 'd/g' => 'g', 'd/e/h' => 'h');
utime $CONFIG{whole_mtime}, $CONFIG{whole_mtime}, File::Spec->catfile($tree, 'f.txt');
my $file = App::FileSync::Trash::move_to_trash(src => File::Spec->catfile($tree, 'f.txt'), rel => 'f.txt', root => $trash);
my $dir = App::FileSync::Trash::move_to_trash(src => File::Spec->catdir($tree, 'd'), rel => 'd', root => $trash);
my $to = File::Spec->catfile($base, 'out', 'f.txt');
my ($got) = keeps_globals('restore', sub { App::FileSync::Trash::restore(src => $file, to => $to) });
is($got, $to, 'returns the destination');
is(read_text($to), 'file', 'the file is copied out');
is((stat $to)[9], $CONFIG{whole_mtime}, '... with its mtime');
ok(-f $file, 'the trash entry is left in place');
my $again = File::Spec->catfile($base, 'out', 'again.txt');
is_deeply($all, [ @events[0, 1, 3, 2] ], 'every event, oldest first, from every month');
covered('Admin::journal_read/events');
is(scalar(grep { ($_->{ts} || 0) == 9 } @{$all}), 0, 'a torn final line is skipped');
covered('Admin::journal_read/torn_line');
is_deeply($admin->journal_read(repo => 'docs', client => 'a'), [ @events[0, 2] ], 'client');
is_deeply($admin->journal_read(repo => 'docs', since => '2026-10-22'), [ @events[1, 3, 2] ], 'since a date: from midnight');
is_deeply($admin->journal_read(repo => 'docs', until => '2026-10-22'), [ @events[0, 1, 3] ], 'until a date: to its last second');
is_deeply($admin->journal_read(repo => 'docs', since => $CONFIG{day_epoch} + 10, until => $CONFIG{day_epoch} + 10), [ $events[1] ],
'epochs, inclusive');
is_deeply($admin->journal_read(repo => 'docs', exits => [ 1, 3 ]), [ @events[1, 2] ], 'exits');
is_deeply($admin->journal_read(repo => 'docs', warnings => 1), [ $events[1] ], 'warnings: sessions with conflict copies');
is_deeply($admin->journal_read(repo => 'docs', limit => 2), [ @events[3, 2] ], 'limit: the newest N');
covered('Admin::journal_read/filters');
is(error_of(sub { $admin->journal_read(repo => 'docs', since => 'soon') }), "Bad --since 'soon' (use YYYY-MM-DD or an epoch)", 'when.bad');
is(error_of(sub { $admin->journal_read(repo => 'docs', until => 'later') }), "Bad --until 'later' (use YYYY-MM-DD or an epoch)", '... for until');
covered('Admin::journal_read/when.bad');
SKIP: {
skip_states('permissions are not enforced here', 1, 'Admin::journal_read/io.read') unless $CAN_DENY;
my $file = File::Spec->catfile($dir, '2026-11.jsonl');
chmod 0, $file;
like(error_of(sub { $admin->journal_read(repo => 'docs') }), qr/\ACannot read \Q$file\E: \S/, 'io.read');
covered('Admin::journal_read/io.read');
chmod $CONFIG{file_mode}, $file;
}
};
subtest 'Admin::verify and reindex' => sub {
my $admin = new_admin();
my $root = $admin->root;
my $master = $admin->repo_create(name => 'docs')->{master};
write_atomic(File::Spec->catfile($master, $_), $_) for 'a.txt', 'b.txt';
my ($dry) = keeps_globals('reindex', sub { $admin->reindex(repo => 'docs', dry_run => 1) });
my $store = App::FileSync::Store->new(root => $root, repo => 'docs');
is_deeply([ @{$dry}{qw(repo master index files dirs bytes dry_run written)} ], [ 'docs', $master, $store->index_path, 2, 0, 10, 1, 0 ],
'dry run: repo, master, index, counts, nothing written');
is_deeply($store->load_index, {}, '... the index is untouched');
covered('Admin::reindex/dry_run');
my $before = $admin->verify(repo => 'docs');
is_deeply([ map { $_->{p} } @{ $before->{extra} } ], [ 'a.txt', 'b.txt' ], 'verify: files the index lacks are extra');
is($before->{ok}, 0, '... so not ok');
my $done = $admin->reindex(repo => 'docs');
is_deeply([ @{$done}{qw(files dry_run written)} ], [ 2, 0, 1 ], 'reindex writes the index');
is_deeply($done->{skipped}, {}, '... with nothing skipped');
is_deeply([ sort keys %{ $store->load_index } ], [ 'a.txt', 'b.txt' ], '... describing the tree');
my ($event) = grep { ($_->{action} || '') eq 'reindex' } @{ $admin->journal_read(repo => 'docs') };
is_deeply([ @{$event}{qw(files result)} ], [ 2, 'ok' ], '... and journals it');
covered('Admin::reindex/written');
my ($report) = keeps_globals('verify', sub { $admin->verify(repo => 'docs') });
is($report->{ok}, 1, 'verify: the master now agrees with its index');
is_deeply([ @{$report}{qw(repo master)} ], [ 'docs', $master ], '... with repo and master added');
my $logged = (grep { $_->[0] eq 'debug' && $_->[1] eq 'verify finished' } @{ $admin->{logger}{lines} })[-1];
is_deeply($logged->[2], { repo => 'docs', files => 2, modified => 0, missing => 0, extra => 0, ok => 1 }, '... and logs a debug summary');
my $path = File::Spec->catfile($master, 'a.txt');
my $mtime = (Time::HiRes::stat($path))[9];
write_atomic($path, 'A.TXT');
set_mtime($path, $mtime);
is($admin->verify(repo => 'docs')->{ok}, 1, 'a shallow verify trusts size and mtime');
is($admin->verify(repo => 'docs', deep => 1)->{modified}[0]{p}, 'a.txt', 'deep rehashes');
is($admin->verify(repo => 'docs', sample => 5)->{sampled}, 2, 'sample');
covered('Admin::verify/report');
is(error_of(sub { $admin->verify(repo => 'nope') }), "No such repo 'nope' under $root (run filesync-admin repo create)", 'verify: config.no_repo');
covered('Admin::verify/config.no_repo');
is(error_of(sub { $admin->reindex(repo => 'nope') }), "No such repo 'nope' under $root (run filesync-admin repo create)", 'reindex: config.no_repo');
covered('Admin::reindex/config.no_repo');
my $lock = $store->acquire_lock;
is(error_of(sub { $admin->reindex(repo => 'docs') }), "Another sync session holds the lock for repo 'docs'", 'admin.locked');
covered('Admin::reindex/admin.locked');
close $lock;
};
subtest 'Admin::restore' => sub {
my $admin = new_admin();
my $root = $admin->root;
my $master = $admin->repo_create(name => 'docs')->{master};
my $store = App::FileSync::Store->new(root => $root, repo => 'docs');
for my $day (0, 1) {
write_atomic(File::Spec->catfile($master, 'notes', 'n.txt'), "day $day");
$store->move_to_trash('notes/n.txt', $CONFIG{day_epoch} + $day * 86_400);
}
my ($listed) = keeps_globals('restore list', sub { $admin->restore(repo => 'docs', path => 'notes/n.txt', list => 1) });
is_deeply([ map { $_->{date} } @{ $listed->{versions} } ], [ '2026-10-23', '2026-10-22' ], 'list: the versions, newest first');
is_deeply([ @{$listed}{qw(repo path)} ], [ 'docs', 'notes/n.txt' ], '... with repo and path');
ok(defined $listed->{versions}[0]{size}, '... as version_info rows');
covered('Admin::restore/list');
my $out = tempdir(DIR => $SCRATCH);
my $export = $admin->restore(repo => 'docs', path => 'notes/n.txt', to => $out, date => '2026-10-22');
my $exported = File::Spec->catfile($out, 'notes', 'n.txt');
is_deeply($export, { repo => 'docs', path => 'notes/n.txt', to => $exported, from => $listed->{versions}[1]{path}, date => '2026-10-22',
sha256 => Digest::SHA::sha256_hex('day 0'), into_master => 0 }, 'an export: the chosen day, copied under to');
is(read_text($exported), 'day 0', '... with that day\'s contents');
covered('Admin::restore/export');
my ($back) = keeps_globals('restore', sub { $admin->restore(repo => 'docs', path => 'notes/n.txt') });
is($back->{into_master}, 1, 'by default, into the master');
is($back->{date}, '2026-10-23', '... the newest version');
is(read_text(File::Spec->catfile($master, 'notes', 'n.txt')), 'day 1', '... in place');
ok($store->load_index->{'notes/n.txt'}, '... and the index is rebuilt');
ok(-e $listed->{versions}[0]{path}, 'the trash entry is kept');
my @restores = grep { ($_->{action} || '') eq 'restore' } @{ $admin->journal_read(repo => 'docs') };
is(scalar @restores, 2, 'each restore is journalled');
covered('Admin::restore/into_master');
is(error_of(sub { $admin->restore(repo => 'docs', path => '../x') }), "Unsafe path '../x': parent path component", 'admin.unsafe_path');
is(error_of(sub { $admin->restore(repo => 'docs') }), "Unsafe path '': missing path", 'no path');
covered('Admin::restore/admin.unsafe_path');
is(error_of(sub { $admin->restore(repo => 'docs', path => 'never.txt') }), "No trashed version of 'never.txt' in repo 'docs'", 'admin.no_versions');
covered('Admin::restore/admin.no_versions');
is(error_of(sub { $admin->restore(repo => 'docs', path => 'notes/n.txt', date => '22/10/2026') }),
"Bad --date '22/10/2026' (want YYYY-MM-DD)", 'admin.bad_date');
covered('Admin::restore/admin.bad_date');
( run in 1.929 second using v1.01-cache-2.11-cpan-eb134014566 )