Debian Codegraph @

t/lib/HtmlSanitizer.pm

raw
1 # A package to sanitize HTML in order to ease comparison between multiple tools.
2
3 package HtmlSanitizer;
4
5 use strict;
6 use warnings;
7 use utf8;
8 use feature ':5.24';
9
10 use Exporter 'import';
11
12 our @EXPORT = qw(sanitize_html);
13
14
15 my $html_tag_name_re = qr/[a-zA-Z][-a-zA-Z0-9]*/;
16 my $html_attribute_name_re = qr/[a-zA-Z_:][-a-zA-Z0-9_.:]*/;
17 my $html_space_re = qr/\n[ \t]*|[ \t][ \t]*\n?[ \t]*/; # Spaces, tabs, and up to one line ending.
18 my $opt_html_space_re = qr/[ \t]*\n?[ \t]*/; # Optional spaces.
19 my $html_attribute_value_re = qr/ [^ \t\n"'=<>`]+ | '[^']*' | "[^"]*" /x;
20 my $html_attribute_re =
21 qr/ ${html_space_re} ${html_attribute_name_re} (?: ${opt_html_space_re} = ${opt_html_space_re} ${html_attribute_value_re} )? /x;
22
23 my $html_open_tag_re = qr/ ${html_tag_name_re} ${html_attribute_re}* ${opt_html_space_re} \/? /x;
24 my $html_close_tag_re = qr/ \/ ${html_tag_name_re} ${opt_html_space_re} /x;
25
26
27 # The sanitizing here is quite strict (it only removes new lines happening just
28 # before or after an HTML tag), so this forces our converter to match closely
29 # what the cmark spec has (I guess it’s not a bad thing).
30 # In addition, this light-weight normalization did uncover a couple of bugs that
31 # were hidden by the normalization done by the cmark tool.
32 sub sanitize_html {
33 my ($html, $dense) = @_;
34 while ($html =~ m/<code>|(?<new_line>(?<=>)\s*\n+\s*(?=.)|\s*\n+\s*(?=<))/g) {
35 if ($+{new_line}) {
36 my $p = pos($html);
37 substr $html, $-[0], $+[0] - $-[0], '';
38 pos($html) = $p - length($+{new_line});
39 } else {
40 $html =~ m/<\/code>|$/g;
41 }
42 }
43 if ($dense) {
44 $html =~ s/\n+$//;
45 } else {
46 $html =~ s/( < (?: \/[a-z]+ | input ) >)/$1\n/gx;
47 $html =~ s/\n\n+$/\n/;
48 }
49 return $html;
50 }