App-FileSync

 view release on metacpan or  search on metacpan

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


=head3 EXAMPLE

	print "$_\n" for @{ list_dir('/tmp') || [] };

=head3 API SPECIFICATION

=head4 INPUT

	[ { name => 'directory', type => 'string', min => 1 } ]

=head4 OUTPUT

	{ type => 'arrayref', optional => 1 }

=head3 MESSAGES

None; an unreadable directory yields C<undef>.

=head3 FORMAL SPECIFICATION

	list_dir : PATH ⇸ seq NAME
	list_dir(d) = sort(children d \ {".", ".."})   if readable d

=cut

sub list_dir {
	my ($directory) = @_;

	# A missing or unreadable directory is an answer here, not an exception,
	# so autodie is switched off for this one call and $! is left for the
	# caller to report.
	my $dh;
	my $opened = do { no autodie qw(opendir); opendir($dh, $directory) };
	return undef unless $opened;	## no critic (Subroutines::ProhibitExplicitReturnUndef)

	my @names = sort grep { $_ ne '.' && $_ ne '..' } readdir($dh);
	closedir $dh;

	return \@names;
}

=head2 copy_preserving

Purpose: copy one regular file, keeping its mode and mtime.

Args: C<$source>, C<$destination>, optional C<\@stat> of the source (saves a
second C<stat> when the caller already has one).

Returns: 1.

Side Effects: creates C<$destination>'s parent directories; overwrites
C<$destination>.

Usage:

	copy_preserving($from, $to, \@stat);

=head3 EXAMPLE

	copy_preserving('/srv/a.txt', '/backup/a.txt');

=head3 API SPECIFICATION

=head4 INPUT

	[
		{ name => 'source',      type => 'string', min => 1 },
		{ name => 'destination', type => 'string', min => 1 },
		{ name => 'stat',        type => 'arrayref', optional => 1 },
	]

=head4 OUTPUT

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

=head3 MESSAGES

	Key       Meaning                      Resolution
	io.copy   the copy could not be made   check space and permissions

=head3 FORMAL SPECIFICATION

	Δ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->[2] & $MODE_MASK, $destination) if $HAS_MODES;
	utime($stat->[9], $stat->[9], $destination);

	return 1;
}

=head2 append_line

Purpose: append one line to a log or journal.

Args: C<$path>, C<$line> (without a newline).

Returns: 1.

Side Effects: creates C<$path> and its directory if needed.  If the file ends
in a torn line from a killed run, a newline is written first so the new entry
is not glued to the fragment.

Usage:

	append_line($journal, json_encode($event));

=head3 EXAMPLE



( run in 2.217 seconds using v1.01-cache-2.11-cpan-99fa8243a42 )