1 |
package Frey::Shell::Grep; |
2 |
use Moose; |
3 |
|
4 |
extends 'Frey'; |
5 |
with 'Frey::Web'; |
6 |
|
7 |
use English; |
8 |
|
9 |
has pattern => ( |
10 |
documentation => 'grep pattern', |
11 |
is => 'rw', |
12 |
isa => 'Str', |
13 |
required => 1, |
14 |
default => 'FIXME', |
15 |
); |
16 |
|
17 |
has path => ( |
18 |
documentation => 'path(s) to grep', |
19 |
is => 'rw', |
20 |
isa => 'Str', |
21 |
required => 1, |
22 |
default => 'lib/ t/ etc/', |
23 |
); |
24 |
|
25 |
has _grep_command => ( |
26 |
documentation => 'executed grep command', |
27 |
is => 'rw', |
28 |
isa => 'Str', |
29 |
); |
30 |
|
31 |
has results_as_data => ( |
32 |
is => 'rw', |
33 |
isa => 'ArrayRef[HashRef]', |
34 |
lazy => 1, |
35 |
default => |
36 |
sub { |
37 |
|
38 |
my ($self) = @_; |
39 |
|
40 |
my $patt = $self->pattern; |
41 |
|
42 |
my $cmd = 'grep -rn ' . $patt . ' ' . $self->path; |
43 |
$self->_grep_command( $cmd ); |
44 |
warn "# $cmd"; |
45 |
|
46 |
my @results; |
47 |
|
48 |
open(my $fh, '-|', $cmd) || die "can't open pipe to $cmd $!"; |
49 |
while(<$fh>) { |
50 |
my ( $path, $line, $text ) = split(/:/,$_,3); |
51 |
if ( ! $line ) { |
52 |
push @results, { text => $path }; |
53 |
} else { |
54 |
push @results, { path => $path, line => $line, text => $text }; |
55 |
} |
56 |
} |
57 |
|
58 |
if ( $INPUT_LINE_NUMBER > 0 ) { # closing pipe grep output results in error |
59 |
close($fh) || die "can't close pipe to $cmd $!"; |
60 |
} |
61 |
|
62 |
# warn "# ", $self->dump( @results ); |
63 |
|
64 |
return \@results; |
65 |
}); |
66 |
|
67 |
sub as_markup { |
68 |
my ($self) = @_; |
69 |
|
70 |
my $patt = $self->pattern; |
71 |
$self->title( $patt ); |
72 |
|
73 |
$self->add_css(qq| |
74 |
dt.p { |
75 |
color: #888; |
76 |
white-space: pre-wrap; |
77 |
font-family: monospace; |
78 |
margin-top: 1em; |
79 |
} |
80 |
dd a { |
81 |
float: left; |
82 |
width: 3em; |
83 |
} |
84 |
dd code b { |
85 |
background-color: #ff8; |
86 |
} |
87 |
|); |
88 |
|
89 |
my $html; |
90 |
my $last_path = ''; |
91 |
|
92 |
foreach my $result ( @{ $self->results_as_data } ) { |
93 |
|
94 |
warn $self->dump( $result ); |
95 |
|
96 |
my $text = $result->{text} || die "no text"; |
97 |
|
98 |
$text = $self->html_escape( $text ); |
99 |
if ( my $path = $result->{path} ) { |
100 |
my $line = $result->{line} || die "no line"; |
101 |
if ( $path ne $last_path ) { |
102 |
$html .= qq|<dt class="p">$path</dt>|; |
103 |
} |
104 |
$text =~ s{(\Q$patt\E)}{<b>$1</b>}; |
105 |
$html .= qq|<dd><a target="editor" href="/editor+$path+$line">$line</a> <code>$text</code>|; |
106 |
$last_path = $path; |
107 |
} else { |
108 |
$html .= qq|<dt>$text</dt>|; |
109 |
} |
110 |
} |
111 |
|
112 |
if ( $html ) { |
113 |
my $command = $self->_grep_command; |
114 |
$html = qq| |
115 |
<h1>$patt</h1> |
116 |
<pre>$command</pre> |
117 |
<dl>$html</dl> |
118 |
|; |
119 |
} else { |
120 |
$html = $self->error( "No results for $patt\n" ); |
121 |
} |
122 |
|
123 |
return $html; |
124 |
} |
125 |
|
126 |
1; |