App-FileSync

 view release on metacpan or  search on metacpan

lib/App/FileSync/Client.pm  view on Meta::CPAN

	my ($self, $connection, $action) = @_;

	my $path = $action->{p};
	my $abs  = $self->_abs($path);

	if (($action->{t} || $TYPE_FILE) eq $TYPE_DIR) {
		$self->_request($connection, { cmd => 'mkdir', p => $path }, 'client.req.mkdir', { path => $path });
		return 1;
	}

	my @stat = Time::HiRes::stat($abs);
	$self->_throw('client.cannot_stat', { path => $abs, error => os_error() }) unless @stat;
	my %file = (s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK);

	return 1 if !$action->{loser_name} && $self->_push_delta($connection, $path, $abs, \%file, $action->{h});

	my $in = open_file($abs, '<:raw');

	# The server acknowledges the header before any chunk is sent; reading it
	# here keeps the lock-step protocol aligned.
	$self->_request($connection, {

lib/App/FileSync/Client.pm  view on Meta::CPAN

#              Without a scan (a caller outside a session) there is nothing
#              to compare against, so it returns 1.
# Side effects: raises client.changed_during_sync otherwise.  The next sync
#              scans again and plans the change (as a conflict, if the master
#              changed too).  An edit that keeps both size and mtime is not
#              seen.
sub _assert_unchanged :Private {
	my ($self, $path, $abs) = @_;

	return 1 unless $self->{scanned};
	my @now = Time::HiRes::lstat($abs);
	return 1 if !@now || -d _ || exists $self->{skipped}{$path};

	my $seen = $self->{scanned}{$path};
	return 1 if $seen && ($seen->{t} || '') eq $TYPE_FILE
		&& $now[$STAT_SIZE] == $seen->{s} && $now[$STAT_MTIME] == $seen->{m};

	$self->_throw('client.changed_during_sync', { path => $path });
}

# _delete_local

lib/App/FileSync/Constants.pm  view on Meta::CPAN


# Session roles.  A replica only ever pulls.
Readonly::Scalar our $ROLE_CLIENT  => 'client';
Readonly::Scalar our $ROLE_REPLICA => 'replica';
Readonly our @ROLES        => ($ROLE_CLIENT, $ROLE_REPLICA);

# Manifest entry types.
Readonly::Scalar our $TYPE_FILE => 'f';
Readonly::Scalar our $TYPE_DIR  => 'd';

# Fields of the list stat() and lstat() return.
Readonly::Scalar our $STAT_MODE  => 2;
Readonly::Scalar our $STAT_SIZE  => 7;
Readonly::Scalar our $STAT_MTIME => 9;

# Permission bits worth carrying between machines, and the mode a file gets
# when the peer did not send one.  Setuid and setgid (04000, 02000) are left
# out: a client could otherwise push a set-id program that every other client
# then installs with those bits.  The sticky bit (01000) is kept.
Readonly::Scalar our $MODE_MASK         => oct('1777');
Readonly::Scalar our $DEFAULT_FILE_MODE => oct('644');

lib/App/FileSync/Constants.pm  view on Meta::CPAN

=head1 SYNOPSIS

	use App::FileSync::Constants qw($EXIT_LOCKED $ROLE_REPLICA);

	exit $EXIT_LOCKED if $locked;

=head1 DESCRIPTION

Read-only values (L<Readonly>) shared by the client, server and admin tools:
exit codes, the protocol version, reserved file names, the fields of
C<stat()>, policy defaults and size limits.  Import them by name, or all of
them with C<:all>.

=head1 EXIT CODES

	$EXIT_OK        0  success
	$EXIT_FATAL     1  the run failed
	$EXIT_LOCKED    2  another run holds the lock (temporary, not a failure)
	$EXIT_WARNINGS  3  completed, with warnings or conflict copies
	$EXIT_DRIFT     4  verify found the tree differs from its record

lib/App/FileSync/IO.pm  view on Meta::CPAN


	ΔFS
	src?, dst? : PATH
	FS'(dst?) = FS(src?) ∧ mtime'(dst?) = mtime(src?) ∧ mode'(dst?) = mode(src?)

=cut

sub copy_preserving {
	my ($source, $destination, $stat) = @_;

	$stat = [ Time::HiRes::stat($source) ] unless ref($stat) eq 'ARRAY' && @{$stat};
	ensure_dir(dirname($destination));

	File::Copy::copy($source, $destination)
		or throw('io.copy', { from => $source, to => $destination, error => "$!" });

	chmod($stat->[$STAT_MODE] & $MODE_MASK, $destination) if $HAS_MODES;
	utime($stat->[$STAT_MTIME], $stat->[$STAT_MTIME], $destination);

	return 1;
}

lib/App/FileSync/Scan.pm  view on Meta::CPAN

			# Digest::SHA croaks with its own location; people see the reason only.
			$context->{skipped}{$rel} = message('scan.unreadable', { error => strip_location($@) });
			$context->{unreadable}{$rel} = 1;
			$context->{stats}{skipped}++;
			return undef;	## no critic (Subroutines::ProhibitExplicitReturnUndef)
		}
		# A writer between the lstat and the read would pair the old size and
		# mtime with the new contents' hash, an entry no upload can satisfy.
		# Such a file is unknown this run, like an unreadable one: neither
		# pushed nor taken for a deletion.
		my @after = Time::HiRes::lstat($abs);
		unless (@after && $after[$STAT_SIZE] == $size && $after[$STAT_MTIME] == $mtime) {
			$context->{skipped}{$rel} = message('scan.changed');
			$context->{unreadable}{$rel} = 1;
			$context->{stats}{skipped}++;
			return undef;	## no critic (Subroutines::ProhibitExplicitReturnUndef)
		}
		$hash = $sha->hexdigest;
		$context->{stats}{hashed}++;
	}

lib/App/FileSync/Scan.pm  view on Meta::CPAN

	my $now = Time::HiRes::time();
	my $removed = 0;

	# Breadth first with an explicit queue: no recursion depth limit, and
	# symlinked directories are never followed because lstat says what they are.
	my @queue = ($root);
	while (@queue) {
		my $dir = shift @queue;
		for my $name (@{ list_dir($dir) || [] }) {
			my $path = File::Spec->catfile($dir, $name);
			my @stat = Time::HiRes::lstat($path) or next;
			if (-d _) {
				push @queue, $path;
			} elsif ($name =~ $TEMP_NAME && $now - $stat[$STAT_MTIME] >= $max_age) {
				no autodie qw(unlink);
				$removed++ if unlink $path;
			}
		}
	}

	return $removed;

lib/App/FileSync/Scan.pm  view on Meta::CPAN

		_skip($context, length $rel ? $rel : '.', 'scan.cannot_list', os_error());
		return undef;	## no critic (Subroutines::ProhibitExplicitReturnUndef)
	}

	my $entries = 0;
	for my $name (@{$names}) {
		my $child_rel = length $rel ? "$rel/$name" : $name;
		next if $context->{ignore} && $context->{ignore}->match($child_rel);

		my $child_abs = File::Spec->catfile($abs, $name);
		my @stat = Time::HiRes::lstat($child_abs);
		if (!@stat) {
			_skip($context, $child_rel, 'scan.cannot_stat', os_error());
		} elsif (-d _) {
			# An empty directory is worth syncing; a non-empty one is implied
			# by the files inside it.  One that cannot be listed is neither:
			# recording it as empty would describe its files as deleted.
			$entries++;
			my $inside = _walk($context, $child_abs, $child_rel);
			if (defined $inside && $inside == 0) {
				$context->{manifest}{$child_rel} = { t => $TYPE_DIR };

lib/App/FileSync/Server.pm  view on Meta::CPAN

	my ($self, $message) = @_;

	my $path = $message->{p};
	$self->_expect('read', $path);

	my $offset = $self->_uint($message, 'off', 0);
	my $max    = $self->_uint($message, 'max', $CHUNK);
	$max = $MAX_CHUNK_BYTES if $max > $MAX_CHUNK_BYTES;

	my $abs = $self->{store}->abs_path($path);
	my $file = $self->_file_stat($abs, $path);
	$self->_throw('server.bad_field', { field => 'off', path => $path }) if $offset > $file->{s};

	my $length = $file->{s} - $offset;
	$length = $max if $length > $max;

	my $bytes = '';
	if ($length > 0) {
		my $fh = App::FileSync::IO::open_file($abs, '<:raw');
		seek($fh, $offset, 0);
		$bytes = App::FileSync::Delta::read_exact($fh, $length, $abs);

lib/App/FileSync/Server.pm  view on Meta::CPAN

	$self->_expect('pull', $path);

	my $count = $self->_uint($message, 'n');
	my $block = $self->_uint($message, 'b');
	$self->_throw('server.bad_signature', { path => $path })
		unless $count <= $MAX_SIGNATURE_BLOCKS && $block >= $MIN_SIGNATURE_BLOCK && $block <= $MAX_SIGNATURE_BLOCK;

	my $blocks = App::FileSync::Delta::decode_signature($self->{conn}->read_data($message), $count);

	my $abs = $self->{store}->abs_path($path);
	my $file = $self->_file_stat($abs, $path);
	return $self->_reply({ ok => 1, delta => 0 }) if $file->{s} < $App::FileSync::Delta::MIN_SIZE;

	my $spool = File::Temp->new(UNLINK => 1);
	binmode $spool;
	my $stats = App::FileSync::Delta::diff($abs, { blocklen => $block, blocks => $blocks }, $spool);
	$spool->flush();

	# Only the literal bytes and record headers go on the wire; compression can
	# shrink them further, so this is a conservative estimate.
	my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;

lib/App/FileSync/Server.pm  view on Meta::CPAN

# _file_stat
# Purpose:     size, mtime and mode of a master file the client is reading.
# Entry:       $abs is inside the master.
# Exit:        returns { s, m, mode }.
# Side effects: raises server.cannot_stat or server.not_file.
sub _file_stat :Private {
	my ($self, $abs, $path) = @_;

	# lstat: Scan never lists a symlink, but one can appear between the plan
	# and the read, and following it would send a file outside the master.
	my @stat = Time::HiRes::lstat($abs);
	$self->_throw('server.cannot_stat', { path => $path, error => os_error() }) unless @stat;
	$self->_throw('server.not_file', { path => $path }) unless -f _;
	return { s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK };
}

# _uint
# Purpose:     read an unsigned integer field from a client message.
# Entry:       $default is used when the field is absent; without one the
#              field is required.
# Exit:        returns the number.

lib/App/FileSync/Snapshot.pm  view on Meta::CPAN


	my $names = list_dir($src) or throw('snapshot.read', { path => $src, error => os_error() });

	for my $name (@{$names}) {
		# The snapshots, the root marker and temporaries are bookkeeping, not
		# content; anything else, even a name starting ".filesync-", is data.
		next if $name eq $SNAPSHOT_DIR || $name =~ $TEMP_FILE || ($at_root && $name eq $ROOT_MARKER);

		my $from = File::Spec->catfile($src, $name);
		my $to   = File::Spec->catfile($dst, $name);
		my @stat = Time::HiRes::lstat($from) or next;

		if (-d _) {
			ensure_dir($to);
			_mirror($from, $to, $mode, $counts, 0);
			chmod($stat[$STAT_MODE] & $MODE_MASK, $to) if $HAS_MODES;
		} elsif (-f _) {
			# A link shares the inode, so mode and mtime are already right;
			# a copy (or a failed link across filesystems) needs them set.
			my $linked = $mode eq $HARDLINK && do { no autodie qw(link); link($from, $to) };
			copy_preserving($from, $to, \@stat) unless $linked;

lib/App/FileSync/Snapshot.pm  view on Meta::CPAN

# Entry:       $dir is the snapshot directory.
# Exit:        returns 1.
# Side effects: removes .tmp-PID-N directories older than an hour; younger
#              ones may belong to a concurrent run.
sub _clean_stale_temps :Private {
	my ($dir) = @_;

	my $now = time;
	for my $name (grep { $_ =~ $TEMP_DIR } @{ list_dir($dir) || [] }) {
		my $path = File::Spec->catdir($dir, $name);
		my @stat = Time::HiRes::lstat($path);
		next unless @stat && -d _ && $now - $stat[$STAT_MTIME] >= $STALE_TEMP_SECONDS;
		eval { remove_tree($path) };
	}

	return 1;
}

# _count
# Purpose:     count the regular files and bytes in a snapshot.
# Entry:       $dir exists.
# Exit:        returns 1.
# Side effects: adds to $counts->{files} and {bytes}.
sub _count :Private {
	my ($dir, $counts) = @_;

	for my $name (@{ list_dir($dir) || [] }) {
		my $path = File::Spec->catfile($dir, $name);
		my @stat = Time::HiRes::lstat($path) or next;
		if (-d _) {
			_count($path, $counts);
		} elsif (-f _) {
			$counts->{files}++;
			$counts->{bytes} += $stat[$STAT_SIZE];
		}
	}

	return 1;
}

lib/App/FileSync/Snapshot.pm  view on Meta::CPAN

}

# _copy_out
# Purpose:     copy a snapshot entry to its destination, replacing it.
# Entry:       $src exists in the snapshot.
# Exit:        returns 1.
# Side effects: replaces $dst (unless $dry_run); updates $counts.
sub _copy_out :Private {
	my ($src, $dst, $counts, $dry_run) = @_;

	my @stat = Time::HiRes::lstat($src);
	throw('snapshot.cannot_stat', { path => $src, error => os_error() }) unless @stat;

	if (-d _) {
		ensure_dir($dst) unless $dry_run;
		_copy_out(File::Spec->catfile($src, $_), File::Spec->catfile($dst, $_), $counts, $dry_run)
			for @{ list_dir($src) || [] };

		# Directory metadata last: filling it changed its mtime.
		unless ($dry_run) {
			chmod($stat[$STAT_MODE] & $MODE_MASK, $dst) if $HAS_MODES;

lib/App/FileSync/Trash.pm  view on Meta::CPAN

=head3 FORMAL SPECIFICATION

	version_info(p) = ⟨path ↦ p, date ↦ date_of(p), size ↦ size(FS(p)), mtime ↦ mtime(FS(p))⟩

=cut

sub version_info {
	my ($path) = @_;

	# A listing races with prune, so a vanished version is reported, not fatal.
	my @stat = Time::HiRes::stat($path);
	return {
		path  => $path,
		date  => date_of($path),
		size  => @stat ? $stat[$STAT_SIZE] : undef,
		mtime => @stat ? $stat[$STAT_MTIME] : undef,
	};
}

# _bucket
# Purpose:     the day directory for an epoch.

lib/App/FileSync/Trash.pm  view on Meta::CPAN

}

# _restore_entry
# Purpose:     copy a trashed file or directory tree out of the trash.
# Entry:       $src exists; $to does not (or is a directory being filled).
# Exit:        returns 1.
# Side effects: creates $to; raises trash.cannot_stat or trash.not_regular.
sub _restore_entry :Private {
	my ($src, $to) = @_;

	my @stat = Time::HiRes::lstat($src);
	throw('trash.cannot_stat', { path => $src, error => os_error() }) unless @stat;

	if (-d _) {
		ensure_dir($to);
		_restore_entry(File::Spec->catfile($src, $_), File::Spec->catfile($to, $_))
			for @{ list_dir($src) || [] };

		# Directory metadata last: filling it changed its mtime.
		chmod($stat[$STAT_MODE] & $MODE_MASK, $to) if $HAS_MODES;
		utime($stat[$STAT_MTIME], $stat[$STAT_MTIME], $to);

lib/App/FileSync/Trash.pm  view on Meta::CPAN


# _copy_tree
# Purpose:     copy a directory tree, keeping modes, mtimes and symlinks.
# Entry:       $src exists; $to does not.
# Exit:        returns 1.
# Side effects: creates $to; raises trash.cannot_stat, trash.not_regular,
#              io.copy, io.mkdir or an autodie error.
sub _copy_tree :Private {
	my ($src, $to) = @_;

	my @stat = Time::HiRes::lstat($src);
	throw('trash.cannot_stat', { path => $src, error => os_error() }) unless @stat;

	if (-l _) {
		symlink readlink($src), $to;
		return 1;
	}

	if (-d _) {
		ensure_dir($to);
		_copy_tree(File::Spec->catfile($src, $_), File::Spec->catfile($to, $_))

t/00-load.t  view on Meta::CPAN

use_ok('App::FileSync::Scan');
use_ok('App::FileSync::Server');
use_ok('App::FileSync::Settings');
use_ok('App::FileSync::Snapshot');
use_ok('App::FileSync::Store');
use_ok('App::FileSync::Transport::Local');
use_ok('App::FileSync::Transport::SSH');
use_ok('App::FileSync::Trash');
use_ok('App::FileSync::Verify');

# The named stat() fields must pick the same values as the numbers they
# replace, and must stay read-only without being tied (a tied scalar costs a
# method call on every read, and some are read once per file).
{
	use App::FileSync::Constants qw($STAT_MODE $STAT_SIZE $STAT_MTIME $MODE_MASK);

	my @stat = stat($0);
	is($stat[$STAT_SIZE], -s $0, '$STAT_SIZE picks the size');
	is($stat[$STAT_MTIME], (stat _)[9], '$STAT_MTIME picks the modification time');
	is($stat[$STAT_MODE] & $MODE_MASK, (stat _)[2] & oct('7777'), '$STAT_MODE picks the mode');

	for my $name (qw(STAT_MODE STAT_SIZE STAT_MTIME MODE_MASK)) {
		no strict 'refs';	## no critic (TestingAndDebugging::ProhibitNoStrict)
		my $ref = \${"App::FileSync::Constants::$name"};
		ok(!tied(${$ref}), "\$$name is not tied");
		throws_ok { ${$ref} = 0 } qr/read-?only/i, "\$$name cannot be changed";
	}

t/function.t  view on Meta::CPAN

	# Strategy: undef means "leave it", a fractional time is kept where the
	# platform allows, the whole-second fallback is used only for the
	# "unimplemented" croak, and a file that cannot be touched is an error
	# (old: a missing file silently "succeeded").
	my $dir = scratch();
	my $path = put_file(File::Spec->catfile($dir, 'f'), 'x', 1000);

	is(App::FileSync::IO::set_mtime($path, undef), 1, 'undef: nothing to do');
	is((stat $path)[9], 1000, 'and the file is unchanged');
	App::FileSync::IO::set_mtime($path, 2000.75);
	cmp_ok(abs((Time::HiRes::stat($path))[9] - 2000.75), '<', 1, 'a fractional time');

	my $missing = File::Spec->catfile($dir, 'missing');
	error_is(sub { App::FileSync::IO::set_mtime($missing, 5) },
		"Cannot set the modification time of $missing: ${\ do { local $! = ENOENT; qq{$!} }}", 'a missing file is io.utime');

	my @fallback;
	mock 'Time::HiRes::utime' => sub { die "Time::HiRes::utime(): unimplemented in this platform\n" };
	App::FileSync::IO::set_mtime($path, 3000.9);
	is((stat $path)[9], 3000, 'the fallback stores whole seconds');
	error_is(sub { App::FileSync::IO::set_mtime($missing, 5) },

t/function.t  view on Meta::CPAN

	is_deeply([ @{ $conn->last_reply() }{qw(_bytes eof s)} ], [ '', 1, 6 ], 'an offset at the end is an empty last chunk');
	error_is(sub { $server->_get({ p => 'f', off => 7 }) }, "Bad 'off' for 'f'", 'past the end');
	error_is(sub { $server->_get({ p => 'f', off => -1 }) }, "Bad 'off' for 'f'", 'a negative offset');
	error_is(sub { $server->_get({ p => 'f', max => '1.5' }) }, "Bad 'max' for 'f'", 'a fractional max');
	mock 'App::FileSync::Delta::read_exact' => sub { return 'x' x $_[1] };
	$server->_get({ p => 'f', max => 10**12 });
	restore_all();
	is(length $conn->last_reply()->{_bytes}, 6, 'a huge max is clamped, never trusted');
	error_is(sub { $server->_get({ p => 'd' }) }, "Cannot send 'd': not a regular file", 'a directory');
	error_is(sub { $server->_get({ p => 'gone' }) }, "Cannot stat gone: ${\ do { local $! = ENOENT; qq{$!} }}", 'a vanished file');
	is_deeply($server->_file_stat(master_file($server, 'f'), 'f')->{s}, 6, '_file_stat');
	SKIP: {
		skip 'no symlinks', 1 unless eval { symlink '/etc/passwd', master_file($server, 'evil') };
		# Scan never lists a symlink, but the master can change between the
		# plan and the read: a link put there must not be followed out of it.
		$server->{plan}{evil} = { p => 'evil', a => 'pull' };
		error_is(sub { $server->_get({ p => 'evil' }) }, "Cannot send 'evil': not a regular file", 'a symlink is never followed (old: sent its target)');
	}
};

subtest 'Server::_put, _chunk, _chunk_end and the upload helpers' => sub {

t/lib/TestSync.pm  view on Meta::CPAN

}

sub snapshot {
	my ($self, $dir) = @_;

	my %snapshot;
	for my $rel (@{ $self->tree($dir) }) {
		my $path = File::Spec->catfile($dir, split m{/}, $rel);
		my $sha = Digest::SHA->new(256);
		$sha->addfile($path, 'b');
		my @stat = stat($path);
		$snapshot{$rel} = $sha->hexdigest() . ':' . $stat[9];
	}

	return \%snapshot;
}

sub meta_path {
	my ($self, @parts) = @_;
	return File::Spec->catfile($self->{server}, '.filesync', 'repos', 'docs', @parts);
}

t/mtime.t  view on Meta::CPAN

# Pretend to be one of them: the builtin fallback must still set the time.
{
	no warnings 'redefine';
	local *Time::HiRes::utime = sub {
		die "Time::HiRes::utime(): unimplemented in this platform\n";
	};

	lives_ok { set_mtime($file, 1_700_000_124.75) }
		'set_mtime survives an unimplemented Time::HiRes::utime';

	my @stat = stat($file);
	is($stat[9], 1_700_000_124,
		'the builtin fallback sets the mtime to whole seconds');
}

# Anything other than the unimplemented croak is a real failure and is not
# quietly retried and swallowed.
{
	no warnings 'redefine';
	local *Time::HiRes::utime = sub { die "utime failed: permission denied\n" };

	throws_ok { set_mtime($file, 1_700_000_124) } qr/permission denied/,
		'a real utime failure still propagates';
}

# Where Time::HiRes works, the helper keeps its sub-second precision.
SKIP: {
	skip 'sub-second mtimes are not available here', 1 if $^O eq 'MSWin32';

	set_mtime($file, 1_700_000_124.75);
	my @stat = Time::HiRes::stat($file);
	ok(abs($stat[9] - 1_700_000_124.75) < 0.01,
		'the normal path keeps sub-second precision');
}

done_testing();

t/regressions.t  view on Meta::CPAN


subtest 'Server: a symlink in the master is never sent' => sub {
	# Old: _file_stat followed links, so a link appearing between the plan
	# and the read sent whatever it pointed at.
	my $env = TestSync->new_env();
	my $store = App::FileSync::Store->new(root => $env->{server}, repo => 'docs');
	my $server = App::FileSync::Server->new(root => $env->{server}, repo => 'docs', client => 'test-1', role => 'client',
		connection => App::FileSync::Protocol->new(in => \*STDIN, out => \*STDOUT), logger => Log::Abstraction->new(level => 'error', logger => []));
	my $link = File::Spec->catfile($store->master_dir(), 'evil');
	plan skip_all => 'no symlinks' unless eval { symlink $INC{'App/FileSync.pm'}, $link };
	throws_ok { $server->_file_stat($link, 'evil') } qr/\ACannot send 'evil': not a regular file/, 'refused';
};

subtest 'Client: a pull never goes through a symlinked directory' => sub {
	# Old: _abs only checked the path's text, so another client's file under
	# a name that is a symlink here was written wherever the link points.
	my $env = TestSync->new_env();
	my $outside = tempdir(CLEANUP => 1);
	plan skip_all => 'no symlinks' unless eval { symlink $outside, File::Spec->catfile($env->{client}, 'linked') };
	$env->write_file(server => 'linked/planted.txt', 'x');
	App::FileSync::Admin->new(root => $env->{server})->reindex(repo => 'docs');

t/snapshot.t  view on Meta::CPAN

	is($first->{created}, 1, 'a snapshot is created');
	is($first->{files}, 2, 'both files are in the snapshot');
	is($first->{linked}, $mode eq 'hardlink' ? 2 : 0,
		'files are hardlinked, not copied, when that is the platform default');
	is($first->{copied}, $mode eq 'copy' ? 2 : 0,
		'files are copied when copying is the platform default');
	SKIP: {
		skip 'inode numbers are not meaningful here', 1
			unless $mode eq 'hardlink' && $^O ne 'MSWin32';

		is((stat("$root/a.txt"))[1], (stat("$first->{path}/a.txt"))[1],
			'the snapshot file shares the inode with the mirror');
	}
	ok(-d "$first->{path}/empty", 'empty directories are captured');
	ok(!-e "$first->{path}/.filesync-root", 'the marker is not part of the snapshot');
	ok(!-e "$first->{path}/.filesync-snapshots", 'the snapshot directory does not contain itself');
	is(read_file("$first->{path}/sub/b.txt"), "bravo\n", 'content is captured');

	my $same = App::FileSync::Snapshot::create(
		root => $root, date => '2026-10-20', mode => $mode,
	);

t/snapshot.t  view on Meta::CPAN

	ok(!-d "$root/.filesync-snapshots/2026-10-18", 'it is gone from disk');
	is(scalar @{ App::FileSync::Snapshot::list(root => $root) }, 2, 'two snapshots are kept');

	# Restoring a single path replaces what is there now.
	replace_file("$root/a.txt", "corrupted\n", $T0 + 500);
	my $restored = App::FileSync::Snapshot::restore(
		root => $root, date => '2026-10-20', paths => ['a.txt'], to => $root,
	);
	is($restored->{files}, 1, 'one file restored');
	is(read_file("$root/a.txt"), "alpha\n", 'the old content is back');
	is((stat("$root/a.txt"))[9], $T0, 'mtime is preserved by the restore');

	# A copy-mode snapshot does not share inodes.
	my $copy = App::FileSync::Snapshot::create(
		root => $root, date => '2026-10-21', mode => 'copy',
	);
	is($copy->{copied}, 2, 'copy mode copies');
	SKIP: {
		skip 'inode numbers are not meaningful here', 1 if $^O eq 'MSWin32';

		isnt((stat("$root/a.txt"))[1], (stat("$copy->{path}/a.txt"))[1],
			'copy mode does not share inodes');
	}
	is(read_file("$copy->{path}/a.txt"), "alpha\n", 'copy mode captured the content');

	# A whole snapshot can be exported somewhere else.
	my $export = tempdir(CLEANUP => 1);
	my $whole = App::FileSync::Snapshot::restore(
		root => $root, date => '2026-10-20', to => $export,
	);
	is($whole->{files}, 2, 'the whole snapshot was restored');

t/sync.t  view on Meta::CPAN

	$env->write_file('client', 'sub/b.bin', "\x00\x01\x02\xff", $T0 + 10);
	make_path(File::Spec->catdir($env->{client}, 'empty'));
	utime($T0, $T0, File::Spec->catdir($env->{client}, 'empty'));

	my $result = $env->sync();
	is($result->{summary}{pushed}, 3, 'two files and one empty directory pushed');
	is($result->{exit}, 0, 'a clean sync exits 0');
	is($env->read_file('server', 'a.txt'), "alpha\n", 'file content reached the master');
	ok($env->exists_in('server', 'sub/b.bin'), 'nested file reached the master');
	ok($env->exists_in('server', 'empty'), 'empty directory reached the master');
	is((stat($env->server_path('a.txt')))[9], $T0, 'mtime preserved on the master');

	my $again = $env->sync();
	is($again->{summary}{pushed}, 0, 'second run pushes nothing');
	is($again->{summary}{pulled}, 0, 'second run pulls nothing');
	is($again->{exit}, 0, 'second run is clean');

	# Master-side edit is pulled.
	$env->write_file('server', 'a.txt', "changed on the server\n", $T0 + 100);
	my $pull = $env->sync();
	is($pull->{summary}{pulled}, 1, 'master-side change pulled');

t/unit.t  view on Meta::CPAN

	};

	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');

t/unit.t  view on Meta::CPAN

	}
};

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" };

t/unit.t  view on Meta::CPAN

			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');

t/unit.t  view on Meta::CPAN

	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');

t/unit.t  view on Meta::CPAN

	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');

t/unit.t  view on Meta::CPAN

	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');



( run in 3.814 seconds using v1.01-cache-2.11-cpan-eb134014566 )