App-FileSync

 view release on metacpan or  search on metacpan

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


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

	my @date = defined $path ? $path =~ m{[/\\](\d{4})[/\\](\d{2})[/\\](\d{2})[/\\]}a : ();
	return @date ? join('-', @date) : undef;
}

=head2 version_info

Purpose: describe one trashed version for a listing.

Args: C<$path>, a path from L</versions>.

Returns: C<{ path, date, size, mtime }>; C<size> and C<mtime> are C<undef> if
the version has gone since it was listed.

Side Effects: stats the path.

Usage:

	my @rows = map { App::FileSync::Trash::version_info($_) } @{$versions};

=head3 EXAMPLE

	my $info = App::FileSync::Trash::version_info($versions->[0]);
	print "$info->{date} $info->{size} bytes\n";

=head3 API SPECIFICATION

=head4 INPUT

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

=head4 OUTPUT

	{
		type => 'hashref',
		schema => {
			path  => { type => 'string' },
			date  => { type => 'string', optional => 1 },
			size  => { type => 'integer', optional => 1 },
			mtime => { type => 'number', optional => 1 },
		},
	}

=head3 MESSAGES

None.

=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.
# Entry:       $root is the trash root; $epoch a time.
# Exit:        returns ROOT/YYYY/MM/DD (UTC).
# Side effects: none.
sub _bucket :Private {
	my ($root, $epoch) = @_;

	# One directory per year, month and day: strftime gives "2026/11/04", and
	# catdir rejoins the parts with this platform's separator.
	return File::Spec->catdir($root, split m{/}, strftime($BUCKET_FORMAT, gmtime($epoch)));
}

# _buckets
# Purpose:     every day bucket under a trash root.
# Entry:       $root exists.
# Exit:        returns an arrayref of { path, year, month, day, date },
#              oldest first.
# Side effects: none.  Stray names at any level are ignored.
sub _buckets :Private {
	my ($root) = @_;

	my @buckets;
	for my $year (grep { $_ =~ $YEAR } @{ list_dir($root) || [] }) {
		my $year_dir = File::Spec->catdir($root, $year);
		for my $month (grep { $_ =~ $MONTH } @{ list_dir($year_dir) || [] }) {
			my $month_dir = File::Spec->catdir($year_dir, $month);
			for my $day (grep { $_ =~ $DAY } @{ list_dir($month_dir) || [] }) {
				push @buckets, {
					path  => File::Spec->catdir($month_dir, $day),
					year  => $year,
					month => $month,
					day   => $day,
					date  => "$year-$month-$day",
				};
			}
		}
	}

	return \@buckets;
}

# _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);
		return 1;
	}

	throw('trash.not_regular', { path => $src }) unless -f _;
	copy_preserving($src, $to, \@stat);

	return 1;
}

# _move_dir
# Purpose:     move a directory tree into the trash, even across filesystems.
# Entry:       $src is a directory (not a symlink); $final does not exist.
# Exit:        returns 1, or raises trash.move with $src left in place.
# Side effects: renames $src to $final; on EXDEV copies the tree to $final and
#              removes $src, removing the partial copy if the copy fails.
sub _move_dir :Private {
	my ($src, $final) = @_;

	return 1 if _rename_dir($src, $final);
	my $error = os_error();
	throw('trash.move', { from => $src, to => $final, error => $error }) unless $! == EXDEV;

	unless (eval { _copy_tree($src, $final); 1 }) {
		# An autodie failure carries its errno; one of ours is already text.
		my $caught = $@;
		$error = blessed($caught) && $caught->can(q{errno}) ? os_error($caught) : strip_location($caught);
		eval { remove_tree($final) };
		throw('trash.move', { from => $src, to => $final, error => $error });
	}

	# The copy is complete, so the trash holds everything; what cannot be
	# removed from the tree is reported rather than left silently.
	remove_tree($src, { error => \my $errors });
	if (@{$errors}) {
		my ($path, $message) = %{ $errors->[0] };
		throw('trash.move', { from => $path, to => $final, error => $message });
	}

	return 1;
}

# _rename_dir
# Purpose:     rename a directory, reporting failure through $! (a seam the
#              tests replace to simulate a cross-device rename).
# Entry:       $src exists; $to does not.
# Exit:        returns true on success, false with $! set on failure.
# Side effects: renames $src.
sub _rename_dir :Private {
	my ($src, $to) = @_;

	no autodie qw(rename);
	return rename $src, $to;
}

# _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, $_))
			for @{ list_dir($src) || throw('trash.cannot_stat', { path => $src, error => os_error() }) };

		# 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);
		return 1;
	}

	throw('trash.not_regular', { path => $src }) unless -f _;
	copy_preserving($src, $to, \@stat);

	return 1;
}

# _check_rel
# Purpose:     keep a relative path inside the bucket it is joined to.
# Entry:       $rel is the caller's relative path.
# Exit:        returns 1, or raises path.unsafe (an absolute path or a ".."
#              component would reach outside the trash).
# Side effects: none.
sub _check_rel :Private {
	my ($rel) = @_;

	my ($safe, $reason) = validate_relpath($rel);
	throw('path.unsafe', { path => $rel, reason => $reason }) unless $safe;
	return 1;
}

# _midnight_epoch
# Purpose:     the UTC epoch at the start of a bucket's day.
# Entry:       numeric year, month (1-12) and day strings from a bucket path.
# Exit:        returns the epoch, or undef for a date that does not exist
#              (timegm croaks on month 13 or day 31 of a 30-day month).
# Side effects: none.
sub _midnight_epoch :Private {
	my ($year, $month, $day) = @_;

	my $epoch = eval { Time::Local::timegm_modern(0, 0, 0, $day, $month - 1, $year) };
	return $epoch;
}

1;

__END__

=head1 LIMITATIONS

=over 4

=item * A same-day collision is stored as C<PATH.N>.  A real file whose name



( run in 0.667 second using v1.01-cache-2.11-cpan-eb134014566 )