blib/lib/App/WRT/Markup.pm untested

filter: Statementstmt 0.0% 0 / 111 Branchbran 0.0% 0 / 24 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 176 CC 13 SCAR 28.8
CC
13
Cov
0%
retrieve_include
56.0
line_parse
20.0
image_markup
12.0
CRAP 17.7
1 package App::WRT::Markup;
2  
3 use strict;
4 use warnings;
5 use feature "state";
6  
7 use base qw(Exporter);
8 our @EXPORT_OK = qw(line_parse image_markup eval_perl);
9  
10 use App::WRT::Image qw(image_size);
11 use App::WRT::Util qw(file_get_contents);
12  
13 use Carp;
14 use File::Basename;
15 use Text::Textile;
16 use Text::Markdown::Discount;
17  
18 # Some useful defaults:
19  
20 my %tags = (
21 retcon => q{div class="retcon"},
22 freeverse => 'p',
23 list => "ul>\n<li"
24 );
25  
26 my %end_tags = (
27 retcon => 'div',
28 freeverse => 'p',
29 list => "li>\n</ul"
30 );
31  
32 my %blank_lines = (
33 freeverse => "</p>\n\n<p>",
34 list => "</li>\n\n<li>"
35 );
36  
37 my %newlines = (
38 freeverse => "<br />\n"
39 );
40  
41 my %dashes = (
42 freeverse => ' &mdash; '
43 );
44  
45 =over
46  
47 =item eval_perl
48  
49 Evaluate embedded Perl in a string, replacing blocks enclosed with <perl> tags
50 with whatever they return (well, evaluated in a scalar context). Returns the
51 modified string.
52  
53 Also handles simple ${variables}, replacing them from the keys to $self.
54  
55 =cut
56  
57 sub eval_perl {
58 my $self = shift;
59 my ($text) = @_;
60  
61 while ($text =~ m{<perl>(.*?)</perl>}s) {
62 my $block = $1;
63  
64 # Run the $block, and include anything returned:
65 my $output = eval $block;
66  
67 if ($@) {
68 # Errors - log and return an empty string:
69 carp($@);
70 $output = '';
71 }
72  
73 $text =~ s{<perl>\Q$block\E</perl>}{$output}s;
74 }
75  
76 # Interpolate variables:
77 $text =~ s{
78 \$\{ ([a-zA-Z_]+) \}
79 }{
80 if (defined $self->{$1}) {
81 $self->{$1};
82 } else {
83 # TODO: Possibly this should be fatal.
84 "UNDEFINED: $1";
85 }
86 }gex;
87  
88 return $text;
89 }
90  
91 =item line_parse
92  
93 Performs substitutions on lines called by fragment_slurp, at least. Calls
94 include_process(), image_markup(), textile_process(), markdown_process(),
95 eval_perl().
96  
97 Applies before-parsing and after-parsing filters.
98  
99 Returns string.
100  
101 Parses some special markup. Specifically:
102  
103 <perl>print "hello world";</perl>
104 ${variable} interpolation from the WRT object
105  
106 <include>path/to/file/from/project/root</include>
107  
108 <textile></textile> - Text::Textile to HTML
109 <markdown></markdown> - Text::Markdown::Discount to HTML
110  
111 <image>filename.ext
112 optional alt tag
113 optional title text</image>
114  
115 <freeverse></freeverse>
116 <retcon></retcon>
117 <list></list>
118  
119 =cut
120  
121 sub line_parse {
122 my $self = shift;
123 my ($everything, $file) = (@_);
124  
125 # Eventually, this should probably only happen for templates:
126 $everything = $self->eval_perl($everything);
127  
128 # Take care of <include>, <textile>, <markdown>, and <image> tags:
129 include_process($self, $everything);
130 textile_process($everything);
131 markdown_process($everything);
132 $everything =~ s!<image>(.*?)</image>!$self->image_markup($file, $1)!seg;
133  
134 foreach my $key (keys %tags) {
135 # Set some replacements, unless they've been explicitly set already:
136 $end_tags{$key} ||= $tags{$key};
137  
138 # Transform blocks:
139 while ($everything =~ m| (<$key>\n?) (.*?) (\n?</$key>) |sx) {
140 my $open = $1;
141 my $block = $2;
142 my $close = $3;
143  
144 # Save the bits between instances of the block:
145 my (@interstices) = split /\Q$open$block$close\E/s, $everything;
146  
147 # Transform dashes, blank lines, and newlines:
148 dashes($dashes{$key}, $block) if defined $dashes{$key};
149 $block =~ s/\n\n/$blank_lines{$key}/gs if defined $blank_lines{$key};
150 newlines($newlines{$key}, $block) if defined $newlines{$key};
151  
152 # Slap it all back together as $everything, with start and end
153 # tags:
154 $block = "<$tags{$key}>$block</$end_tags{$key}>";
155 $everything = join $block, @interstices;
156 }
157 }
158  
159 return $everything;
160 }
161  
162 =item newlines($replacement, $block)
163  
164 Inline replace single newlines (i.e., line ends) within the block, except those
165 preceded by a double-quote, which probably indicates a still-open tag.
166  
167 =cut
168  
169 sub newlines {
170 $_[1] =~ s/(?<=[^"\n]) # not a double-quote or newline
171 # don't capture
172  
173 \n # end-of-line
174  
175 (?=[^\n]) # not a newline
176 # don't capture
177 /$_[0]/xgs;
178 }
179  
180 =item dashes($replacement, $block)
181  
182 Inline replace double dashes in a block - " -- " - with a given replacement.
183  
184 =cut
185  
186 sub dashes {
187 $_[1] =~ s/(\s+) # whitespace - no capture
188 \-{2} # two dashes
189 (\n|\s+|$) # newline, whitespace, or eol
190 /$1$_[0]$2/xgs;
191  
192 }
193  
194 =item include_process
195  
196 Inline replace <include>filename</include> tags, replacing them with the
197 contents of files.
198  
199 =cut
200  
201 sub include_process {
202 my $wrt = shift;
203  
204 $_[0] =~ s{
205  
206 <include> # start tag
207 (.*?) # anything (non-greedy)
208 </include> # end tag
209  
210 }{
211 retrieve_include($wrt, $1);
212 }xesg;
213 }
214  
215 =item retrieve_include
216  
217 Get the contents of an included file. This probably needs a great
218 deal more thought than I am presently giving it.
219  
220 =cut
221  
222 sub retrieve_include {
223 my $wrt = shift;
224 my ($file) = @_;
225  
226 # Trim leading and trailing spaces:
227 $file =~ s/^\s+//;
228 $file =~ s/\s+$//;
229  
230 if ($file =~ m{^ (/ | [.]/) }x) {
231 # TODO: Leads with a slash or a ./
232 croak('Tried to open an include path with a leading / or ./ - not yet supported.');
233 } else {
234 # Use the archive root as path.
235 $file = $wrt->{root_dir} . '/' . $file;
236 }
237  
238 if ($wrt->{cache_includes}) {
239 if (defined $wrt->{include_cache}->{$file}) {
240 return $wrt->{include_cache}->{$file};
241 }
242 }
243  
244 unless (-e $file) {
245 carp "No such file: $file";
246 return '';
247 }
248  
249 if (-d $file) {
250 carp("Tried to open a directory as an include path: $file");
251 return '';
252 }
253  
254 if ($wrt->{cache_includes}) {
255 $wrt->{include_cache}->{$file} = file_get_contents($file);
256 return $wrt->{include_cache}->{$file};
257 } else {
258 return file_get_contents($file);
259 }
260 }
261  
262 =item textile_process
263  
264 Inline replace <textile> markup in a string.
265  
266 =cut
267  
268 # This is exactly the kind of code that, even though it isn't doing anything
269 # especially over the top, looks ghastly to people who don't read Perl, so I'll
270 # try to explain a bit.
271  
272 sub textile_process {
273  
274 # First, there's a state variable here which can retain the Text::Textile
275 # object between invocations of the function, saving us a bit of time on
276 # subsequent calls. This should be equivalent to creating a closure around
277 # the function and keeping a $textile variable there.
278 state $textile;
279  
280 # Second, instead of unrolling the arguments to the function, we just act
281 # directly on the first (0th) one. =~ more or less means "do a regexy
282 # thing on this". It's followed by s, the substitution operator, which can
283 # use curly braces as delimiters between pattern and replacement.
284  
285 $_[0] =~ s{
286  
287 # Find tags...
288  
289 <textile> # start tag
290 (.*?) # anything (non-greedy)
291 </textile> # end tag
292  
293 }{
294  
295 # ...and replace them with the result of evaluating this block.
296  
297 # //= means "defined-or-equals"; if the var hasn't been defined yet,
298 # then make a new Textile object:
299 $textile //= Text::Textile->new();
300  
301 # Process the stuff we slurped out of our tags - this value will be
302 # used to replace the entire match from above (in Perl, the last
303 # expression evaluated is the return value of subs, evals, etc.):
304 $textile->process($1);
305  
306 }xesg;
307  
308 # x: eXtended regexp - whitespace ignored by default, comments allowed
309 # e: Execute the replacement as Perl code, and use its value
310 # s: treat all lines of the search subject as a Single string
311 # g: Globally replace all matches
312  
313 # For the genuinely concise version of this, see markdown_process().
314 }
315  
316 =item markdown_process
317  
318 Inline replace <markdown> markup in a string.
319  
320 =cut
321  
322 sub markdown_process {
323 state $markdown;
324  
325 my $flags = Text::Markdown::Discount::MKD_EXTRA_FOOTNOTE();
326  
327 $_[0] =~ s{
328 <markdown>(.*?)</markdown>
329 }{
330 $markdown //= Text::Markdown::Discount->new;
331 $markdown->markdown($1, $flags);
332 }xesg;
333 }
334  
335 =item image_markup
336  
337 Parse out an image tag and return the appropriate html.
338  
339 Relies on image_size from App::WRT::Image.
340  
341 =cut
342  
343 sub image_markup {
344 my $self = shift;
345 my ($file, $block) = @_;
346  
347 # Get a basename and directory for the file (entry) referencing the image:
348 my ($basename, $dir) = fileparse($file);
349  
350 # Truncated file date that just includes date + sub docs:
351 my ($file_date) = $dir =~ m{
352 (
353 [0-9]{4}/ # year
354 [0-9]{1,2}/ # month
355 [0-9]{1,2}/ # day
356 ([a-z]*/)* # sub-entries
357 )
358 $
359 }x;
360  
361 # Process the contents of the <image> tag:
362 my ($image_url, $alt_text, $title_text) = split /\n/, $block;
363 $alt_text ||= q{};
364 $title_text ||= $alt_text;
365  
366 # Resolve relative paths:
367 my $image_file;
368 if (-e "$dir/$image_url" ) {
369 # The path is to an image file in the same directory as current entry:
370 $image_file = "$dir/$image_url";
371 $image_url = "${file_date}${image_url}";
372 } elsif (-e $self->{entry_dir} . "/$image_url") {
373 # The path is to an image file starting with the entry_dir, like
374 # 2005/9/20/candles.jpg -> ./archives/2005/9/20/candles.jpg
375 $image_file = $self->{entry_dir} . "/$image_url";
376 }
377  
378 # Get width & height in pixels for known filetypes:
379 my ($width, $height) = image_size($self->{root_dir_abs} . '/' . $image_file);
380  
381 # This probably relies on mod_rewrite working:
382 $image_url = $self->{image_url_root} . $image_url;
383 return <<"IMG";
384 <img src="$image_url"
385 width="$width"
386 height="$height"
387 alt="$alt_text"
388 title="$title_text" />
389 IMG
390 }
391  
392 =back
393  
394 1;