1 package DX::Lib::FS::Action::RewriteFile;
3 use DX::Lib::FS::Fact::FileContent;
6 use Fcntl qw(O_CREAT O_WRONLY);
9 with 'DX::Role::Action';
11 has from => (is => 'ro', required => 1, handles => [ 'path' ]);
13 has add_lines => (is => 'ro', default => sub { [] });
15 has remove_lines => (is => 'ro', default => sub { {} });
17 has final_content => (is => 'lazy', init_arg => undef, builder => sub {
19 my %remove = %{$self->remove_lines};
21 (grep !$remove{$_}, $self->from->lines->all),
28 $_[0]->but(add_lines => [ @{$_[0]->add_lines}, $_[1] ]);
32 $_[0]->but(remove_lines => [ %{$_[0]->remove_lines}, $_[1] => 1 ]);
37 +(file_content => DX::Lib::FS::Fact::FileContent->new(
39 data => $self->final_content
45 my $stat = stat($self->path) or die "Couldn't stat ${\$self->path}: $!";
46 my $perms = $stat->mode & 07777;
47 my $new = $self->path.'.new';
49 sysopen my $fh, $new, O_CREAT | O_WRONLY, $perms
50 or die "Couldn't open ${new}: $!";
51 print $fh $self->final_content
52 or die "Couldn't write data to ${new}: $!";
54 move($new, $self->path) or die "Couldn't install ${new}: $!";
55 return +(file_content => $self->from);