lib/Markdown/Render.pm untested

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