| 1 | package Sidef::Types::Glob::Pipe; | ||
| 2 | |||
| 3 | use utf8; | ||
| 4 | use 5.016; | ||
| 5 | |||
| 6 | use parent qw( | ||
| 7 | Sidef::Object::Object | ||
| 8 | ); | ||
| 9 | |||
| 10 | use overload q{""} => sub { | ||
| 11 | 'Pipe(' . join(', ', map { ${Sidef::Types::String::String->new("$_")->dump} } @{$_[0]}) . ')'; | ||
| 12 | }; | ||
| 13 | |||
| 14 | sub new { | ||
| 15 | my (undef, @command) = @_; | ||
| 16 | bless \@command, __PACKAGE__; | ||
| 17 | } | ||
| 18 | |||
| 19 | *call = \&new; | ||
| 20 | |||
| 21 | sub get_value { | ||
| 22 | join(' ', @{$_[0]}); | ||
| 23 | } | ||
| 24 | |||
| 25 | sub command { | ||
| 26 | my ($self) = @_; | ||
| 27 | @{$self} > 1 ? (@{$self}) : $self->[0]; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub open { | ||
| 31 | ref($_[0]) || shift(@_); | ||
| 32 | my ($self, $mode, $var_ref) = @_; | ||
| 33 | |||
| 34 | if (ref $mode) { | ||
| 35 | $mode = "$mode"; | ||
| 36 | } | ||
| 37 | |||
| 38 | my $pid = open(my $pipe_h, $mode, @{$self}); | ||
| 39 | my $pipe_obj = Sidef::Types::Glob::FileHandle->new($pipe_h, $self); | ||
| 40 | |||
| 41 | if (defined($var_ref)) { | ||
| 42 | ${$var_ref} = $pipe_obj; | ||
| 43 | |||
| 44 | return defined($pid) | ||
| 45 | ? Sidef::Types::Number::Number::_set_int($pid) | ||
| 46 | : undef; | ||
| 47 | } | ||
| 48 | |||
| 49 | defined($pid) ? $pipe_obj : undef; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub open_r { | ||
| 53 | ref($_[0]) || shift(@_); | ||
| 54 | my ($self, $var_ref) = @_; | ||
| 55 | $self->open('-|:utf8', $var_ref); | ||
| 56 | } | ||
| 57 | |||
| 58 | *open_read = \&open_r; | ||
| 59 | |||
| 60 | sub open_w { | ||
| 61 | ref($_[0]) || shift(@_); | ||
| 62 | my ($self, $var_ref) = @_; | ||
| 63 | $self->open('|-:utf8', $var_ref); | ||
| 64 | } | ||
| 65 | |||
| 66 | *open_write = \&open_w; | ||
| 67 | |||
| 68 | sub slurp { | ||
| 69 | ref($_[0]) || shift(@_); | ||
| 70 | my ($self) = @_; | ||
| 71 | my $fh = $self->open_r // return undef; | ||
| 72 | my $content = $fh->slurp; | ||
| 73 | $fh->close; | ||
| 74 | $content; | ||
| 75 | } | ||
| 76 | |||
| 77 | sub write_all { | ||
| 78 | ref($_[0]) || shift(@_); | ||
| 79 | my ($self, $data) = @_; | ||
| 80 | my $fh = $self->open_w // return undef; | ||
| 81 | $fh->print($data); | ||
| 82 | $fh->close; | ||
| 83 | Sidef::Types::Bool::Bool::TRUE; | ||
| 84 | } | ||
| 85 | |||
| 86 | sub dump { | ||
| 87 | my ($self) = @_; | ||
| 88 | Sidef::Types::String::String->new("$self"); | ||
| 89 | } | ||
| 90 | |||
| 91 | *to_s = \&dump; | ||
| 92 | *to_str = \&dump; | ||
| 93 | |||
| 94 | 1 |