lib/Markdown/Render.pm untested

filter: Statementstmt 0.0% 0 / 230 Branchbran 0.0% 0 / 58 Conditioncond 0.0% 0 / 28 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 358 CC 30 SCAR 34.1
CC
30
Cov
0%
finalize_markdown
90.0
print_html
72.0
_render_with_github
30.0
CRAP 30.3
1 package Markdown::Render;
2  
3 use strict;
4 use warnings;
5  
6 use Carp;
7 use Data::Dumper;
8 use English qw(-no_match_vars);
9 use HTTP::Request;
10 use IO::Scalar;
11 use JSON;
12 use LWP::UserAgent;
13 use List::Util qw(none);
14  
15 our $VERSION = '1.02';
16  
17 use parent qw(Class::Accessor::Fast);
18  
19 __PACKAGE__->follow_best_practice;
20  
21 __PACKAGE__->mk_accessors(
22 qw(
23 css
24 engine
25 git_email
26 git_user
27 html
28 infile
29 markdown
30 mode
31 no_title
32 raw
33 body
34 render
35 title
36 )
37 );
38  
39 use Readonly;
40  
41 Readonly our $GITHUB_API => 'https://api.github.com/markdown';
42 Readonly our $EMPTY => q{};
43 Readonly our $SPACE => q{ };
44 Readonly our $TOC_TITLE => 'Table of Contents';
45 Readonly our $TOC_BACK => 'Back to Table of Contents';
46 Readonly our $DEFAULT_CSS => 'https://cdn.simplecss.org/simple-v1.css';
47  
48 caller or __PACKAGE__->main;
49  
50 ########################################################################
51 sub new {
52 ########################################################################
53 my ( $class, @args ) = @_;
54  
55 my %options = ref $args[0] ? %{ $args[0] } : @args;
56  
57 $options{title} //= $TOC_TITLE;
58 $options{css} //= $DEFAULT_CSS;
59 $options{mode} //= 'markdown';
60 $options{engine} //= 'github';
61  
62 my $self = $class->SUPER::new( \%options );
63  
64 if ( $self->get_infile ) {
65 open my $fh, '<', $self->get_infile
66 or die 'could not open ' . $self->get_infile;
67  
68 local $RS = undef;
69  
70 $self->set_markdown(<$fh>);
71  
72 close $fh;
73 }
74  
75 return $self;
76 }
77  
78 ########################################################################
79 sub toc_back {
80 ########################################################################
81 my ($self) = @_;
82  
83 my $back_link = lc $self->get_title;
84 $back_link =~ s/\s/-/gxsm;
85  
86 return $back_link;
87 }
88  
89 ########################################################################
90 sub back_to_toc {
91 ########################################################################
92 my ( $self, $message ) = @_;
93  
94 $message ||= $TOC_BACK;
95  
96 $message =~ s/[(]\"?(.*?)\"?[)]/$1/xsm;
97  
98 return sprintf '[%s](#%s)', $message, $self->toc_back;
99 }
100  
101 ########################################################################
102 sub finalize_markdown {
103 ########################################################################
104 my ($self) = @_;
105  
106 my $markdown = $self->get_markdown;
107  
108 die "no markdown yet\n"
109 if !$markdown;
110  
111 my $fh = IO::Scalar->new( \$markdown );
112  
113 my $final_markdown;
114 my $in_code_block;
115  
116 while ( my $line = <$fh> ) {
117  
118 if ( $line =~ /\A\s*[`]{3}\s*\z/xsm ) {
119 $in_code_block ^= 1;
120 }
121  
122 if ($in_code_block) {
123 $final_markdown .= $line;
124 next;
125 }
126  
127 $line =~ s/^\!\#/\#/xsm; # ! used to prevent including header in TOC
128  
129 if ( $line =~ /^\@TOC\@/xsm ) {
130 my $toc = $self->create_toc;
131  
132 chomp $toc;
133  
134 $line =~ s/\@TOC\@/$toc/xsm;
135 }
136  
137 my $title = $self->get_title;
138  
139 if ( $line =~ /\@TOC_TITLE\@/xsm ) {
140 $line =~ s/\@TOC_TITLE\@/$title/xsm;
141 }
142  
143 my $git_user = $self->get_git_user // 'anonymouse';
144 my $git_email = $self->get_git_email // 'anonymouse@example.com';
145  
146 if ( $line =~ /\@GIT_(USER|EMAIL)\@/xsm ) {
147 $line =~ s/\@GIT_USER\@/$git_user/xsm;
148  
149 $line =~ s/\@GIT_EMAIL\@/$git_email/xsm;
150 }
151  
152 my $date;
153  
154 while ( $line =~ /\@DATE[(]?(.*?)[)]?\@/xsm ) {
155 my $format = $1 ? $1 : '%Y-%m-%d';
156  
157 $date = $self->format_date($format);
158  
159 $line =~ s /\@DATE[(]?(.*?)[)]?\@/$date/xsm;
160 }
161  
162 if ( $line =~ /\@TOC_BACK[(]?(.*?)[)]?\@/xsm ) {
163 my $back = $self->back_to_toc($1);
164  
165 $line =~ s/\@TOC_BACK[(]?(.*?)[)]?\@/$back/xsm;
166 }
167  
168 $final_markdown .= $line;
169 }
170  
171 close $fh;
172  
173 $self->set_markdown($final_markdown);
174  
175 return $self;
176  
177 }
178  
179 ########################################################################
180 sub _render_with_text_markdown {
181 ########################################################################
182 my ($self) = @_;
183  
184 eval { require Text::Markdown; };
185  
186 if ($EVAL_ERROR) {
187 croak "no Text::Markdown available...try using GitHub API.\n$EVAL_ERROR";
188 }
189  
190 my $tm = Text::Markdown->new( trust_list_start_value => 1 );
191  
192 my $markdown = $self->get_markdown;
193 my $html = Text::Markdown::markdown($markdown);
194  
195 if ( $self->get_raw ) {
196 $self->set_html($html);
197 }
198 else {
199 $self->fix_anchors( Text::Markdown::markdown($markdown) );
200 }
201  
202 return $self;
203 }
204  
205 ########################################################################
206 sub fix_anchors {
207 ########################################################################
208 my ( $self, $html_raw ) = @_;
209  
210 my $fh = IO::Scalar->new( \$html_raw );
211  
212 my $html;
213  
214 while ( my $line = <$fh> ) {
215 # remove garbage if there...
216 if ( $line =~ /^\s*<h(\d+)><a (.*)>(.*)<\/a>(.*)/xsm ) {
217 $line = "<h$1>$3$4</h$1>\n";
218 }
219  
220 $html .= _fix_header($line);
221 }
222  
223 close $fh;
224  
225 $self->set_html($html);
226  
227 return $self;
228 }
229  
230 ########################################################################
231 sub _fix_header {
232 ########################################################################
233 my ($line) = @_;
234  
235 return $line if $line !~ /^\s*<h(\d+)>(.*?)<\/h\d>$/xsm;
236  
237 my ( $hn, $anchor, $header ) = ( $1, $2, $2 ); ## no critic (ProhibitCaptureWithoutTest)
238  
239 $anchor = lc $anchor;
240 $anchor =~ s/\s+/-/gxsm; # spaces become '-'
241 $anchor =~ s/[\@'(),\`]//xsmg; # known weird characters, but expect more
242 $anchor =~ s/\///xsmg;
243  
244 $line
245 = sprintf qq{<h%d><a id="%s" class="anchor" href="#%s"></a>%s</h%d>\n},
246 $hn,
247 $anchor, $anchor, $header, $hn;
248  
249 return $line;
250 }
251  
252 ########################################################################
253 sub render_markdown {
254 ########################################################################
255 my ($self) = @_;
256  
257 if ( $self->get_engine eq 'github' ) {
258 return $self->_render_with_github;
259 }
260 elsif ( $self->get_engine eq 'text_markdown' ) {
261 return $self->_render_with_text_markdown;
262 }
263 else {
264 croak 'invalid engine: ' . $self->get_engine;
265 }
266 }
267  
268 ########################################################################
269 sub _render_with_github {
270 ########################################################################
271 my ($self) = @_;
272  
273 my $markdown = $self->get_markdown;
274  
275 my $ua = LWP::UserAgent->new;
276 my $req = HTTP::Request->new( 'POST', $GITHUB_API );
277  
278 my $mode = $self->get_mode;
279  
280 if ( none { $mode eq $_ } qw(gfm markdown) ) {
281 $mode = 'markdown';
282 }
283  
284 my $api_request = {
285 text => $markdown,
286 mode => $mode,
287 };
288  
289 $req->content( to_json($api_request) );
290  
291 my $rsp = $ua->request($req);
292  
293 croak 'could not render using GitHub API: ' . $rsp->status_line
294 if !$rsp->is_success;
295  
296 if ( $self->get_raw ) {
297 $self->set_html( $rsp->content );
298  
299 return $self;
300 }
301  
302 if ( $self->get_mode eq 'gfm' ) {
303 return $self->fix_anchors( $rsp->content );
304 }
305 else {
306 return $self->fix_github_html( $rsp->content );
307 }
308 }
309  
310 ########################################################################
311 sub fix_github_html {
312 ########################################################################
313 my ( $self, $html_raw ) = @_;
314  
315 my $fh = IO::Scalar->new( \$html_raw );
316  
317 my $html = $EMPTY;
318  
319 while ( my $line = <$fh> ) {
320 chomp $line;
321  
322 $line =~ s/(href|id)=\"\#?user-content-/$1=\"/xsm;
323 $line =~ s/(href|id)=\"\#?\%60.*\%60/$1=\"#$2/xsm;
324  
325 $html .= "$line\n";
326 }
327  
328 close $fh;
329  
330 $self->set_html($html);
331  
332 return $self;
333 }
334  
335 ########################################################################
336 sub format_date {
337 ########################################################################
338 my ( $self, $template ) = @_;
339  
340 require Date::Format;
341  
342 $template =~ s/[(]\"?(.*?)\"?[)]/$1/xsm;
343  
344 my $val = eval { Date::Format::time2str( $template, time ); };
345  
346 return $EVAL_ERROR ? '<undef>' : $val;
347 }
348  
349 ########################################################################
350 sub create_toc {
351 ########################################################################
352 my ($self) = @_;
353  
354 my $markdown = $self->get_markdown;
355  
356 my $fh = IO::Scalar->new( \$markdown );
357  
358 my $toc = $self->get_no_title ? $EMPTY : "# \@TOC_TITLE\@\n\n";
359  
360 while (<$fh>) {
361 chomp;
362  
363 /^(\#+)\s+(.*?)$/xsm && do {
364 my $level = $1;
365  
366 my $indent = $SPACE x ( 2 * ( length($level) - 1 ) );
367  
368 my $topic = $2;
369  
370 my $link = $topic;
371  
372 $link =~ s/^\s*(.*)\s*$/$1/xsm;
373  
374 $link =~ s/\s+/-/gxsm; # spaces become '-'
375  
376 $link =~ s/[\@'(),\`]//xsmg; # known weird characters, but expect more
377  
378 $link =~ s/\///xsmg;
379  
380 $link = lc $link;
381  
382 # remove HTML entities
383 $link =~ s/&\#\d+;//xsmg;
384  
385 # remove escaped entities and remaining noisy characters
386 $link =~ s/[{}&]//xsmg;
387  
388 $toc .= sprintf "%s* [%s](#%s)\n", $indent, $topic, $link;
389 };
390 }
391  
392 close $fh;
393  
394 return $toc;
395 }
396  
397 ########################################################################
398 sub print_html {
399 ########################################################################
400 my ( $self, %options ) = @_;
401  
402 my $fh = $options{fh} // *STDOUT;
403  
404 if ( !$options{body} ) {
405 print {$fh} $self->get_html;
406  
407 return;
408 }
409  
410 my $css = exists $options{css} ? $options{css} : $self->get_css;
411 my $title = exists $options{title} ? $options{title} : $self->get_infile;
412  
413 my $title_section = $title ? "<title>$title</title>" : $EMPTY;
414  
415 my $css_section
416 = $css
417 ? qq{<link href="$css" rel="stylesheet" type="text/css" />}
418 : $EMPTY;
419  
420 my @head = grep { $_ ? $_ : () } ( $title_section, $css_section );
421  
422 my $head_section;
423  
424 if (@head) {
425 unshift @head, '<head>';
426 push @head, '</head>';
427  
428 $head_section = join "\n", @head;
429 }
430  
431 my $body = $self->get_html;
432  
433 print {$fh} <<"END_OF_TEXT";
434 <html>
435 $head_section
436 <body>
437 $body
438 </body>
439 </html>
440 END_OF_TEXT
441  
442 return;
443 }
444  
445 ########################################################################
446 sub main {
447 ########################################################################
448  
449 my $md = Markdown::Render->new(
450 infile => shift @ARGV,
451 css => $DEFAULT_CSS
452 );
453  
454 $md->finalize_markdown->render_markdown;
455  
456 $md->print_html;
457  
458 exit 0;
459 }
460  
461 1;
462  
463 ## no critic (RequirePodSections)
464  
465 __END__