simplify_static_dir/lib/Directory/Simplify/Instruction/Hardlink.pm
2023-07-20 14:30:05 -05:00

47 lines
1.1 KiB
Perl

package Directory::Simplify::Instruction::Hardlink;
use strict;
use warnings;
use overload '""' => 'as_string';
use Carp qw/ croak /;
# :squash-remove-start:
require Directory::Simplify::Utils;
# :squash-remove-end:
sub new {
my ($class, %args) = @_;
return bless {
freed => 0,
%args,
}, $class;
}
sub run {
my $self = shift;
# hard link the files
unless (unlink $self->{target}->{name}) {
croak "Failed to remove file `$self->{target}->{name}': $!\n";
}
unless (link $self->{source}->{name}, $self->{target}->{name}) {
croak "Failed to hard link `$self->{source}->{name}' => `$self->{target}->{name}': $!";
}
# bookkeeping
++$self->{source}->{nlink};
if (--$self->{target}->{nlink} == 0) {
$self->{freed} = $self->{target}->{size};
}
return;
}
sub bytes_freed {
my $self = shift;
return $self->{freed};
}
sub as_string {
my $self = shift;
return sprintf 'ln -sf %s %s', Directory::Simplify::Utils::shell_quote($self->{source}->{name}, $self->{target}->{name});
}
1;