blib/lib/MOP4Import/Util/CommentedJson.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 3 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 58 CC 2 SCAR 11.0
CC
2
Cov
0%
list_json_comments
6.0
strip_json_comments
2.0
BEGIN
2.0
CRAP 3.0
1 #!/usr/bin/env perl
2 package MOP4Import::Util::CommentedJson;
3 use strict;
4 use warnings FATAL => 'all';
5 use Exporter qw/import/;
6 use JSON::MaybeXS;
7 use bytes;
8  
9 our @EXPORT_OK = qw/strip_json_comments/;
10  
11 our $re_atom = qr{true|false|null}xs;
12  
13 our $re_string = qr{
14 "(?: [^\\"]
15 | \\ (?: \\
16 | \"
17 | / | b | f | n | r | t
18 | u [0-9A-F]{4}
19 )
20 )*+"
21 }xs;
22  
23 our $re_number = qr{
24 -?+
25 (?: 0
26 | [1-9] [0-9]*+
27 )?+
28 (?:
29 \. [0-9]++
30 )?+
31 (?:
32 [eE] [-+]?+ [0-9]*+
33 )?+
34 }xs;
35  
36 our $re_comment1 = qr{//[^\n]*+}xs;
37 our $re_comment2 = qr{/\*.*?\*/}xs;
38  
39 our $re_ALL = qr{ [\[\]\{\},:]
40 | (?<comment> $re_comment1 | $re_comment2)
41 | $re_atom
42 | $re_number
43 | $re_string
44 }xs;
45  
46 sub strip_json_comments {
47 my ($pack, $bytes) = @_;
48 $bytes =~ s/\A\xef\xbb\xbf//; # Strip BOM of utf-8.
49 my @region = reverse list_json_comments($pack, $bytes);
50 foreach my $region (@region) {
51 my ($startPos, $len) = @$region;
52 substr($bytes, $startPos, $len, '');
53 }
54 $bytes;
55 }
56  
57 sub list_json_comments {
58 my @pos;
59 while ($_[1] =~ m{\G(?<ws>\s*+)$re_ALL}g) {
60 if (defined $+{comment} and my $len = length($+{comment})) {
61 my $startPos = pos($_[1]) - $len;
62 push @pos, [$startPos, $len]
63 }
64 }
65 @pos;
66 }
67  
68 unless (caller) {
69 my $pack = __PACKAGE__;
70 my $method = shift;
71 my $codec = JSON::MaybeXS->new(allow_nonref => 1);
72 my @res = $pack->$method(@ARGV);
73 print $codec->encode(\@res), "\n";
74 }
75  
76 1;