KeyMangler example app
[scpubgit/DKit.git] / lib / DX / Lib / FS / Action / RewriteFile.pm
1 package DX::Lib::FS::Action::RewriteFile;
2
3 use DX::Lib::FS::Fact::FileContent;
4 use Moo;
5
6 with 'DX::Role::Action';
7 with 'DX::Lib::FS::Role::RunOn';
8
9 has from => (is => 'ro', required => 1, handles => [ 'path' ]);
10
11 has add_lines => (is => 'ro', default => sub { [] });
12
13 has remove_lines => (is => 'ro', default => sub { [] });
14
15 has final_content => (is => 'lazy', init_arg => undef, builder => sub {
16   my ($self) = @_;
17   my %remove = map +($_ => 1), @{$self->remove_lines};
18   join("\n",
19     (grep !$remove{$_}, $self->from->lines->all),
20     @{$self->add_lines},
21     ''
22   );
23 });
24
25 sub but_add {
26   $_[0]->but(add_lines => [ @{$_[0]->add_lines}, $_[1] ]);
27 }
28
29 sub but_remove {
30   $_[0]->but(remove_lines => [ @{$_[0]->remove_lines}, $_[1] ]);
31 }
32
33 sub expected_effect {
34   my ($self) = @_;
35   +(file_content => DX::Lib::FS::Fact::FileContent->new(
36     path => $self->path,
37     data => $self->final_content
38   ));
39 }
40
41 sub _do_run {
42   my ($self) = @_;
43   $self->_call_guts(rewrite_file => $self->final_content);
44   return +(file_content => $self->path);
45 }
46
47 1;