rewrite file correctly chaining from create file
[scpubgit/DKit.git] / lib / DX / Lib / FS / Action / RewriteFile.pm
index 0e7548f..64bd66b 100644 (file)
@@ -1,11 +1,14 @@
 package DX::Lib::FS::Action::RewriteFile;
 
 use DX::Lib::FS::Fact::FileContent;
+use File::stat;
+use File::Copy;
+use Fcntl qw(O_CREAT O_WRONLY);
 use Moo;
 
 with 'DX::Role::Action';
 
-has from => (is => 'ro', required => 1);
+has from => (is => 'ro', required => 1, handles => [ 'path' ]);
 
 has add_lines => (is => 'ro', default => sub { [] });
 
@@ -32,11 +35,24 @@ sub but_remove {
 sub expected_effect {
   my ($self) = @_;
   +(file_content => DX::Lib::FS::Fact::FileContent->new(
-    path => $self->from->path,
+    path => $self->path,
     data => $self->final_content
   ));
 }
 
-sub _do_run { die }
+sub _do_run {
+  my ($self) = @_;
+  my $stat = stat($self->path) or die "Couldn't stat ${\$self->path}: $!";
+  my $perms = $stat->mode & 07777;
+  my $new = $self->path.'.new';
+  unlink($new);
+  sysopen my $fh, $new, O_CREAT | O_WRONLY, $perms
+    or die "Couldn't open ${new}: $!";
+  print $fh $self->final_content
+    or die "Couldn't write data to ${new}: $!";
+  close $fh;
+  move($new, $self->path) or die "Couldn't install ${new}: $!";
+  return +(file_content => $self->from);
+}
 
 1;