blib/lib/App/DuckPAN/Fathead.pm

filter: Statementstmt 23.2% 30 / 129 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 38.8% 7 / 18 Podpod 0.0% 0 / 1 totaltotal 19.8% 37 / 186 CC 19 SCAR 25.9
CC
19
Cov
18%
_build_structured_answer
42.0
_trigger_selected
12.0
_build__trigger_words
12.0
CRAP 13.3
« blib/lib/App/DuckPAN/Cmd/Installdeps.pm ↑ Summary blib/lib/App/DuckPAN/Query.pm »
1 package App::DuckPAN::Fathead;
2 1 our $AUTHORITY = 'cpan:DDG';
3 # ABSTRACT: Searches a given output.txt file for a query match
4 1 $App::DuckPAN::Fathead::VERSION = '1021';
5 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 with 'App::DuckPAN::HasApp';
7  
8 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use HTML::TreeBuilder;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use HTML::Element;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Data::Printer return_value => 'dump';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 1 has selected => (
16 is => 'rw',
17 lazy => 1,
18 required => 0,
19 predicate => 1,
20 trigger => 1
21 );
22  
23 0 ▶sub _trigger_selected {
Subroutine _trigger_selected: not called CC=3 SCAR=24.8
24 0 my ( $self, $id ) = @_;
25 0 my $dir = path("lib/fathead/$id");
26 0 ▶ unless ($dir->is_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dir->is_dir) 0 0 0
27 0 my $full_path = $dir->realpath;
28 0 $self->app->emit_and_exit(1, "Directory not found: $full_path") ;
29 }
30 0 my $file = $dir->child("output.txt");
31 0 ▶ unless ($file->exists){
Branch: 1 branch
BranchTrueFalseTotal
unless ($file->exists) 0 0 0
32 0 my $full_path = $file->realpath;
33 0 $self->app->emit_and_exit(1, "No output.txt was found in $full_path");
34 }
35 0 $self->_set_output_txt($file);
36 0 return $dir;
37 }
38  
39 1 has _trigger_words => (
40 is => 'ro',
41 builder => 1,
42 lazy => 1,
43 );
44  
45 0 ▶sub _build__trigger_words {
Subroutine _build__trigger_words: not called CC=3 SCAR=24.8
46 0 my ($self) = @_;
47 0 my $tf = 'trigger_words.txt';
48 0 ▶ return [] unless $self->has_selected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_selected 0 0 0
49 0 my $file = path("lib/fathead/", $self->selected, $tf);
50 0 ▶ unless ($file->exists){
Branch: 1 branch
BranchTrueFalseTotal
unless ($file->exists) 0 0 0
51 0 my $full_path = $file->realpath;
52 0 $self->app->emit_debug("No $tf was found in $full_path");
53 0 return [];
54 }
55 0 chomp (my @words = $file->lines);
56 0 return \@words;
57 }
58  
59 1 has _trigger_re => (
60 is => 'ro',
61 lazy => 1,
62 builder => 1,
63 );
64  
65 0 ▶sub _build__trigger_re {
Subroutine _build__trigger_re: not called CC=1 SCAR=6.9
66 0 my ($self) = @_;
67 0 my @words = @{$self->_trigger_words};
68 0 my $text = join '|', map { quotemeta $_ } @words;
69 0 return qr/\b(?:$text)\b/i;
70 }
71  
72 1 has output_txt => (
73 is => 'rwp',
74 lazy => 1,
75 required => 0
76 );
77  
78 1 has dbh => (
79 is => 'rw',
80 lazy => 1,
81 required => 0,
82 builder => 1
83 );
84  
85 0 ▶sub _build_dbh {
Subroutine _build_dbh: not called CC=2 SCAR=17.9
86 0 my ( $self ) = @_;
87  
88 # Open output.txt file for searching
89 # Handles as a CSV with "\t" separator
90 # Provide numbered column names
91 0 ▶ my $dbh = DBI->connect ("dbi:CSV:", undef, undef, {
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = "DBI"->connect("dbi:CSV:", undef, undef, {"f_dir", $self->output_txt->parent, "f_ext", ".txt/r", "csv_sep_char", "\t", "csv_quote_char", undef, "csv_escape_char", undef, "csv_allow_whitespace", 1, "csv_allow_quotes", 1, "RaiseError", 1, "PrintError", 0, "csv_tables", {"output", {"file", "output.txt", "col_names", ["title", "type", "redirect", "col4", "categories", "col6", "related_topics", "col8", "external_links", "disambiguation", "images", "abstract", "abstract_url"]}}}) or die $DBI::errstr 0 0 0
92 f_dir => $self->output_txt->parent,
93 f_ext => ".txt/r",
94 csv_sep_char => "\t",
95 csv_quote_char => undef,
96 csv_escape_char => undef,
97 csv_allow_whitespace => 1,
98 csv_allow_quotes => 1,
99 RaiseError => 1,
100 PrintError => 0,
101 csv_tables => {
102 output => {
103 file => 'output.txt',
104 col_names => [
105 "title",
106 "type",
107 "redirect",
108 "col4",
109 "categories",
110 "col6",
111 "related_topics",
112 "col8",
113 "external_links",
114 "disambiguation",
115 "images",
116 "abstract",
117 "abstract_url",
118 ],
119 },
120 },
121 }) or die $DBI::errstr;
122  
123 0 return $dbh;
124 }
125  
126 # Get a Fathead result from the DB
127 # Requery when we get a Redirect
128 0 ▶sub _search_output {
Subroutine _search_output: not called CC=3 SCAR=24.8
129  
130 0 my ($self, $query) = @_;
131  
132 0 my $trigger_re = $self->_trigger_re;
133 0 $query =~ s/^$trigger_re\s+|\s+$trigger_re$//;
134 0 my $result = $self->_db_lookup($query);
135  
136 0 ▶ while ($result && $result->{type} eq 'R') {
Branch: 1 branch
BranchTrueFalseTotal
if ($result and $result->{"type"} eq "R") 0 0 0
Condition0%0/3
$result and $result->{"type"} eq "R"
!ll&&!rl&&r
000
MC/DC0%0/2
$result and $result->{"type"} eq "R"
$result $result->{"type"} eq "R"
Truth table0%0/3
A and B
A= $resultB= $result->{"type"} eq "R"
ABresult
0X0
100
111
137 0 my $redirect = $result->{redirect};
138 0 $self->app->emit_notice("Following Redirect: '$result->{title}' -> '$redirect'");
139 0 $result = $self->_db_lookup($redirect);
140 }
141 0 return $result;
142 }
143  
144 # Attempt to get a result from DB (output.txt)
145 # Capture & display any raised errors
146 0 ▶sub _db_lookup {
Subroutine _db_lookup: not called CC=3 SCAR=24.8
147 0 my ($self, $query) = @_;
148  
149 0 my $result;
150 0 $@ = '';
151  
152 0 eval {
153 # TODO lowercase all titles first
154 0 my $sth = $self->dbh->prepare("SELECT * FROM output WHERE lower(title) = ?");
155 0 $sth->execute(lc $query);
156 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
157 0 $result = $row;
158 }
159 0 $sth->finish();
160 };
161 0 ▶ $self->app->emit_error("SQL database error: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
162 0 return $result;
163 }
164  
165 0 ▶sub structured_answer_for_query {
Subroutine structured_answer_for_query: not called CC=2 SCAR=17.9
Pod undocumented
166 0 my ($self, $query) = @_;
167 0 ▶ my $result = $self->_search_output($query) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $result = $self->_search_output($query) or return undef 0 0 0
168 0 return $self->_build_structured_answer($result);
169 }
170  
171 # Build a Structured Answer hash
172 # Properties depend on Fathead result type
173 0 ▶sub _build_structured_answer {
Subroutine _build_structured_answer: not called CC=6 SCAR=37.4
174 0 my ($self, $data) = @_;
175  
176 # Get IA Metadata via ID lookup
177 # Assume selected is an ID
178 0 ▶ my $metadata = DDG::Meta::Data->get_ia(id => $self->selected) // {};
Condition0%0/2
"DDG::Meta::Data"->get_ia("id", $self->selected) // {}
l!l
00
MC/DC0%0/1
"DDG::Meta::Data"->get_ia("id", $self->selected) // {}
"DDG::Meta::Data"->get_ia("id", $self->selected)
Truth table0%0/2
A
A= "DDG::Meta::Data"->get_ia("id", $self->selected)
Aresult
11
00
179 0 ▶ $self->app->emit_error("No Metadata found for ID: ".$self->selected) unless keys %$metadata;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$metadata 0 0 0
180  
181 # DBD::Csv ignores col_names letter casing
182 # So, manually map columns to template properties
183 # TODO update info_detail template to use lowercase variable names
184 0 my %extra_data;
185  
186 0 my $out = {
187 id => $self->selected,
188 signal => "high",
189 meta => $metadata,
190 };
191  
192 # Article Result
193 0 ▶ if ($data->{type} eq 'A') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"type"} eq "A") 0 0 0
194 0 $out->{duckbar_topic} = 'About';
195 0 $out->{model} = 'FatheadArticle';
196 0 $out->{templates} = { detail => 'info_detail' };
197 %extra_data = (
198 Heading => $data->{title},
199 Abstract => $self->_replace_newlines($data->{abstract}),
200 AbstractURL => $data->{abstract_url},
201 FirstURL => $metadata->{src_url},
202 0 Image => $self->_get_image($data->{images}),
203 );
204 }
205  
206 # Disambiguation Result
207 0 ▶ if ($data->{type} eq 'D') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"type"} eq "D") 0 0 0
208 0 $out->{duckbar_topic} = 'Meanings';
209 0 $out->{model} = 'FatheadListItem';
210 0 $out->{templates} = { item => 'meanings_item' };
211 %extra_data = (
212 Heading => $data->{title}." (".$metadata->{name}.")",
213 0 RelatedTopics => $self->_parse_disambiguations($data->{disambiguation}, $out)
214 );
215 }
216  
217 # Category Pages Result
218 0 ▶ if ($data->{type} eq 'C') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"type"} eq "C") 0 0 0
219 0 $out->{duckbar_topic} = 'List';
220 0 $out->{model} = 'FatheadListItem';
221 0 $out->{templates} = { item => 'categories_item' };
222 }
223  
224 0 $out->{data} = { %$data, %extra_data };
225 0 return $out;
226 }
227  
228 # Emulate internal processing to build JSON
229 # matching DDG API result format
230 0 ▶sub _parse_disambiguations {
Subroutine _parse_disambiguations: not called CC=3 SCAR=24.8
231 0 my ($self, $disambiguations, $out) = @_;
232 0 my @out;
233 0 my @disambiguations = split /\\n/, $disambiguations;
234 0 foreach my $disambiguation (@disambiguations){
235 0 my $result = {};
236 0 ▶ if ($disambiguation =~ m/^\*\[\[(.+)\]\],(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disambiguation =~ /^\*\[\[(.+)\]\],(.+)$/) 0 0 0
237  
238 0 my $title = $1;
239 0 my $html = $2;
240  
241 # Parse HTML into plaintext
242 0 my $root = HTML::TreeBuilder->new_from_content($html);
243 0 $root->elementify();
244 0 my $text = $root->as_trimmed_text;
245  
246 # Build URL Path
247 0 my $href = "/?q=$title&ia=about";
248 0 my $a = HTML::Element->new('a', href => $href);
249 0 $a->push_content($title);
250  
251 0 $result = {
252 Result => $a->as_HTML . "$text", # generates `<a href="$url">$title</a>$text` which gets parsed by template helpers
253 FirstURL => $href,
254 Text => $text
255 };
256 }
257 0 push @out, $result;
258 }
259 0 return \@out;
260 }
261  
262 # Emulate internal processing to build JSON
263 # matching DDG API result format
264 0 ▶sub _get_image {
Subroutine _get_image: not called CC=2 SCAR=17.9
265 0 my ($self, $image) = @_;
266 0 my $url = "";
267 0 ▶ if ($image =~ m/^\[\[Image:(.+)\]\]$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($image =~ /^\[\[Image:(.+)\]\]$/) 0 0 0
268 0 $url = $1;
269 }
270 0 return $url;
271 }
272  
273  
274 0 ▶sub _replace_newlines {
Subroutine _replace_newlines: not called CC=1 SCAR=6.9
275 0 my ($self, $abstract) = @_;
276 0 $abstract =~ s/\\n/<br>/g;
277 0 return $abstract;
278 }
279  
280  
281 1 1;
282  
283 __END__
« blib/lib/App/DuckPAN/Cmd/Installdeps.pm ↑ Summary blib/lib/App/DuckPAN/Query.pm »