File Coverage

blib/lib/Tak/CommandService.pm
Criterion Covered Total %
statement 15 39 38.4
branch 0 10 0.0
condition n/a
subroutine 5 11 45.4
pod 0 2 0.0
total 20 62 32.2


line stmt bran cond sub pod time code
1             package Tak::CommandService;
2              
3 1     1   120877 use Capture::Tiny qw(capture);
  1         19637  
  1         83  
4 1     1   1226 use IPC::System::Simple qw(runx EXIT_ANY);
  1         15940  
  1         74  
5 1     1   789 use IPC::Open3;
  1         2608  
  1         45  
6 1     1   6 use Symbol qw(gensym);
  1         2  
  1         28  
7 1     1   5 use Moo;
  1         2  
  1         9  
8              
9             with 'Tak::Role::Service';
10              
11             sub handle_exec {
12 0     0 0   my ($self, $command) = @_;
13 0           my $code;
14             my ($stdout, $stderr) = capture {
15 0     0     $code = runx(EXIT_ANY, @$command);
16 0           };
17 0           return { stdout => $stdout, stderr => $stderr, exit_code => $code };
18             }
19              
20             sub start_stream_exec_request {
21 0     0 0   my ($self, $req, $command) = @_;
22 0           my $err = gensym;
23 0 0         my $pid = open3(my $in, my $out, $err, @$command)
24             or return $req->failure("Couldn't spawn process: $!");
25 0           close($in); # bye
26             my $done = sub {
27             Tak->loop->unwatch_io(handle => $_, on_read_ready => 1)
28 0     0     for ($out, $err);
29 0           waitpid($pid, 0);
30 0           $req->success({ exit_code => $? });
31 0           };
32 0           my $outbuf = '';
33 0           my $errbuf = '';
34             Tak->loop->watch_io(
35             handle => $out,
36             on_read_ready => sub {
37 0 0   0     if (sysread($out, $outbuf, 1024, length($outbuf)) > 0) {
38 0           $req->progress(stdout => $1) while $outbuf =~ s/^(.*)\n//;
39             } else {
40 0 0         $req->progress(stdout => $outbuf) if $outbuf;
41 0 0         $req->progress(stderr => $errbuf) if $errbuf;
42 0           $done->();
43             }
44             }
45 0           );
46             Tak->loop->watch_io(
47             handle => $err,
48             on_read_ready => sub {
49 0 0   0     if (sysread($err, $errbuf, 1024, length($errbuf)) > 0) {
50 0           $req->progress(stderr => $1) while $errbuf =~ s/^(.*)\n//;
51             }
52             }
53 0           );
54             }
55              
56             1;