create directory and create file, now with mode setting
[scpubgit/DKit.git] / lib / DX / Lib / FS / Action / CreateFile.pm
1 package DX::Lib::FS::Action::CreateFile;
2
3 use aliased 'DX::Lib::FS::Fact::PathStatus';
4 use aliased 'DX::Lib::FS::Fact::PathStatusInfo';
5 use POSIX ();
6 use Moo;
7
8 with 'DX::Role::Action';
9
10 has path => (is => 'ro', required => 1);
11
12 has mode => (is => 'ro', predicate => 1);
13
14 sub expected_effect {
15   my ($self) = @_;
16   return +(path_status => PathStatus->new(
17     path => $self->path,
18     info => PathStatusInfo->new(
19       is_file => 1,
20       mode => ($self->has_mode ? $self->mode : '')
21     )
22   ));
23 }
24
25 sub _do_run {
26   my ($self) = @_;
27   if ($self->has_mode) {
28     my $umask = umask(0000);
29     my $fd = POSIX::open(
30       $self->path, POSIX::O_CREAT | POSIX::O_RDONLY, oct($self->mode)
31     ) or do { umask($umask); die "Couldn't create ${\$self->path}: $!" };
32     POSIX::close($fd);
33     umask($umask);
34   } else {
35     open my $fh, '>>', $self->path or die "Couldn't create ${\$self->path}: $!";
36   }
37   +(path_status => PathStatus->new(path => $self->path));
38 }
39
40 1;