blib/lib/PMLTQ/Command.pm

filter: Statementstmt 17.7% 40 / 225 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 26.8% 11 / 41 Podpod 0.0% 0 / 19 totaltotal 13.2% 51 / 384 CC 45 SCAR 35.2
CC
45
Cov
13%
run_sql_from_file
110.0
request
72.0
create_treebank_param
72.0
CRAP 33.7
« blib/lib/PMLTQ/Command/load.pm ↑ Summary blib/lib/PMLTQ/Command/verify.pm »
1 package PMLTQ::Command;
2 14 our $AUTHORITY = 'cpan:MATY';
3 14 $PMLTQ::Command::VERSION = '2.0.1';
4 # ABSTRACT: Command base class
5  
6 14 ▶use PMLTQ::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 14 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 14 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 ▶use File::Slurp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 14 ▶use Pod::Usage 'pod2usage';
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 14 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 14 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 14 ▶use HTTP::Cookies;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 14 ▶use URI::WithBase;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 14 ▶use URI::Encode qw(uri_encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 14 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 0 ▶has config => sub { die 'Command has no configuration'; };
Subroutine __ANON__: not called CC=1 SCAR=1.2
22  
23 0 ▶has usage => sub {'Usage: '};
Subroutine __ANON__: not called CC=1 SCAR=1.2
24  
25 has term => sub {
26 0 ▶ require Term::UI;
Subroutine __ANON__: not called CC=1 SCAR=6.9
27 0 require Term::ReadLine;
28 0 Term::ReadLine->new('pmltq');
29 14 };
30  
31 has term_encoding => sub {
32 0 ▶ require Term::Encoding;
Subroutine __ANON__: not called CC=1 SCAR=6.9
33 0 Term::Encoding::get_encoding();
34 14 };
35  
36 sub run {
37 0 ▶ die 'Override by parent class';
Subroutine run: not called CC=1 SCAR=6.9
Pod undocumented
38 }
39  
40 sub extract_usage {
41 0 ▶ my $self = shift;
Subroutine extract_usage: not called CC=1 SCAR=6.9
Pod undocumented
42  
43 0 open my $handle, '>', \my $output;
44 0 pod2usage( -exitval => 'NOEXIT', -input => (caller)[1], -output => $handle );
45 0 $output =~ s/\n$//;
46  
47 0 return $output;
48 }
49  
50 sub help {
51 0 ▶ print shift->usage;
Subroutine help: not called CC=1 SCAR=6.9
Pod undocumented
52 }
53  
54 sub _db_connect {
55 0 ▶ my ( $database, $host, $port, $user, $password ) = @_;
Subroutine _db_connect: not called CC=2 SCAR=17.9
56 0 ▶ my $dbh = DBI->connect( 'DBI:Pg:dbname=' . $database . ';host=' . $host . ';port=' . $port,
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = "DBI"->connect('DBI:Pg:dbname=' . $database . ';host=' . $host . ';port=' . $port, $user, $password, {"RaiseError", 1, "PrintError", 1}) or die "Unable to connect to database!\n$DBI::errstr\n" 0 0 0
57 $user, $password, { RaiseError => 1, PrintError => 1 } )
58 or die "Unable to connect to database!\n$DBI::errstr\n";
59 0 return $dbh;
60 }
61  
62 sub db {
63 0 ▶ my $self = shift;
Subroutine db: not called CC=1 SCAR=6.9
Pod undocumented
64  
65 0 my $db = $self->config->{db};
66 0 return _db_connect( $db->{name}, $db->{host}, $db->{port}, $db->{user}, $db->{password} );
67 }
68  
69 sub sys_db {
70 0 ▶ my $self = shift;
Subroutine sys_db: not called CC=3 SCAR=24.8
Pod undocumented
71  
72 0 my $config = $self->config;
73 0 my $db = $config->{db};
74 0 my $sys_db = $config->{sys_db};
75  
76 0 ▶ unless ( ref $sys_db ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $sys_db) 0 0 0
77 0 $sys_db = { name => $sys_db };
78 }
79  
80 0 $sys_db->{$_} = $db->{$_} for ( grep { !defined $sys_db->{$_} } qw/user password/ );
81  
82 0 return _db_connect( $sys_db->{name}, $db->{host}, $db->{port}, $sys_db->{user}, $sys_db->{password} );
83 }
84  
85 sub run_sql_from_file {
86 0 ▶ my ( $self, $file, $dir, $dbh ) = @_;
Subroutine run_sql_from_file: not called CC=10 SCAR=47.0
Pod undocumented
87  
88 0 my $sqlfile = File::Spec->catfile( $dir, $file );
89 0 my $sql = read_file($sqlfile);
90  
91 0 print STDERR "RUNNING SQL FROM $sqlfile\n";
92 0 ▶ if ( $file =~ m/.ctl/ and my $copy = () = $sql =~ m/(COPY .*? FROM *?["'].*?["'])/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /.ctl/ and my $copy = () = $sql =~ /(COPY .*? FROM *?["'].*?["'])/g) { } 0 0 0
Condition0%0/3
$file =~ /.ctl/ and my $copy = () = $sql =~ /(COPY .*? FROM *?["'].*?["'])/g
!ll&&!rl&&r
000
MC/DC0%0/2
$file =~ /.ctl/ and my $copy = () = $sql =~ /(COPY .*? FROM *?["'].*?["'])/g
$file =~ /.ctl/ my $copy = () = $sql =~ /(COPY .*? FROM *?["'].*?["'])/g
Truth table0%0/3
A and B
A= $file =~ /.ctl/B= my $copy = () = $sql =~ /(COPY .*? FROM *?["'].*?["'])/g
ABresult
0X0
100
111
93 0 ▶ die "More COPY commands than one in file is not supported.\n\n$sql\n" if $copy > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $copy > 1 0 0 0
94 0 $sql =~ s/(COPY .*? FROM) *?["'](.*?)["']/$1 STDIN/;
95 0 my $dump_file = File::Spec->catfile( $dir, $2 );
96 0 eval {
97 0 $dbh->do($sql);
98 0 ▶ open my $fh, '<', "$dump_file" or die "Can't open $dump_file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", "$dump_file" or die "Can't open ${dump_file}: $!" 0 0 0
99 0 ▶ while ( my $data = <$fh> ) { # Do not load whole file, but process it line by line
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $data = readline $fh)) 0 0 0
100 0 ▶ next unless $data;
Branch: 1 branch
BranchTrueFalseTotal
unless $data 0 0 0
101 0 $data= Encode::decode("UTF-8", $data, Encode::FB_CROAK);
102 0 $dbh->pg_putcopydata("$data");
103 }
104 0 $dbh->pg_putcopyend();
105 };
106 0 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
107 }
108 else {
109 0 my @statements = split /\n\n/, $sql;
110 0 for my $s (@statements) {
111 0 eval { $dbh->do($s); };
112 0 ▶ print STDERR "SQL FAILED:\t$s\n\t$@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
113 }
114 }
115 }
116  
117 # Borrowed from https://metacpan.org/release/Dist-Zilla
118 sub prompt_str {
119 0 ▶ my ( $self, $prompt, $arg ) = @_;
Subroutine prompt_str: not called CC=6 SCAR=37.4
Pod undocumented
120  
121 0 ▶ $arg ||= {};
Condition0%0/2
$arg ||= {}
l!l
00
MC/DC0%0/1
$arg ||= {}
$arg
Truth table0%0/2
A
A= $arg
Aresult
11
00
122 0 my $default = $arg->{default};
123 0 my $check = $arg->{check};
124  
125 0 require Encode;
126 0 my $term_encoding = $self->term_encoding;
127  
128 my $encode
129 = $term_encoding
130 0 ▶ ? sub { Encode::encode( $term_encoding, shift, Encode::FB_CROAK() ) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
131 0 ▶ : sub {shift};
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$term_encoding ? : 0 0 0
132 my $decode
133 = $term_encoding
134 0 ▶ ? sub { Encode::decode( $term_encoding, shift, Encode::FB_CROAK() ) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
135 0 ▶ : sub {shift};
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$term_encoding ? : 0 0 0
136  
137 my $input_bytes = $self->term->get_reply(
138 prompt => $encode->($prompt),
139 0 ▶ allow => $check || sub { defined $_[0] and length $_[0] },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and length $_[0] 0 0 0
140 0 ▶ ( defined $default
Branch: 1 branch
BranchTrueFalseTotal
defined $default ? : 0 0 0
Condition0%0/3
$check || sub { defined $_[0] and length $_[0]; }
l!l&&r!l&&!r
000
MC/DC0%0/2
$check || sub { defined $_[0] and length $_[0]; }
$check sub { defined $_[0] and length $_[0]; }
Truth table0%0/3
A || B
A= $checkB= sub { defined $_[0] and length $_[0]; }
ABresult
1X1
011
000
141 ? ( default => $encode->($default) )
142 : ()
143 ),
144 );
145  
146 0 my $input = $decode->($input_bytes);
147 0 chomp $input;
148  
149 0 return $input;
150 }
151  
152 sub prompt_yn {
153 0 ▶ my ( $self, $prompt, $arg ) = @_;
Subroutine prompt_yn: not called CC=3 SCAR=24.8
Pod undocumented
154 0 ▶ $arg ||= {};
Condition0%0/2
$arg ||= {}
l!l
00
MC/DC0%0/1
$arg ||= {}
$arg
Truth table0%0/2
A
A= $arg
Aresult
11
00
155 0 my $default = $arg->{default};
156  
157 0 ▶ my $input = $self->term->ask_yn(
Branch: 1 branch
BranchTrueFalseTotal
defined $default ? : 0 0 0
158 prompt => $prompt,
159 ( defined $default ? ( default => $default ) : () ),
160 );
161  
162 0 return $input;
163 }
164  
165 # WEB
166  
167 sub ua {
168 0 ▶ my $self = shift;
Subroutine ua: not called CC=2 SCAR=17.9
Pod undocumented
169 0 ▶ $self->{ua} = LWP::UserAgent->new() unless $self->{ua};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ua"} 0 0 0
170 0 return $self->{ua};
171 }
172  
173 sub login {
174 0 ▶ my ($self,$ua,$auth) = @_;
Subroutine login: not called CC=4 SCAR=30.0
Pod undocumented
175 0 ▶ my $url = URI::WithBase->new('/',$auth->{baseurl}||$self->config->{web_api}->{url});
Condition0%0/3
$auth->{'baseurl'} || $self->config->{'web_api'}{'url'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$auth->{'baseurl'} || $self->config->{'web_api'}{'url'}
$auth->{'baseurl'} $self->config->{'web_api'}{'url'}
Truth table0%0/3
A || B
A= $auth->{'baseurl'}B= $self->config->{'web_api'}{'url'}
ABresult
1X1
011
000
176 0 $url->path_segments('api','auth');
177  
178 0 ▶ my $res = $self->request($ua,'POST',$url->abs->as_string,{auth => {password => $auth->{password} || $self->config->{web_api}->{password}, username => $auth->{username} || $self->config->{web_api}->{user}}});
Condition0%0/6
$auth->{'password'} || $self->config->{'web_api'}{'password'}
l!l&&r!l&&!r
000
$auth->{'username'} || $self->config->{'web_api'}{'user'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$auth->{'password'} || $self->config->{'web_api'}{'password'}
$auth->{'password'} $self->config->{'web_api'}{'password'}
MC/DC0%0/2
$auth->{'username'} || $self->config->{'web_api'}{'user'}
$auth->{'username'} $self->config->{'web_api'}{'user'}
Truth table0%0/3
A || B
A= $auth->{'password'}B= $self->config->{'web_api'}{'password'}
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $auth->{'username'}B= $self->config->{'web_api'}{'user'}
ABresult
1X1
011
000
179 0 my $cookie_jar = HTTP::Cookies->new();
180 0 $cookie_jar->extract_cookies($res);
181 0 $ua->cookie_jar($cookie_jar);
182 }
183  
184 sub request {
185 0 ▶ my ($self,$ua,$method, $url,$data) = @_;
Subroutine request: not called CC=8 SCAR=42.8
Pod undocumented
186 0 my $JSON = JSON->new->utf8;
187 0 my $req = HTTP::Request->new( $method => $url );
188 0 $req->content_type('application/json;charset=UTF-8');
189 0 ▶ if($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 0 0 0
190 0 $data = $JSON->encode($data);
191 0 $data =~ s/"false"/false/g;
192 0 $data =~ s/"true"/true/g;
193 0 $req->content($data);
194 }
195 0 my $res = eval { $ua->request( $req ); };
196 0 ▶ confess($@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
197 0 ▶ unless ( $res->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 0 0 0
198 0 ▶ if($res->code() == 502) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->code == 502) { } 0 0 0
199 0 die "Error while executing query.\n";
200 } else {
201 0 die "Error reported by PML-TQ server:\n\n" . $res->content . "\n";
202 }
203 0 return;
204 }
205 0 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 0 0 0
206 0 ▶ return ($res,$res->decoded_content) unless $res->content_type eq 'application/json';
Branch: 1 branch
BranchTrueFalseTotal
unless $res->content_type eq "application/json" 0 0 0
207 0 my $json = $res->decoded_content;
208 0 ▶ return ($res,$json ? $JSON->decode($json) : undef);
Branch: 1 branch
BranchTrueFalseTotal
$json ? : 0 0 0
209 }
210 0 return $res;
211 }
212  
213 sub get_all_treebanks {
214 0 ▶ my ($self,$ua, $apiurl) = @_;
Subroutine get_all_treebanks: not called CC=3 SCAR=24.8
Pod undocumented
215 0 my $data;
216 0 ▶ my $url = URI::WithBase->new('/',$apiurl || $self->config->{web_api}->{url});
Condition0%0/3
$apiurl || $self->config->{'web_api'}{'url'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$apiurl || $self->config->{'web_api'}{'url'}
$apiurl $self->config->{'web_api'}{'url'}
Truth table0%0/3
A || B
A= $apiurlB= $self->config->{'web_api'}{'url'}
ABresult
1X1
011
000
217 0 $url->path_segments('api','admin', 'treebanks');
218 0 (undef,$data) = $self->request($ua,'GET',$url->abs->as_string);
219 0 ▶ return $data // [];
Condition0%0/2
$data // []
l!l
00
MC/DC0%0/1
$data // []
$data
Truth table0%0/2
A
A= $data
Aresult
11
00
220 }
221  
222 sub get_treebank {
223 0 ▶ my ($self,$ua) = @_;
Subroutine get_treebank: not called CC=1 SCAR=6.9
Pod undocumented
224 0 my ($treebank) = grep {$_->{name} eq $self->config->{treebank_id}} @{ $self->get_all_treebanks($ua)};
225 0 return $treebank;
226 }
227  
228 sub request_treebank {
229 0 ▶ my ($self,$treebank,$ua,$method,$data) = @_;
Subroutine request_treebank: not called CC=1 SCAR=6.9
Pod undocumented
230 0 my $url = URI::WithBase->new('/',$self->config->{web_api}->{url});
231 0 $url->path_segments('api','admin', 'treebanks',$treebank->{id});
232 0 (undef,$data) = $self->request($ua,$method,$url->abs->as_string,$data);
233 }
234  
235 sub create_treebank_param {
236 0 ▶ my ($self) = @_;
Subroutine create_treebank_param: not called CC=8 SCAR=42.8
Pod undocumented
237 0 my (@langs,@tags,@server);
238 0 my @searches = (
239 {
240 results => \@langs,
241 configpath => ['languages'],
242 api => 'languages',
243 compare => 'code',
244 error => "Unknown language code '\%s'\n",
245 min => 0
246 },
247 {
248 results => \@tags,
249 configpath => ['tags'],
250 api => 'tags',
251 compare => 'name',
252 error => "Unknown tag '\%s'\n",
253 min => 0
254 },
255 {
256 results => \@server,
257 configpath => ['web_api','dbserver'],
258 api => 'servers',
259 compare => 'name',
260 no_url_filter => 1,
261 error => "Unknown server name '\%s'\n",
262 min => 1
263 },
264 );
265 0 for my $search (@searches) {
266 0 my $config_values = $self->config;
267 0 for my $path (@{$search->{configpath}}) {
268 0 $config_values = $config_values->{$path};
269 }
270 0 ▶ $config_values = $config_values ? (ref $config_values ? $config_values : [$config_values] ) : [];
Branch: 2 branches
BranchTrueFalseTotal
$config_values ? : 0 0 0
ref $config_values ? : 0 0 0
271 0 for my $text (@{$config_values}) {
272 0 my $res = $self->_search_param($text,$search);
273 0 ▶ if($res) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res) { } 0 0 0
274 0 push @{$search->{results}}, $res->{id};
275 } else {
276 0 die "ERROR: " . sprintf($search->{error},$text);
277 }
278 }
279 0 ▶ die "ERROR: " . $search->{min} . " " . join("-",@{$search->{configpath}}) . " is required\n" unless @{$search->{results}} >= $search->{min} ;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$search->{"results"};} >= $search->{"min"} 0 0 0
280 }
281  
282 return {
283 title => $self->config->{title},
284 name => $self->config->{treebank_id},
285 homepage => $self->config->{homepage},
286 description => $self->config->{description},
287 manuals => $self->config->{manuals},
288 0 dataSources => [map { {layer => $_->{name},path => $_->{path} } }@{$self->config->{layers}}],
289 tags => \@tags,
290 languages => \@langs,
291 serverId => $server[0],
292 database => $self->config->{db}->{name},
293 isFree => $self->config->{isFree},
294 isAllLogged => $self->config->{isAllLogged},
295 isPublic => $self->config->{isPublic},
296 isFeatured => $self->config->{isFeatured},
297 }
298 0 }
299  
300 sub _search_param {
301 0 ▶ my $self = shift;
Subroutine _search_param: not called CC=2 SCAR=17.9
302 0 my $text = shift;
303 0 my $opts = shift;
304 0 my $url = URI::WithBase->new('/',$self->config->{web_api}->{url});
305 0 $url->path_segments('api', 'admin', $opts->{api});
306 0 my $data;
307 0 ▶ (undef,$data) = $self->request($self->{ua}, 'GET', $url->abs->as_string.($opts->{no_url_filter} ? '' : "?filter=".URI::Encode::uri_encode("{\"q\":\"$text\"}")), {});
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'no_url_filter'} ? : 0 0 0
308 0 my ($res) = grep {$_->{$opts->{compare}} eq $text } @$data;
309 0 return $res;
310 }
311  
312  
313 sub evaluate_query {
314 0 ▶ my ($self,$tb_id,$query) = @_;
Subroutine evaluate_query: not called CC=4 SCAR=30.0
Pod undocumented
315 0 my $url = URI::WithBase->new('/',$self->config->{web_api}->{url});
316 0 $url->path_segments('api', 'treebanks', $tb_id, 'query');
317 0 my $data;
318 0 (undef,$data) = $self->request($self->{ua}, 'POST', $url->abs->as_string, {filter => "true", limit => 100, query => $query, timeout => 30});
319 0 my $result = '';
320 0 ▶ unless($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) { } 0 0 0
321 0 print STDERR "Error while executing query: $query\n";
322 } else {
323 0 my $results = $data->{results};
324 0 ▶ if(@$results) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$results) { } 0 0 0
325 0 ▶ if($data->{nodes}) { # tree result
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{'nodes'}) { } 0 0 0
326 0 $url = URI::WithBase->new('/',$self->config->{web_api}->{url});
327 0 $url->path_segments('api', 'treebanks', $tb_id, 'svg');
328 0 (undef,$result) = $self->request($self->{ua}, 'POST', $url->abs->as_string, {nodes => $results->[0], tree => 0});
329 } else { # filter result
330 0 $result = join("\n",map {join("\t",@$_)} @$results) . "\n";
331 }
332 } else {
333 0 print STDERR "Empty result for: $query\n";
334 }
335 }
336 0 return $result;
337 }
338  
339 sub user2admin_format { # converts getted treebank json to treebank configuration format
340 0 ▶ my ($self, $treebank) = @_;
Subroutine user2admin_format: not called CC=1 SCAR=6.9
Pod undocumented
341 return {
342 id => $treebank->{name},
343 0 tags => [map {$_->{name}} @{$treebank->{tags}}],
344 language => $treebank->{languages}->[0]->{code},
345 0 map {$_ => $treebank->{$_}} qw/title isFree isAllLogged isFeatured isPublic homepage description documentation dataSources manuals/
346 }
347 }
348  
349  
350 sub get_nodetypes {
351 0 ▶ my ($self, $treebank) = @_;
Subroutine get_nodetypes: not called CC=1 SCAR=6.9
Pod undocumented
352 0 my $url = URI::WithBase->new('/',$self->config->{web_api}->{url});
353 0 $url->path_segments('api', 'treebanks', $treebank->{name}, 'node-types');
354 0 my $data;
355 0 (undef,$data) = $self->request($self->{ua}, 'GET', $url->abs->as_string);
356 return $data->{types}
357 0 }
358  
359 sub get_test_queries {
360 0 ▶ my ($self, $treebank) = @_;
Subroutine get_test_queries: not called CC=1 SCAR=6.9
Pod undocumented
361 # get node types
362 0 my ($type) = @{$self->get_nodetypes($treebank)};
363 0 return [{filename=>"$type.svg", query => "$type [];"}, {filename=>"${type}_count.txt", query => "$type []; >> count()"}]
364 }
365  
366 14 1;
« blib/lib/PMLTQ/Command/load.pm ↑ Summary blib/lib/PMLTQ/Command/verify.pm »