App-FileSync

 view release on metacpan or  search on metacpan

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

	client  => { allow => '_admin_client_allow', list => '_admin_client_list', forget => '_admin_client_forget' },
	log     => '_admin_log',
	verify  => '_admin_verify',
	reindex => '_admin_reindex',
	restore => '_admin_restore',
);

# Settings whose empty value means "the transport's default", and what to
# show instead of a blank column.
Readonly my %BLANK_SETTING => (
	log_file        => 'cli.settings.stderr',
	ssh_identity    => 'cli.settings.ssh_default',
	ssh_known_hosts => 'cli.settings.ssh_default',
	server_command  => 'cli.settings.server_default',
);

# Journal fields "filesync-admin log" prints as key=value, in this order.
Readonly my @EVENT_FIELDS   => qw(from winner loser_name exit trash sha256);
Readonly my @EVENT_COUNTERS => qw(actions deletions conflicts pulled pushed deleted);
Readonly my %EVENT_LABEL    => (loser_name => 'loser');

lib/App/FileSync/I18N/en.pm  view on Meta::CPAN

                    [--until YYYY-MM-DD|EPOCH] [--exit N]... [--warnings] [--json]
    filesync settings [--config FILE] [--json]
    filesync verify [--repo NAME] [--deep] [--json]
    filesync restore PATH [--repo NAME] [--to DIR] [--list]
    filesync snapshot [--repo NAME] [--keep N]
    filesync snapshot list [--repo NAME]
    filesync snapshot restore DATE [PATH] [--repo NAME] [--to DIR]
    filesync version

The sync root must contain the .filesync-root marker created by "filesync init".
Diagnostics go to stderr; settings are read from ~/.conf/app-filesync.json or
$FILESYNC_SETTINGS (log_level, log_format, log_file, ssh_identity,
ssh_known_hosts, server_command).  "filesync settings" prints the effective
values and where each came from.  Per-repo values from "filesync init" win;
port and host_key_checking exist per repo only and are marked [repo only].

Exit codes: 0 ok, 1 fatal, 2 another run holds the lock, 3 completed with
warnings, 4 verification found drift.

"filesync init --help" explains the options init takes.
USAGE

lib/App/FileSync/I18N/en.pm  view on Meta::CPAN

	'cli.log.event'     => '%{indent}s%{ts}s  %{client}-12s %{action}-12s %{detail}s',

	'cli.settings.file'           => 'settings file: %{file}s',
	'cli.settings.no_file'        => '(none)',
	'cli.settings.row'            => '  %{key}-16s %{value}-40s %{source}s',
	'cli.settings.note'           => "An empty ssh_identity or ssh_known_hosts means ssh's own default; an empty server_command means filesync-server.\nIn the repo sections, [repo only] marks port and host_key_checking, which have no process-wide defaul...
	'cli.settings.repos'          => 'repos:',
	'cli.settings.repo'           => '  %{repo}s (%{transport}s%{server}s)',
	'cli.settings.local'          => '    the local transport does not use the SSH settings',
	'cli.settings.repo_row'       => '    %{key}-18s %{value}-38s %{source}s',
	'cli.settings.stderr'         => '(stderr)',
	'cli.settings.ssh_default'    => '(ssh default)',
	'cli.settings.server_default' => 'filesync-server',
	'cli.source.default'          => '%{label}s',
	'cli.source.merged'           => 'merged: %{label}s',
	'cli.source.env'              => 'environment %{label}s',
	'cli.source.file'             => 'file %{label}s',
	'cli.repo_source.repo'        => 'repo (%{label}s)',
	'cli.repo_source.process'     => 'process (%{label}s)',
	'cli.repo_source.default'     => '%{label}s',
	'cli.source.repo_only'        => '%{description}s [repo only]',

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

=encoding utf8

=head1 NAME

App::FileSync::Process - start and reap a transport's child process

=head1 SYNOPSIS

	use App::FileSync::Process;

	my $child = App::FileSync::Process::spawn(command => [ 'ssh', 'host', 'filesync-server' ], stderr => fileno(STDERR));
	print { $child->{writer} } "...\n";
	close $child->{writer};
	close $child->{reader};
	my $end = App::FileSync::Process::reap(pid => $child->{pid});

=head1 DESCRIPTION

A transport writes to its child's standard input and reads its standard
output, and relies on the child seeing end of file when the transport closes
its end.  That only happens once every copy of the pipe's write end is

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

C<spawn> therefore makes the parent's ends non-inheritable on Windows before
starting the child, and C<reap> never waits without limit: a child that has
not exited after C<$GRACE_SECONDS> is stopped.

=head1 FUNCTIONS

=head2 spawn

Purpose: start a child process with pipes to its standard input and output.

Args: C<command> (the argv, never passed through a shell), C<stderr> (a file
descriptor the child's standard error goes to).

Returns: a hashref: C<pid>, C<writer> (to the child's standard input),
C<reader> (from its standard output).  The writer is unbuffered.

Side Effects: starts the process.  On Windows, briefly points this process's
standard handles at the child's pipes while it starts.

Usage:

	my $child = App::FileSync::Process::spawn(command => \@argv, stderr => fileno(STDERR));

=head3 EXAMPLE

	my $child = App::FileSync::Process::spawn(command => [ $^X, '-pe1' ], stderr => fileno(STDERR));
	print { $child->{writer} } "echo\n";
	close $child->{writer};
	print readline $child->{reader};	# echo

=head3 API SPECIFICATION

=head4 INPUT

	{
		command => { type => 'arrayref', min => 1 },
		stderr  => { type => 'integer', min => 0 },
	}

=head4 OUTPUT

	{
		type => 'hashref',
		schema => {
			pid    => { type => 'integer', min => 1 },
			writer => { type => 'object' },
			reader => { type => 'object' },
		},
	}

=head3 MESSAGES

	Key              Meaning                       Resolution
	args.invalid     command or stderr is missing  pass them
	process.spawn    the program could not start   check that it exists and runs
	process.inherit  Windows refused a handle flag see the error text

=head3 FORMAL SPECIFICATION

	spawn(a) ⇒ ∃ c • argv(c) = a.command ∧ stdin(c) = pipe(writer) ∧ stdout(c) = pipe(reader)
	         ∧ writer ∉ handles(c) ∧ reader ∉ handles(c)

=head3 PSEUDOCODE

	if not Windows:
		open3 the command (it marks the parent's ends close-on-exec)
	else:
		make two pipes, and mark the parent's ends non-inheritable
		save STDIN, STDOUT, STDERR; point them at the child's ends and stderr
		start the command without waiting; restore the standard handles
		close the child's ends in this process
	return pid, writer, reader

=cut

sub spawn {
	my $args = named(\@_, {
		command => { type => 'arrayref', min => 1 },
		stderr  => { type => 'integer', min => 0 },
	}, 'Process::spawn');

	my @command = @{ $args->{command} };
	my ($pid, $writer, $reader);

	if ($IS_WINDOWS) {
		($pid, $writer, $reader) = _spawn_windows(\@command, $args->{stderr});
	} else {
		$pid = eval { IPC::Open3::open3($writer, $reader, '>&' . $args->{stderr}, @command) };
		throw('process.spawn', { program => $command[0], error => _reason($@) }) unless $pid;
	}
	$writer->autoflush(1);

	return { pid => $pid, writer => $writer, reader => $reader };
}

=head2 reap

Purpose: wait for a child to exit, stopping it if it does not.

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

		my $reaped = waitpid($pid, WNOHANG);
		return 1 if $reaped == $pid || $reaped == $NO_CHILD;
		return 0 if Time::HiRes::time() >= $deadline;
		Time::HiRes::sleep($POLL_SECONDS);
	}
	return 0;
}

# _spawn_windows
# Purpose:     start a child on Windows without it inheriting our pipe ends.
# Entry:       $command is the argv; $stderr a file descriptor.
# Exit:        returns ($pid, $writer, $reader).
# Side effects: starts the process.  STDIN, STDOUT and STDERR point at the
#              child's handles while it starts (that is how a Windows child
#              is given them) and are restored before returning, even when
#              the start fails.  This is what IPC::Open3 does on Windows,
#              plus the inheritance flags it leaves set.
sub _spawn_windows :Private {
	my ($command, $stderr) = @_;

	pipe(my $child_in, my $writer);
	pipe(my $reader, my $child_out);
	_no_inherit($_) for $writer, $reader;

	STDOUT->flush();
	STDERR->flush();
	my @restore = (
		_point(\*STDIN,  '<', $child_in),
		_point(\*STDOUT, '>', $child_out),
		_point(\*STDERR, '>', $stderr),
	);

	my $pid = do {
		local $!;
		my $started = eval { CORE::system(1, @{$command}) };	# 1 == P_NOWAIT
		my $error = $@ || "$!";
		$_->() for reverse @restore;
		throw('process.spawn', { program => $command->[0], error => _reason($error) })
			unless $started && $started > 0;
		$started;

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

# _point
# Purpose:     point a standard handle somewhere else for a while.
# Entry:       $handle is STDIN, STDOUT or STDERR; $mode '<' or '>';
#              $target a handle or a file descriptor.
# Exit:        returns a coderef that puts $handle back as it was.
# Side effects: dups $handle aside (not inheritable, so the child does not
#              keep this process's own output open), then dups $target onto it.
sub _point :Private {
	my ($handle, $mode, $target) = @_;

	# Already there (the server's stderr is usually ours): reopening a handle
	# as a dup of its own descriptor would close it first.
	my $current = fileno $handle;
	return sub { 1 } if !ref $target && defined $current && $target == $current;

	my $saved;
	if (defined fileno $handle) {
		open $saved, "$mode&", $handle;
		_no_inherit($saved);
	}
	open $handle, "$mode&", $target;

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

	]

=head4 OUTPUT

	{ type => 'integer', min => 1, max => 1 }

=head3 MESSAGES

	Key                       Meaning                          Resolution
	protocol.closed           the connection was closed        a caller bug
	protocol.write_failed     the pipe would not take it       see the transport's stderr

=head3 FORMAL SPECIFICATION

	pre ¬closed
	out' = out ⁀ json(message) ⁀ "\n"

=cut

sub send {	## no critic (Subroutines::ProhibitBuiltinHomonyms)
	my ($self, $message) = @_;

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

=head4 OUTPUT

	{ type => 'hashref' }

=head3 MESSAGES

	Key                   Meaning                        Resolution
	protocol.malformed    the line is not JSON           version mismatch or corrupt stream
	protocol.not_object   the JSON is not an object      version mismatch
	protocol.eof          the peer closed the connection see the peer's log
	protocol.read_failed  the pipe failed                see the transport's stderr

=head3 FORMAL SPECIFICATION

	in = line ⁀ "\n" ⁀ rest ⇒ recv = json⁻¹(line) ∧ in' = rest
	pre json⁻¹(line) ∈ OBJECT

=cut

sub recv {	## no critic (Subroutines::ProhibitBuiltinHomonyms)
	my ($self) = @_;

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

	]

=head4 OUTPUT

	{ type => 'integer', min => 1, max => 1 }

=head3 MESSAGES

	Key                       Meaning                          Resolution
	protocol.closed           the connection was closed        a caller bug
	protocol.write_failed     the pipe would not take it       see the transport's stderr

=head3 FORMAL SPECIFICATION

	out' = out ⁀ bytes

=cut

sub send_bytes {
	my ($self, $bytes) = @_;

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


=head4 OUTPUT

	{ type => 'string' }

=head3 MESSAGES

	Key                       Meaning                          Resolution
	protocol.negative         a negative length was asked for  a caller bug
	protocol.eof              the peer closed the connection   see the peer's log
	protocol.read_failed      the pipe failed                  see the transport's stderr

=head3 FORMAL SPECIFICATION

	read_line: in = l ⁀ "\n" ⁀ r ∧ "\n" ∉ ran l ⇒ result = l ∧ in' = r
	read_bytes(n): in = b ⁀ r ∧ #b = n ⇒ result = b ∧ in' = r

=cut

sub read_line {
	my ($self) = @_;

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

		});

		$self->_loop();
		1;
	};

	return 1 if $ok;

	# The client shows this text to a person, so no Perl file and line, and
	# only where in the repo, not where the server keeps it.  The log is
	# rewritten too: over ssh the server's stderr reaches the client.  Only
	# the journal, which stays on the server, keeps the absolute paths.
	my $error = strip_location($@) || $self->i18n('server.unknown_error');
	my $shown = $self->_for_client($error);
	$self->{logger}->error($shown);
	$self->_discard_uploads();
	$self->_journal_failed_session($error);

	eval {
		$connection->send({ ok => 0, error => $shown, fatal => 1, ($self->{refusal} ? (code => $self->{refusal}) : ()) });
	};
	return 0;
}

# _for_client
# Purpose:     take the server's file layout out of an error for the client
#              (and for the log, whose stderr reaches the client over ssh).
# Entry:       $text is an error as the server logs it.
# Exit:        returns the text with each path under the master made relative
#              to the repo ("x", not "/srv/filesync/master/docs/x") and any
#              other mention of the server root replaced by a placeholder.
# Side effects: none.
sub _for_client :Private {
	my ($self, $text) = @_;

	# new() refuses a server without a root or a repo, so both are set.  The
	# store builds its paths with catdir, so match the canonical form: a root

lib/App/FileSync/Transport/Local.pm  view on Meta::CPAN

	}

	my @command = (
		$^X, $args->{server_bin} || _default_server_bin(),
		'--root',   $args->{root},
		'--repo',   $args->{repo},
		'--client', $args->{client},
		'--role',   $args->{role} || $ROLE_CLIENT,
	);

	# The child's stderr is a dup of ours.  A pipe here would not be read, and
	# the first log line would kill the server with SIGPIPE.
	my $child = App::FileSync::Process::spawn(command => \@command, stderr => fileno(STDERR));

	return bless { %{$child} }, $class;
}

=head2 reader

Documented with L</writer> below.

=head2 writer

lib/App/FileSync/Transport/SSH.pm  view on Meta::CPAN


	# The remote shell splits this back into arguments; every value is
	# restricted (above) to characters that are inert in a POSIX shell.
	push @command, $args->{server}, $program,
		'--repo', $args->{repo}, '--client', $args->{client}, '--role', $role, '--proto', $PROTO;

	if ($^O eq 'MSWin32' && $command[0] =~ /\.(?:cmd|bat)\z/i) {
		unshift @command, _given($ENV{COMSPEC}) // 'cmd.exe', '/d', '/c';
	}

	return bless { command => \@command, status => undef, stderr => '', %{ _spawn(\@command) } }, $class;
}

=head2 reader

Documented with L</exit_status> below.

=head2 writer

Documented with L</exit_status> below.

lib/App/FileSync/Transport/SSH.pm  view on Meta::CPAN

	return 1 if $self->{closed}++;

	for my $handle (grep { defined } @{$self}{qw(writer reader)}) {
		CORE::close($handle);
	}

	if ($self->{pid}) {
		my $end = App::FileSync::Process::reap(pid => $self->{pid});
		@{$self}{qw(status signal killed pid)} = (@{$end}{qw(status signal killed)}, 0);
	}
	$self->{stderr} = _slurp($self->{error_path});

	return ($self->{status} || 0) == 0 && !$self->{killed} ? 1 : 0;
}

=head2 error_text

Purpose: what ssh or the remote shell said, for when the protocol failed.

Args: none.

lib/App/FileSync/Transport/SSH.pm  view on Meta::CPAN

=head4 OUTPUT

	{ type => 'string' }

=head3 MESSAGES

None.

=head3 FORMAL SPECIFICATION

	error_text = squeeze(trim(stderr))

=cut

sub error_text {
	my ($self) = @_;

	my $text = length $self->{stderr} ? $self->{stderr} : _slurp($self->{error_path});
	$text =~ s/\A\s+|\s+\z//g;
	$text =~ s/\n+/\n/g;
	return $text;
}

=head2 valid_server

Documented with L</valid_program> below.

=head2 valid_program

lib/App/FileSync/Transport/SSH.pm  view on Meta::CPAN

	return (defined $value && $value =~ $SERVER) ? 1 : 0;
}

sub valid_program {
	my ($value) = @_;

	return (defined $value && $value =~ $PROGRAM) ? 1 : 0;
}

# _spawn
# Purpose:     start ssh with stderr going to a temporary file.
# Entry:       $command is the full argv.
# Exit:        returns { pid, writer, reader, errors, error_path }.
# Side effects: creates the error file (removed when the object goes) and
#              starts the process.  App::FileSync::Process rather than
#              fork/exec: on Windows fork() is a pseudo-process whose pipe
#              handles are not always duplicated, and IPC::Open3 alone lets
#              ssh inherit our end of its stdin, so it never saw end of file.
sub _spawn :Private {
	my ($command) = @_;

	my $errors = File::Temp->new(UNLINK => 1);
	my $error_path = $errors->filename;
	open my $err_fh, '>', $error_path;

	my $child = eval { App::FileSync::Process::spawn(command => $command, stderr => fileno($err_fh)) };
	my $error = $@;
	CORE::close($err_fh);
	die $error unless $child;

	return { %{$child}, errors => $errors, error_path => $error_path };
}

# _check
# Purpose:     refuse an unsafe or out-of-range argument.
# Entry:       $ok is the result of the check.

t/regressions.t  view on Meta::CPAN

use App::FileSync::Transport::SSH;
use App::FileSync::Trash;
use App::FileSync::Verify;

my $T0 = 1_700_000_000;

# --- helpers ----------------------------------------------------------------

# Open a raw session as the env's client, send the client tree's manifest and
# ask for a plan.  Returns { transport, conn, plan => { path => action } }.
# The server's stderr goes to a temporary file: these sessions end abruptly
# on purpose and its "connection closed" diagnostics are expected, but when a
# call finds the server gone, call() shows what it said.
sub session {
	my ($env) = @_;

	my $log = File::Spec->catfile(tempdir(CLEANUP => 1), 'server.err');
	open my $saved, '>&', \*STDERR or die "dup stderr: $!";
	open STDERR, '>', $log or die "stderr to $log: $!";
	my $transport = App::FileSync::Transport::Local->new(root => $env->{server}, repo => 'docs', client => 'test-1');
	open STDERR, '>&', $saved or die "restore stderr: $!";

	my $conn = App::FileSync::Protocol->new(in => $transport->reader(), out => $transport->writer());
	$conn->send({
		cmd => 'hello', proto => 2, client => 'test-1', host => 'test', os => $^O,
		role => 'client', repo => 'docs', case_insensitive => 0, now => time,
	});
	my $hello = $conn->recv();
	die 'session refused' unless $hello->{ok};

	# Scan with the server's own ignore list, as the real client does.

t/regressions.t  view on Meta::CPAN

	die 'manifest refused' unless $conn->recv()->{ok};

	$conn->send({ cmd => 'plan' });
	my $plan = $conn->recv();
	die 'no plan' unless $plan->{ok};

	return { transport => $transport, conn => $conn, log => $log, plan => { map { $_->{p} => $_ } @{ $plan->{actions} } } };
}

# Send one message (with optional data) and return the reply.  If the
# connection fails, the server's stderr is shown before the error is rethrown.
sub call {
	my ($session, $message, $bytes) = @_;

	my $reply = eval {
		defined $bytes ? $session->{conn}->send_data($message, $bytes) : $session->{conn}->send($message);
		$session->{conn}->recv();
	};
	return $reply if $reply;

	my $error = $@;
	if (open my $fh, '<', $session->{log}) {
		local $/;
		my $said = <$fh>;
		diag("the server's stderr:\n$said") if defined $said && length $said;
	}
	die $error;
}

sub sha256_hex {
	my ($bytes) = @_;
	return Digest::SHA::sha256_hex($bytes);
}

# An env whose a.txt was synced, then changed on both sides: the client's

t/regressions.t  view on Meta::CPAN

	ok(!$env->exists_in('server', 'new-here.txt'), 'nothing was created there either');
};

subtest 'Server: filesync-server exits 0 after a good session and 1 after a failed one' => sub {
	# ssh hands the server's exit status back to the client, so it must say
	# whether the session worked.  Nothing checked it, and Server::run could
	# have reported success as failure unnoticed.
	my $env = TestSync->new_env();
	my $exit = sub {
		my ($repo, @messages) = @_;
		open my $saved, '>&', \*STDERR or die "dup stderr: $!";
		open STDERR, '>', File::Spec->devnull() or die "null stderr: $!";
		my $child = App::FileSync::Process::spawn(command => [
			$^X, '-Ilib', 'bin/filesync-server',
			'--root', $env->{server}, '--repo', $repo, '--client', 'test-1', '--role', 'client',
		], stderr => fileno(STDERR));
		open STDERR, '>&', $saved or die "restore stderr: $!";

		my $conn = App::FileSync::Protocol->new(in => $child->{reader}, out => $child->{writer});
		my @replies;
		for my $message (@messages) {
			$conn->send($message);
			push @replies, $conn->recv();
			last unless $replies[-1]{ok};
		}
		close $child->{writer};
		close $child->{reader};

t/regressions.t  view on Meta::CPAN

	}

	# Through a real session: a master directory that refuses new files stops
	# the upload's temporary file, and the error names that directory.
	my $env = TestSync->new_env();
	plan skip_all => why_not('create', $env->{server}) unless can_revoke_create($env->{server});
	$env->write_file('client', 'sub/a.txt', "one\n", $T0);
	$env->sync();
	$env->write_file('client', 'sub/b.txt', "two\n", $T0 + 5);

	# The local server shares our stderr, as an ssh server's reaches the
	# client: catch it to see the server's log line.
	my $error;
	my $log = File::Spec->catfile(tempdir(CLEANUP => 1), 'server.err');
	with_revoked(create => $env->server_path('sub'), sub {
		open my $saved, '>&', \*STDERR or die "dup stderr: $!";
		open STDERR, '>', $log or die "Cannot write $log: $!";
		eval { $env->sync(); 1 } or $error = $@;
		open STDERR, '>&', $saved or die "restore stderr: $!";
	});
	like($error, qr/Cannot create a temporary file in sub: /, 'the client is told the repo path');
	unlike($error, qr/\Q$env->{server}\E/, 'and not where the server keeps it');
	my $logged = do { open my $fh, '<', $log or die "Cannot read $log: $!"; local $/; <$fh> };
	like($logged, qr/Cannot create a temporary file in sub: /, 'the server logs the same text');
	unlike($logged, qr/\Q$env->{server}\E/, 'so its stderr carries no server path either');

	my ($event) = grep { ($_->{action} // '') eq 'session' && ($_->{result} // '') eq 'error' }
		@{ App::FileSync::Admin->new(root => $env->{server})->journal_read(repo => 'docs') };
	like($event->{error}, qr/\Q$env->{server}\E/, 'the server journal keeps the absolute path');
};

# --- Client -----------------------------------------------------------------

subtest 'Client: each repo has its own local trash' => sub {
	my $env = TestSync->new_env();

t/regressions.t  view on Meta::CPAN

	my $env = conflict_env();
	my $s = session($env);
	my $content = "client\n";
	ok(call($s, { cmd => 'put', p => 'a.txt', s => length $content, h => sha256_hex($content), m => $T0 + 20, mode => 0644 })->{ok},
		'put accepted; the server now waits for the data');
	$s->{transport}->close();
	is($s->{transport}{end}{killed}, 0, 'the server saw end of file and exited without being stopped');
};

subtest 'Process: reap stops a child that will not exit' => sub {
	my $child = App::FileSync::Process::spawn(command => [ $^X, '-e', 'sleep 300' ], stderr => fileno(STDERR));
	close $child->{writer};
	close $child->{reader};
	my $started = time;
	my $end = App::FileSync::Process::reap(pid => $child->{pid}, grace => 0.2);
	is($end->{killed}, 1, 'it was stopped');
	cmp_ok(time - $started, '<', 30, 'promptly (old: waitpid with no limit)');
	SKIP: {
		# Windows waitpid() falls back to OpenProcess() for a pid that is no
		# longer its child, so asking again can return the pid.
		skip 'waitpid on a reaped pid is not -1 on Windows', 1 if $^O eq 'MSWin32';
		is(waitpid($child->{pid}, 0), -1, 'and reaped');
	}

	$child = App::FileSync::Process::spawn(command => [ $^X, '-e', 'exit 7' ], stderr => fileno(STDERR));
	$end = App::FileSync::Process::reap(pid => $child->{pid}, grace => 10);
	is_deeply($end, { status => 7, signal => 0, killed => 0 }, 'a child that exits keeps its status');
};

subtest 'Process: a program that cannot start is named' => sub {
	my $missing = File::Spec->catfile(tempdir(CLEANUP => 1), 'no-such-program');
	if ($^O eq 'MSWin32') {
		# Perl on Windows retries a program it cannot start through cmd.exe,
		# so the start succeeds and the failure is cmd.exe's exit status.
		open my $null, '>', File::Spec->devnull() or die "null: $!";
		my $child = App::FileSync::Process::spawn(command => [ $missing ], stderr => fileno($null));
		close $child->{writer};
		close $child->{reader};
		isnt(App::FileSync::Process::reap(pid => $child->{pid}, grace => 30)->{status}, 0, 'the child reports failure');
		return;
	}
	throws_ok { App::FileSync::Process::spawn(command => [ $missing ], stderr => fileno(STDERR)) }
		qr/Cannot start '\Q$missing\E'/, 'process.spawn';
};

subtest 'Transport::SSH: an ssh that has to be stopped is a failed close' => sub {
	plan skip_all => 'the stand-in ssh is a #! script' if $^O eq 'MSWin32';
	local $App::FileSync::Process::GRACE_SECONDS = 0.2;

	my $fake = File::Spec->catfile(tempdir(CLEANUP => 1), 'stuck-ssh');
	open my $fh, '>', $fake or die "Cannot write $fake: $!";
	print {$fh} "#!$^X\nsleep 300;\n";

t/settings.t  view on Meta::CPAN

	);
	local $ENV{FILESYNC_CONFIG} = $client_config;

	my $output = `$^X $filesync settings 2>&1`;
	is($?, 0, 'filesync settings exits 0');
	like($output, qr/^settings file: \Q$settings\E$/m, 'it names the settings file');
	like($output, qr/^\s+ssh_identity\s+\/home\/me\/\.ssh\/id_filesync\s+file \Q$settings\E \[App__FileSync\]$/m,
		'it shows an SSH default and where it came from');
	like($output, qr/^\s+server_command\s+filesync-server\s+built-in default$/m,
		'it shows the transport default for the remote program');
	like($output, qr/^\s+log_file\s+\(stderr\)/m, 'an empty log_file is shown as stderr');

	like($output, qr/^repos:$/m, 'the repos are listed');
	like($output, qr/^  docs \(ssh, srv\)$/m, 'a repo names its transport and server');
	like($output, qr/^    ssh_identity\s+\/home\/me\/\.ssh\/docs_key\s+repo \(\Q$client_config\E \[docs\]\)$/m,
		'a repo value says the repo supplied it');
	like($output, qr/^    ssh_known_hosts\s+\(ssh default\)\s+ssh default$/m,
		'an unset value says ssh supplied it');
	like($output, qr/^    server_command\s+filesync-server\s+process \(built-in default\)$/m,
		'an inherited value says the process settings supplied it');
	like($output, qr/^    port\s+22\s+ssh default \[repo only\]$/m,

t/transport.t  view on Meta::CPAN

	throws_ok {
		App::FileSync::Transport::SSH->new(server => 'host', repo => 'docs', client => 'laptop', command => $fake, extra_args => '-v')
	} qr/'extra_args'/, 'extra_args that is not a list is refused';
	my ($at) = grep { $command->[$_] eq $fake } 0 .. $#{$command};
	is_deeply($recorded->(), [ @{$command}[ $at + 1 .. $#{$command} ] ],
		'a refused transport starts no ssh: the last argv recorded is the good one');
}

# --- Transport::Local::error_text ------------------------------------------------

# The local server shares this process's stderr, so the transport has nothing
# of its own to add: error_text is empty before and after a whole session.
{
	my $env = TestSync->new_env();
	my $local = App::FileSync::Transport::Local->new(root => $env->{server}, repo => 'docs', client => 'test-1');
	is($local->error_text(), '', 'error_text is empty while the session runs');

	my $connection = App::FileSync::Protocol->new(in => $local->reader(), out => $local->writer());
	$connection->send({ cmd => 'hello', proto => $PROTOCOL_VERSION, repo => 'docs', client => 'test-1', role => 'client' });
	ok($connection->recv()->{ok}, 'the local server answers');
	$connection->send({ cmd => 'done' });



( run in 3.606 seconds using v1.01-cache-2.11-cpan-60884a8df76 )