CSE/Command/Search.pm untested

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 292 CC 20 SCAR 24.4
CC
20
Cov
0%
execute
42.0
_build_sort_spec
20.0
_build_query
20.0
CRAP 11.5
1 package App::CSE::Command::Search;
2 $App::CSE::Command::Search::VERSION = '0.016';
3 use Moose;
4 extends qw/App::CSE::Command/;
5  
6 use App::CSE::Command::Check;
7 use App::CSE::Command::Index;
8 use App::CSE::Lucy::Highlight::Highlighter;
9 use App::CSE::Lucy::Search::QueryPrefix;
10 use DateTime;
11 use File::Find;
12 use File::MimeInfo::Magic;
13 use Log::Log4perl;
14 use Lucy::Analysis::RegexTokenizer;
15 use Lucy::Search::Hits;
16 use Lucy::Search::IndexSearcher;
17 use App::CSE::Lucy::Search::QueryParser;
18 use Lucy::Search::SortSpec;
19 use Lucy::Search::SortRule;
20 use Path::Class::Dir;
21 use Time::HiRes;
22  
23 my $LOGGER = Log::Log4perl->get_logger();
24  
25 # Parameter stuff
26  
27 # Inputs
28 has 'query_str' => ( is => 'ro' , isa => 'Str' , lazy_build => 1);
29 has 'dir_str' => ( is => 'ro' , isa => 'Maybe[Str]', lazy_build => 1);
30 has 'num' => ( is => 'ro' , isa => 'Int', lazy_build => 1);
31 has 'offset' => ( is => 'ro' , isa => 'Int' , lazy_build => 1);
32 has 'sort_str' => ( is => 'ro' , isa => 'Str' , lazy_build => 1);
33  
34 # Calculated
35 has 'filtered_query' => ( is => 'ro' , isa => 'Lucy::Search::Query' , lazy_build => 1);
36 has 'query' => ( is => 'ro', isa => 'Lucy::Search::Query' , lazy_build => 1);
37 has 'sort_spec' => ( is => 'ro' , isa => 'Lucy::Search::SortSpec', lazy_build => 1);
38  
39 # Operational stuff.
40 has 'hits' => ( is => 'ro', isa => 'Lucy::Search::Hits', lazy_build => 1);
41 has 'searcher' => ( is => 'ro' , isa => 'Lucy::Search::IndexSearcher' , lazy_build => 1);
42 has 'highlighter' => ( is => 'ro' , isa => 'App::CSE::Lucy::Highlight::Highlighter' , lazy_build => 1);
43  
44 sub _build_sort_spec{
45 my ($self) = @_;
46  
47 my @rules = ( Lucy::Search::SortRule->new( type => 'score'),
48 Lucy::Search::SortRule->new( field => 'path' )
49 );
50 if( $self->sort_str() eq 'score' ){
51 # Nothing to do.
52 1;
53 }elsif( $self->sort_str() eq 'path' ){
54 @rules = (
55 Lucy::Search::SortRule->new( field => 'path' ),
56 Lucy::Search::SortRule->new( type => 'score'),
57 );
58 }elsif( $self->sort_str() eq 'mtime' ){
59 @rules = (
60 Lucy::Search::SortRule->new( field => 'mtime' , reverse => 'true' ),
61 Lucy::Search::SortRule->new( field => 'path' ),
62 );
63 }else{
64 $LOGGER->error($self->cse->colorizer->colored("Unknown sort mode ".$self->sort_str().". Falling back to 'score'", 'red bold'));
65 }
66  
67 return Lucy::Search::SortSpec->new(rules => \@rules );
68 }
69  
70  
71 sub _build_highlighter{
72 my ($self) = @_;
73  
74 ## Note that this only builds a content highlighter.
75  
76 $LOGGER->debug("Using highlight_query = ".$self->highlight_query('content')->to_string());
77 return App::CSE::Lucy::Highlight::Highlighter->new(
78 searcher => $self->searcher(),
79 query => $self->highlight_query(),
80 field => 'content',
81 excerpt_length => 100,
82 cse_command => $self,
83 );
84 }
85  
86 =head2 highlight_query
87  
88 Returns the query used to highlight the given field. Will be the original
89 query or the highlight query of the query prefix.
90  
91 Usage:
92  
93 my $hl_query = $this->highlight_query('content');
94  
95 =cut
96  
97 sub highlight_query{
98 my ($self, $field) = @_;
99 my $query = $self->query();
100 if( $query->isa('App::CSE::Lucy::Search::QueryPrefix') ){
101 return $query->highlight_query($field || 'content');
102 }
103 return $query;
104 }
105  
106 sub _build_searcher{
107 my ($self) = @_;
108 my $searcher = Lucy::Search::IndexSearcher->new( index => $self->cse->index_dir().'' );
109 return $searcher;
110 }
111  
112 sub options_specs{
113 return [ 'offset|o=i', 'num|n=i', 'sort|s=s' , 'reverse|r' ];
114 }
115  
116 my %legit_sort = ( 'score' => 1, 'path' => 1 , 'mtime' => 1 );
117  
118 sub _build_sort_str{
119 my ($self) = @_;
120 my $sort_str = $self->cse()->options()->{sort} || 'score';
121 unless( $legit_sort{$sort_str} ){
122 $LOGGER->error($self->cse->colorizer->colored("Unknown sort mode ".$sort_str.". Falling back to 'score'", 'red bold'));
123 return 'score';
124 }
125  
126 my $perl_version = $];
127 if( $perl_version >= 5.016 && $sort_str ne 'score' ){
128 $LOGGER->warn($self->cse->colorizer->colored("A bug in Lucy doesn't allow this version of Perl($perl_version) to take sort mode (".$sort_str.") into account for now.", 'yellow bold'));
129 return 'score'
130 }
131  
132  
133 return $sort_str;
134 }
135  
136 sub _build_offset{
137 my ($self) = @_;
138 return $self->cse()->options->{offset} || 0;
139 }
140  
141 sub _build_num{
142 my ($self) = @_;
143 my $num = $self->cse->options()->{num};
144 return defined($num) ? $num : 5;
145 }
146  
147 sub _build_hits{
148 my ($self) = @_;
149  
150 $LOGGER->info("Searching for '".$self->filtered_query()->to_string()."'");
151  
152  
153 {
154 my $this_version = $self->cse()->version();
155 my $index_version = $self->cse->index_meta->{version};
156 unless( $this_version eq $index_version ){
157 $LOGGER->warn($self->cse()->colorizer->colored("Index version is too old ($index_version) for this program ($this_version). Please consider re-indexing", 'yellow bold'));
158 }
159 }
160  
161 my $perl_version = $];
162  
163 my $hits = $self->searcher->hits( query => $self->filtered_query(),
164 offset => $self->offset(),
165 num_wanted => $self->num(),
166 ## This segfaults on perl 16 and 18 :(
167 ( $perl_version < 5.016 ) ? ( sort_spec => $self->sort_spec() ) : ()
168 );
169 return $hits;
170 }
171  
172 sub _build_query_str{
173 my ($self) = @_;
174  
175 my @str_bits = @{ $self->cse()->args() };
176 return join(' ', @str_bits);
177 }
178  
179 sub _build_dir_str{
180 my ($self) = @_;
181 # Give a chance to query STR.
182 # Dir candidates?
183 my @dirs = grep{ $_ =~ /^\W/ } @{ $self->cse()->args() };
184 if( $dirs[0] && -d $dirs[0] ){
185 return $dirs[0];
186 }
187 return undef;
188 }
189  
190 sub _build_filtered_query{
191 my ($self) = @_;
192 if( my $dir_str = $self->dir_str() ){
193 # Filter the query with a filter on this dir as a prefix.
194 my $fq = Lucy::Search::ANDQuery->new();
195 $fq->add_child($self->query());
196 $fq->add_child(App::CSE::Lucy::Search::QueryPrefix->new( field => 'path.raw',
197 query_string => $dir_str.'*',
198 keep_case => 1
199 )
200 );
201 return $fq;
202 }
203  
204 # General case. Same as the original query.
205 return $self->query();
206 }
207  
208 sub _build_query{
209 my ($self) = @_;
210  
211 # if( $self->query_str() =~ /\*$/ ){
212 # return App::CSE::Lucy::Search::QueryPrefix->new(
213 # field => 'content',
214 # query_string => $self->query_str(),
215 # );
216 # }
217  
218 my $analyzer;
219 my $fields = [ 'content' , 'decl', 'call', 'path' ];
220  
221 if( $self->query_str() =~ /\*/ ){
222 # Let the query parser keep the *'s
223 $analyzer = Lucy::Analysis::RegexTokenizer->new( pattern => '\S+' );
224 unless( $self->query_str() =~ /\:/ ){
225 # No colon. Search only in content
226 $fields = [ 'content' ];
227 }
228 }
229  
230 my $qp = App::CSE::Lucy::Search::QueryParser->new( schema => $self->searcher->get_schema,
231 default_boolop => 'AND',
232 fields => $fields,
233 $analyzer ? ( analyzer => $analyzer ) : (),
234 );
235 $qp->set_heed_colons(1);
236  
237 return $qp->parse($self->query_str());
238 }
239  
240 sub execute{
241 my ($self) = @_;
242  
243 my $colorizer = $self->cse->colorizer();
244 my $colored = sub{ $colorizer->colored(@_); };
245  
246 unless( $self->query_str() ){
247 $LOGGER->warn(&$colored("Missing query. Do cse help" , 'red'));
248 return 1;
249 }
250  
251 # Check the index.
252 my $check = App::CSE::Command::Check->new({ cse => $self->cse() });
253 if( $check->execute() ){
254 $LOGGER->info(&$colored("Rebuilding the index..", 'green bold'));
255 my $index_cmd = App::CSE::Command::Index->new( { cse => $self->cse() });
256 if( $index_cmd->execute() ){
257 $LOGGER->error(&$colored("Building index failed", 'red'));
258 return 1;
259 }
260 }
261 my $start_time = Time::HiRes::time();
262  
263 ## This will trigger a search. Look at _build_hits
264 my $hits = $self->hits();
265  
266 my $highlighter = $self->highlighter();
267  
268 $LOGGER->info(&$colored('Hits: '. $self->offset().' - '.( $self->offset() + $self->num() - 1).' of '.$hits->total_hits().' sorted by '.$self->sort_str(), 'green bold')."\n\n");
269  
270 while ( my $hit = $hits->next ) {
271  
272 my $excerpt = $highlighter->create_excerpt($hit);
273  
274 my $star = '';
275 if( my $stat = File::stat::stat( $hit->{path} ) ){
276 if( $hit->{mtime} lt DateTime->from_epoch(epoch => $stat->mtime())->iso8601() ){
277 $star = &$colored('*' , 'red bold');
278 # Mark the file as dirty.
279 $self->cse()->dirty_files()->{$hit->{'path.raw'}} = 1;
280 }
281 }else{
282 # No stat. File is gone (consider dirty)
283 $star = &$colored('-' , 'red bold');
284 $self->cse()->dirty_files()->{$hit->{'path.raw'}} = 1;
285 }
286  
287 $LOGGER->trace("Score: ".$hit->get_score());
288  
289 my $hit_str = &$colored($hit->{path}.'', 'magenta bold').' ('.$hit->{mime}.') ['.$hit->{mtime}.$star.']'.&$colored(':', 'cyan bold');
290 $hit_str .= q|
291 |.( $excerpt || substr($hit->{content} || '' , 0 , 100 ) ).q|
292  
293 |;
294  
295  
296 $LOGGER->info($hit_str);
297 }
298  
299 my $stop_time = Time::HiRes::time();
300  
301 # Save the dirty files memory.
302 $self->cse()->save_dirty_files();
303  
304 $LOGGER->info("Search took ".sprintf('%.03f', ( $stop_time - $start_time ))." secs");
305  
306 return 0;
307 }
308  
309 __PACKAGE__->meta->make_immutable();
310  
311 =head1 NAME
312  
313 App::CSE::Command::Search - Search the index for keywords or queries.
314  
315 =cut