create directory and create file, now with mode setting
[scpubgit/DKit.git] / lib / DX / Lib / FS / Action / CreateFile.pm
index 80379e3..feed8f7 100644 (file)
@@ -2,23 +2,38 @@ package DX::Lib::FS::Action::CreateFile;
 
 use aliased 'DX::Lib::FS::Fact::PathStatus';
 use aliased 'DX::Lib::FS::Fact::PathStatusInfo';
+use POSIX ();
 use Moo;
 
 with 'DX::Role::Action';
 
 has path => (is => 'ro', required => 1);
 
+has mode => (is => 'ro', predicate => 1);
+
 sub expected_effect {
   my ($self) = @_;
   return +(path_status => PathStatus->new(
     path => $self->path,
-    info => PathStatusInfo->new(is_file => 1, mode => '')
+    info => PathStatusInfo->new(
+      is_file => 1,
+      mode => ($self->has_mode ? $self->mode : '')
+    )
   ));
 }
 
 sub _do_run {
   my ($self) = @_;
-  open my $fh, '>>', $self->path or die "Couldn't create ${\$self->path}: $!";
+  if ($self->has_mode) {
+    my $umask = umask(0000);
+    my $fd = POSIX::open(
+      $self->path, POSIX::O_CREAT | POSIX::O_RDONLY, oct($self->mode)
+    ) or do { umask($umask); die "Couldn't create ${\$self->path}: $!" };
+    POSIX::close($fd);
+    umask($umask);
+  } else {
+    open my $fh, '>>', $self->path or die "Couldn't create ${\$self->path}: $!";
+  }
   +(path_status => PathStatus->new(path => $self->path));
 }