lib/Config/JSON/Enhanced.pm

filter: Statementstmt 88.9% 121 / 136 Branchbran 82.3% 56 / 68 Conditioncond 60.0% 30 / 50 MC/DCmcdc 33.3% 9 / 27 Subroutinesub 100% 9 / 9 Podpod 100% 1 / 1 totaltotal 77.6% 226 / 291 CC 53 SCAR 42.2
CC
53
Cov
81%
config2perl
77.9
BEGIN
1.0
BEGIN
1.0
CRAP 67.8
↑ Summary script/configjson2json.pl »
1 package Config::JSON::Enhanced;
2  
3 15 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 15 our $VERSION = '0.10';
8  
9 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # which loads JSON::XS with a purel-perl JSON fallback
13 15 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 15 ▶use Data::Roundtrip qw/json2perl perl2dump no-unicode-escape-permanently/;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 15 ▶use Exporter; # we have our own import() don't import it
Subroutine BEGIN: called CC=1 SCAR=0.0
18 15 our @ISA = qw(Exporter);
19 15 our @EXPORT = qw/
20 config2perl
21 /;
22  
23 # Convert enhanced JSON string into a Perl data structure.
24 # The input parameters hashref:
25 # * specify where is the content to be parsed via:
26 # 'filename',
27 # 'filehandle', or,
28 # 'string'
29 # * optional 'commentstyle' is a string of comma separated
30 # commentstyles (valid styles are C, CPP, shell)
31 # * optional 'variable-substitutions' is a hashref with
32 # keys as template variable names to be substutited
33 # inside the content with their corresponding values.
34 # For example {'xx' => 'hello'} will substitute
35 # <% xx %> with hello
36 # * optional 'remove-comments-in-strings' to remove comments from JSON strings
37 # (both keys and values), default is to KEEP anything inside a string
38 # even if it looks like comments we are supposed to remove (because string
39 # can be a bash script, for example).
40 # * optional 'debug' for setting verbosity, default is zero.
41 #
42 # It returns the created Perl data structure or undef on failure.
43 592 ▶sub config2perl {
Subroutine config2perl: called CC=53 SCAR=43.6
Pod documented
44 592 ▶ my $params = shift // {};
Condition50%1/2
shift() // {}
l!l
5920
MC/DC0%0/1
shift() // {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
45  
46 592 my $contents;
47 592 ▶ if( exists($params->{'filename'}) && defined(my $infile=$params->{'filename'}) ){
Branch: 3 branches
BranchTrueFalseTotal
if (exists $params->{'filename'} and defined(my $infile = $params->{'filename'})) { } 19 573 592
elsif (exists $params->{'filehandle'} and defined(my $fh = $params->{'filehandle'})) { } 11 562 573
elsif (exists $params->{'string'} and defined $params->{'string'}) { } 562 0 562
Condition66%2/3
exists $params->{"filename"} and defined(my $infile = $params->{"filename"})
!ll&&!rl&&r
573019
MC/DC50%1/2
exists $params->{"filename"} and defined(my $infile = $params->{"filename"})
exists $params->{"filename"} defined(my $infile = $params->{"filename"})
Truth table66%2/3
A and B
A= exists $params->{"filename"}B= defined(my $infile = $params->{"filename"})
ABresult
0X0
100
111
48 19 my $fh;
49 0 ▶ if( ! open $fh, '<:encoding(UTF-8)', $infile ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, failed to open file '$infile' for reading, $!"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, "<:encoding(UTF-8)", $infile) 0 19 19
50 19 { local $/ = undef; $contents = <$fh> }; close $fh;
51 ▶ } elsif( exists($params->{'filehandle'}) && defined(my $fh=$params->{'filehandle'}) ){
Condition66%2/3
exists $params->{"filehandle"} and defined(my $fh = $params->{"filehandle"})
!ll&&!rl&&r
562011
MC/DC50%1/2
exists $params->{"filehandle"} and defined(my $fh = $params->{"filehandle"})
exists $params->{"filehandle"} defined(my $fh = $params->{"filehandle"})
Truth table66%2/3
A and B
A= exists $params->{"filehandle"}B= defined(my $fh = $params->{"filehandle"})
ABresult
0X0
100
111
52 11 { local $/ = undef; $contents = <$fh> }
53 # we are not closing the filehandle, it is caller-specified, so caller responsibility
54 ▶ } elsif( exists($params->{'string'}) && defined($params->{'string'}) ){
Condition33%1/3
exists $params->{"string"} and defined $params->{"string"}
!ll&&!rl&&r
00562
MC/DC0%0/2
exists $params->{"string"} and defined $params->{"string"}
exists $params->{"string"} defined $params->{"string"}
Truth table33%1/3
A and B
A= exists $params->{"string"}B= defined $params->{"string"}
ABresult
0X0
100
111
55 562 $contents = $params->{'string'};
56 }
57 0 ▶ if( ! defined $contents ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, one of 'filename', 'filehandle' or 'string' must be specified in the parameters hash as the source of the configuration contents."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $contents) 0 592 592
58  
59 my $debug = exists($params->{'debug'}) && defined($params->{'debug'})
60 592 ▶ ? $params->{'debug'} : 0
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'debug'} && defined $params->{'debug'} ? : 0 592 592
Condition33%1/3
exists $params->{"debug"} and defined $params->{"debug"}
!ll&&!rl&&r
59200
MC/DC0%0/2
exists $params->{"debug"} and defined $params->{"debug"}
exists $params->{"debug"} defined $params->{"debug"}
Truth table33%1/3
A and B
A= exists $params->{"debug"}B= defined $params->{"debug"}
ABresult
0X0
100
111
61 ;
62  
63 my $commentstyle = exists($params->{'commentstyle'}) && defined($params->{'commentstyle'})
64 592 ▶ ? $params->{'commentstyle'} : 'C'
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'commentstyle'} && defined $params->{'commentstyle'} ? : 592 0 592
Condition33%1/3
exists $params->{"commentstyle"} and defined $params->{"commentstyle"}
!ll&&!rl&&r
00592
MC/DC0%0/2
exists $params->{"commentstyle"} and defined $params->{"commentstyle"}
exists $params->{"commentstyle"} defined $params->{"commentstyle"}
Truth table33%1/3
A and B
A= exists $params->{"commentstyle"}B= defined $params->{"commentstyle"}
ABresult
0X0
100
111
65 ;
66  
67 592 my ($tvop, $tvcl);
68 592 ▶ if( exists($params->{'tags'}) && defined($params->{'tags'}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{'tags'} and defined $params->{'tags'}) { } 22 570 592
Condition66%2/3
exists $params->{"tags"} and defined $params->{"tags"}
!ll&&!rl&&r
570022
MC/DC50%1/2
exists $params->{"tags"} and defined $params->{"tags"}
exists $params->{"tags"} defined $params->{"tags"}
Truth table66%2/3
A and B
A= exists $params->{"tags"}B= defined $params->{"tags"}
ABresult
0X0
100
111
69 22 ▶ if( ref($params->{'tags'}) ne 'ARRAY' ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, input parameter 'tags' must be an ARRAYref of exactly 2 items and not a '".ref($params->{'tags'})."'."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params->{"tags"} ne "ARRAY") 1 21 22
70 0 ▶ if( scalar(@{ $params->{'tags'} }) != 2 ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, input parameter 'tags' must be an ARRAYref of exactly 2 items and not ".scalar(@{ $params->{'tags'} })."."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$params->{"tags"};} != 2) 0 21 21
71 21 ($tvop, $tvcl) = @{ $params->{'tags'} };
72 570 } else { $tvop = '<%'; $tvcl = '%>' }
73  
74 # check that the tags for verbatim sections is not the same as comments
75 591 ▶ while( $commentstyle =~ /\bcustom\((.+?)\)\((.*?)\)/ig ){
Branch: 1 branch
BranchTrueFalseTotal
if ($commentstyle =~ /\bcustom\((.+?)\)\((.*?)\)/gi) 1865 584 2449
76 1865 my $coop = $1; my $cocl = $2;
77 0 ▶ if( $debug > 0 ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : checking comment tags '${coop}' and '${cocl}' not to be the same or contain verbatim/variables tags '${tvop}' and '${tvcl}' ..." }
Branch: 1 branch
BranchTrueFalseTotal
if ($debug > 0) 0 1865 1865
78 1865 ▶ if( ($tvop eq $coop) || ($tvop eq $cocl)
Branch: 1 branch
BranchTrueFalseTotal
if ($tvop eq $coop or $tvop eq $cocl or $tvcl eq $coop or $tvcl eq $cocl) 3 1862 1865
Condition77%7/9
$tvop eq $coop or $tvop eq $cocl or $tvcl eq $coop or $tvcl eq $cocl
l!l&&r!l&&!r
301862
$tvop eq $coop or $tvop eq $cocl or $tvcl eq $coop
l!l&&r!l&&!r
301862
$tvop eq $coop or $tvop eq $cocl
l!l&&r!l&&!r
211862
MC/DC50%2/4
$tvop eq $coop or $tvop eq $cocl or $tvcl eq $coop or $tvcl eq $cocl
$tvop eq $coop $tvop eq $cocl $tvcl eq $coop $tvcl eq $cocl
Truth table60%3/5
A or B or C or D
A= $tvop eq $coopB= $tvop eq $coclC= $tvcl eq $coopD= $tvcl eq $cocl
ABCDresult
1XXX1
01XX1
001X1
00011
00000
79 || ($tvcl eq $coop) || ($tvcl eq $cocl)
80 3 ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, there is a clash (exact match) with verbatim/variable tags ('${tvop}' and '${tvcl}') and comment tags ('${coop}' and '${cocl}')."; return undef }
81 # also check if one contains the other
82 1862 ▶ if( ($tvop =~ /\Q${coop}\E/) || ($tvop =~ /\Q${cocl}\E/)
Branch: 1 branch
BranchTrueFalseTotal
if ($tvop =~ /\Q$coop\E/ or $tvop =~ /\Q$cocl\E/ or $tvcl =~ /\Q$coop\E/ or $tvcl =~ /\Q$cocl\E/) 3 1859 1862
Condition77%7/9
$tvop =~ /\Q$coop\E/ or $tvop =~ /\Q$cocl\E/ or $tvcl =~ /\Q$coop\E/ or $tvcl =~ /\Q$cocl\E/
l!l&&r!l&&!r
211859
$tvop =~ /\Q$coop\E/ or $tvop =~ /\Q$cocl\E/ or $tvcl =~ /\Q$coop\E/
l!l&&r!l&&!r
201860
$tvop =~ /\Q$coop\E/ or $tvop =~ /\Q$cocl\E/
l!l&&r!l&&!r
201860
MC/DC50%2/4
$tvop =~ /\Q$coop\E/ or $tvop =~ /\Q$cocl\E/ or $tvcl =~ /\Q$coop\E/ or $tvcl =~ /\Q$cocl\E/
$tvop =~ /\Q$coop\E/ $tvop =~ /\Q$cocl\E/ $tvcl =~ /\Q$coop\E/ $tvcl =~ /\Q$cocl\E/
Truth table60%3/5
A or B or C or D
A= $tvop =~ /\Q$coop\E/B= $tvop =~ /\Q$cocl\E/C= $tvcl =~ /\Q$coop\E/D= $tvcl =~ /\Q$cocl\E/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
83 || ($tvcl =~ /\Q${coop}\E/) || ($tvcl =~ /\Q${cocl}\E/)
84 3 ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, there is a clash (one contains the other) with verbatim/variable tags ('${tvop}' and '${tvcl}') and comment tags ('${coop}' and '${cocl}')."; return undef }
85 1859 ▶ if( ($coop =~ /\Q${tvop}\E/) || ($coop =~ /\Q${tvcl}\E/)
Branch: 1 branch
BranchTrueFalseTotal
if ($coop =~ /\Q$tvop\E/ or $coop =~ /\Q$tvcl\E/ or $cocl =~ /\Q$tvop\E/ or $cocl =~ /\Q$tvcl\E/) 1 1858 1859
Condition44%4/9
$coop =~ /\Q$tvop\E/ or $coop =~ /\Q$tvcl\E/ or $cocl =~ /\Q$tvop\E/ or $cocl =~ /\Q$tvcl\E/
l!l&&r!l&&!r
011858
$coop =~ /\Q$tvop\E/ or $coop =~ /\Q$tvcl\E/ or $cocl =~ /\Q$tvop\E/
l!l&&r!l&&!r
001859
$coop =~ /\Q$tvop\E/ or $coop =~ /\Q$tvcl\E/
l!l&&r!l&&!r
001859
MC/DC25%1/4
$coop =~ /\Q$tvop\E/ or $coop =~ /\Q$tvcl\E/ or $cocl =~ /\Q$tvop\E/ or $cocl =~ /\Q$tvcl\E/
$coop =~ /\Q$tvop\E/ $coop =~ /\Q$tvcl\E/ $cocl =~ /\Q$tvop\E/ $cocl =~ /\Q$tvcl\E/
Truth table40%2/5
A or B or C or D
A= $coop =~ /\Q$tvop\E/B= $coop =~ /\Q$tvcl\E/C= $cocl =~ /\Q$tvop\E/D= $cocl =~ /\Q$tvcl\E/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
86 || ($cocl =~ /\Q${tvop}\E/) || ($cocl =~ /\Q${tvcl}\E/)
87 1 ){ warn __PACKAGE__.'::configfile2perl()'." (line ".__LINE__.") : error, there is a clash (one contains the other) with verbatim/variable tags ('${tvop}' and '${tvcl}') and comment tags ('${coop}' and '${cocl}')."; return undef }
88 }
89  
90 my $tsubs = exists($params->{'variable-substitutions'})
91 584 ▶ ? $params->{'variable-substitutions'} : undef
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'variable-substitutions'} ? : 533 51 584
92 ;
93  
94 # remove comments inside strings? default is NO, keep comments if inside strings
95 # because they may not be our comments (e.g. string contains a bash script)
96 my $remove_comments_in_strings = exists($params->{'remove-comments-in-strings'}) && defined($params->{'remove-comments-in-strings'})
97 584 ▶ ? $params->{'remove-comments-in-strings'} : 0
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'remove-comments-in-strings'} && defined $params->{'remove-comments-in-strings'} ? : 18 566 584
Condition66%2/3
exists $params->{"remove-comments-in-strings"} and defined $params->{"remove-comments-in-strings"}
!ll&&!rl&&r
566018
MC/DC50%1/2
exists $params->{"remove-comments-in-strings"} and defined $params->{"remove-comments-in-strings"}
exists $params->{"remove-comments-in-strings"} defined $params->{"remove-comments-in-strings"}
Truth table66%2/3
A and B
A= exists $params->{"remove-comments-in-strings"}B= defined $params->{"remove-comments-in-strings"}
ABresult
0X0
100
111
98 ;
99  
100 # firstly, substitute templated variables if any
101 # with the user-specified data.
102 # This includes ANYTHNING in the input enhanced JSON including
103 # verbatim sections, keys, values, etc.
104 # The opening and closing tags of vars are user-specified
105 # and are NOT allowed to contain spaces in between
106 # (e.g. '< %' will not be matched if '<%' was specified)
107 584 for my $ak (keys %$tsubs){
108 35 my $av = $tsubs->{$ak};
109 0 ▶ if( ($ak =~ /(?:\Q${tvop}\E)|(?:\Q${tvcl}\E)/) ){ warn __PACKAGE__.'::config2perl()'." (line ".__LINE__.") : error, variable names can not contain the specified opening ($tvop) and/or closing ($tvcl) variable name tags."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
if ($ak =~ /(?:\Q$tvop\E)|(?:\Q$tvcl\E)/) 0 35 35
110 35 $contents =~ s!\Q${tvop}\E\s*${ak}\s*\Q${tvcl}\E!${av}!g;
111 }
112 # this is JUST a warning:
113 # we can not be sure if this <% xyz %> is part of the content or a forgotten templated variable
114 0 ▶ if( $contents =~ /\Q${tvop}\E\s*!(:?(:?begin-verbatim-section)|(:?end-verbatim-section))\s*\Q${tvcl}\E/ ){ print STDERR "--begin content:\n".$contents."\n--end content.\n".__PACKAGE__.'::config2perl()'." (line ".__LINE__.") : warning, there may still be remains of templated variables in the specified content (tags used: '${tvop}' and '${tvcl} -- ignore the enclosing single quotes), see above what remained after all template variables substitutions were done." }
Branch: 1 branch
BranchTrueFalseTotal
if ($contents =~ /\Q$tvop\E\s*!(:?(:?begin-verbatim-section)|(:?end-verbatim-section))\s*\Q$tvcl\E/) 0 584 584
115 # this does not print contents in its warning message
116 # in case Test::More gets confused:
117 #if( $contents =~ /\Q${tvop}\E\s*!(:?(:?begin-verbatim-section)|(:?end-verbatim-section))\s*\Q${tvcl}\E/ ){ print STDERR __PACKAGE__.'::config2perl()'." (line ".__LINE__.") : warning, there may still be remains of templated variables in the specified content (tags used: '${tvop}' and '${tvcl}' -- ignore the enclosing single quotes), see above what remained after all template variables substitutions were done." }
118  
119 # secondly, remove the VERBATIM multiline sections and transform them.
120 # Comments inside the verbatim section will NOT BE touched.
121 # The only thing touched was the templated variables earlier
122 # it substitutes each verbatim section with a code
123 # then does the comments and then replaces the code with the verbatim section at the very end
124 584 my @verbs;
125 584 my $idx = 0;
126 584 ▶ while( $contents =~ s/\Q${tvop}\E\s*begin-verbatim-section\s*\Q${tvcl}\E(.*?)\Q${tvop}\E\s*end-verbatim-section\s*\Q${tvcl}\E/"___my___verbatim-section-${idx}___my___"/s ){
Branch: 1 branch
BranchTrueFalseTotal
if ($contents =~ s/\Q$tvop\E\s*begin-verbatim-section\s*\Q$tvcl\E(.*?)\Q$tvop\E\s*end-verbatim-section\s*\Q$tvcl\E/"___my___verbatim-section-${idx}___my___"/s) 72 584 656
127 72 my $vc = $1;
128 # remove from start and end of whole string newlines+spaces
129 72 $vc =~ s/^[\n\t ]+//;
130 72 $vc =~ s/[\n\t ]+$//;
131 # remove newlines followed by optional spaces at the beginning of each line
132 72 $vc =~ s/\n+[ \t]*/\\n/gs;
133 # escape all double quotes (naively)
134 # but not those which are already escaped (naively)
135 72 $vc =~ s/\\"/<%__abcQQxyz__%>/g;
136 72 $vc =~ s/"/\\"/g;
137 72 $vc =~ s/<%__abcQQxyz__%>/\\\\\\"/g;
138 # so echo "aa \"xx\""
139 # becomes echo \"aa \\\"xx\\\"\"
140 72 push @verbs, $vc;
141 72 $idx++;
142 }
143  
144 # thirdly, replace all JSON strings (keys or values) with indexed markers
145 # so that their contained comments
146 # to be left intact after the comment substitution which will
147 # be done later on.
148 584 my @stringsubs;
149 584 ▶ if( $remove_comments_in_strings == 0 ){
Branch: 1 branch
BranchTrueFalseTotal
if ($remove_comments_in_strings == 0) 576 8 584
150 576 $idx = 0;
151 576 ▶ while( $contents =~ s/(?<![\\])"((?:.(?!(?<![\\])"))*.?)"/___my___EJSTRING($idx)___my___/ ){
Branch: 1 branch
BranchTrueFalseTotal
if ($contents =~ s/(?<![\\])"((?:.(?!(?<![\\])"))*.?)"/___my___EJSTRING($idx)___my___/) 4817 576 5393
152 4817 push @stringsubs, $1;
153 4817 $idx++;
154 }
155 }
156  
157 # fourthly, remove comments: 'shell' and/or 'C' and/or 'CPP'
158 # and/or multiple instances of 'custom()()'
159 584 my $tc = $commentstyle;
160 584 ▶ if( $tc =~ s/\bC\b//i ){
Branch: 1 branch
BranchTrueFalseTotal
if ($tc =~ s/\bC\b//i) 375 209 584
161 375 $contents =~ s/\/\*(?:(?!\*\/).)*\*\/\n?//sg;
162 }
163 584 ▶ if( $tc =~ s/\bCPP\b//i ){
Branch: 1 branch
BranchTrueFalseTotal
if ($tc =~ s/\bCPP\b//i) 425 159 584
164 425 $contents =~ s/\/\*(?:(?!\*\/).)*\*\/\n?//sg;
165 425 $contents =~ s!//.*$!!mg;
166 }
167 584 ▶ if( $tc =~ s/\bshell\b//i ){
Branch: 1 branch
BranchTrueFalseTotal
if ($tc =~ s/\bshell\b//i) 398 186 584
168 # TODO: we must also remove the newline left!
169 398 $contents =~ s/#.*$//mg;
170 }
171  
172 # specify a custom comment style with required opening string
173 # and an optional closing
174 # e.g. custom(required)(optional), custom(<<)(>>) or custom(REM)()
175 584 ▶ while( $tc =~ s/\bcustom\((.+?)\)\((.*?)\)//i ){
Branch: 1 branch
BranchTrueFalseTotal
if ($tc =~ s/\bcustom\((.+?)\)\((.*?)\)//i) 1858 584 2442
176 # mulitple custom(opening)(closing) commentstyle are allowed
177 # 'opening' and 'closing' can be any string
178 # And need not be balanced e.g. <<< and >>
179 # And can be the same e.g. <<< and <<<
180 1858 my $coop = $1; my $cocl = $2;
181 1858 ▶ if( $cocl =~ /^\s*$/ ){
Branch: 1 branch
BranchTrueFalseTotal
if ($cocl =~ /^\s*$/) { } 340 1518 1858
182 # TODO: we must also remove the newline left!
183 340 $contents =~ s/\Q${coop}\E.*$//mg;
184 } else {
185 1518 $contents =~ s/\Q${coop}\E(?:(?!\Q${cocl}\E\s*).)*\Q${cocl}\E\s*\n?//sg;
186 }
187 }
188 0 ▶ if( $tc =~ /[a-z]/i ){ warn __PACKAGE__.'::config2perl()'." (line ".__LINE__.") : error, comments style '${commentstyle}' was not understood, this is what was left after parsing it: '${tc}'."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
if ($tc =~ /[a-z]/i) 0 584 584
189  
190 # this is JUST a warning:
191 # because we can not be sure if this <% xyz %>
192 # is part of the content or a forgotten templated variable
193 # However, the json2perl below will return undef on any errors
194 # turn it into an error?
195 0 ▶ if( $contents =~ /\Q${tvop}\E.+?(?:begin|end)-verbatim-section\s*\Q${tvcl}\E/ ){ warn "--begin content:\n".$contents."\n--end content.\n".__PACKAGE__.'::config2perl()'." (line ".__LINE__.") : warning, there may still be remains of templated variables in the specified content, see above what remained after all verbatime sections were removed." }
Branch: 1 branch
BranchTrueFalseTotal
if ($contents =~ /\Q$tvop\E.+?(?:begin|end)-verbatim-section\s*\Q$tvcl\E/) 0 584 584
196  
197 584 ▶ if( $remove_comments_in_strings == 0 ){
Branch: 1 branch
BranchTrueFalseTotal
if ($remove_comments_in_strings == 0) 576 8 584
198 576 $idx = 0;
199 576 ▶ for($idx=scalar(@stringsubs);$idx-->0;){
Branch: 1 branch
BranchTrueFalseTotal
if ($idx-- > 0) 4817 576 5393
200 4817 my $astring = $stringsubs[$idx];
201 4817 $contents =~ s/___my___EJSTRING\($idx\)___my___/"${astring}"/g
202 }
203 }
204  
205 # and now substitute the transformed verbatim sections back
206 584 ▶ for($idx=scalar(@verbs);$idx-->0;){
Branch: 1 branch
BranchTrueFalseTotal
if ($idx-- > 0) 72 584 656
207 72 $contents =~ s/___my___verbatim-section-${idx}___my___/$verbs[$idx]/g;
208 }
209  
210 0 ▶ if( $debug > 0 ){ warn $contents."\n\n".__PACKAGE__.'::config2perl()'." (line ".__LINE__.") : produced above standard JSON from enhanced JSON content." }
Branch: 1 branch
BranchTrueFalseTotal
if ($debug > 0) 0 584 584
211  
212 # here $contents must contain standard JSON which we parse:
213 584 my $inhash = json2perl($contents);
214 584 ▶ if( ! defined $inhash ){ warn $contents."\n\n".__PACKAGE__.'::config2perl()'." (line ".__LINE__.") : error, call to ".'Data::Roundtrip::json2perl()'." has failed for above json string and comments style '${commentstyle}'."; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $inhash) 1 583 584
215 583 return $inhash
216 }
217  
218 =pod
219  
220 =head1 NAME
221  
222 Config::JSON::Enhanced - JSON-based config with C/Shell-style comments, verbatim sections and variable substitutions
223  
224 =head1 VERSION
225  
226 Version 0.10
227  
228 =head1 SYNOPSIS
229  
230 This module provides subroutine C<config2perl()> for parsing configuration content,
231 from files or strings, based on, what I call, "enhanced JSON" (see section
232 L<ENHANCED JSON FORMAT> for more details). Briefly, it is standard JSON which allows:
233  
234 =over 2
235  
236 =item * C<C>-style, C<C++>-style, C<shell>-style or custom comments.
237  
238 =item * Template-style variables (e.g. C<E<lt>% appdir %E<gt>>)
239 which are substituted with user-specified data during parsing.
240  
241 =item * Verbatim sections which are a sort of here-doc for JSON,
242 allowing strings to span multiple
243 lines, to contain single and double quotes unescaped,
244 to contain template-style variables.
245  
246 =back
247  
248 This module was created because I needed to include
249 long shell scripts containing lots of quotes and newlines,
250 in a configuration file which started as JSON.
251  
252 The process is simple: so-called "enhanced JSON" is parsed
253 by L<config2perl>. Comments are removed, variables are
254 substituted, verbatim sections become one line again
255 and standard JSON is created. This is parsed with
256 L<JSON> (via L<Data::Roundtrip::json2perl>) to
257 produce a Perl data structure which is returned.
258  
259 It has been tested with unicode data
260 (see C<t/070-config2perl-complex-utf8.t>)
261 with success. But who knows ?!?!
262  
263 Here is an example:
264  
265 use Config::JSON::Enhanced;
266  
267 # simple "enhanced" JSON with comments in 3 styles: C,shell,CPP
268 my $configdata = <<'EOJ';
269 {
270 /* 'a' is ... */
271 "a" : "abc",
272 # b is ...
273 "b" : [1,2,3],
274 "c" : 12 // c is ...
275 }
276 EOJ
277 my $perldata = config2perl({
278 'string' => $configdata,
279 'commentstyle' => "C,shell,CPP",
280 });
281 die "call to config2perl() has failed" unless defined $perldata;
282 # the standard JSON:
283 # {"a" : "abc","b" : [1,2,3], "c" : 12}
284  
285  
286 # this "enhanced" JSON demonstrates the use of variables
287 # which will be substituted during the transformation to
288 # standard JSON with user-specified data.
289 # Notice that the opening and closing tags enclosing variable
290 # names can be customised using the 'tags' input parameter,
291 # so as to avoid clashes with content in the JSON.
292 my $configdata = <<'EOJ';
293 {
294 "d" : [1,2,<% tempvar0 %>],
295 "configfile" : "<%SCRIPTDIR%>/config/myapp.conf",
296 "username" : "<% username %>"
297 }
298 }
299 EOJ
300 my $perldata = config2perl({
301 'string' => $configdata,
302 'commentstyle' => "C,shell,CPP",
303 # optionally customise the tags enclosing the variables
304 # when you want to avoid clashes with other strings in JSON
305 #'tags' => ['<%', '%>'], # <<< these are the default values
306 # user-specified data to replace the variables in
307 # the "enhanced" JSON above:
308 'variable-substitutions' => {
309 'tempvar0' => 42,
310 'username' => getlogin(),
311 'SCRIPTDIR' => $FindBin::Bin,
312 },
313 });
314 die "call to config2perl() has failed" unless defined $perldata;
315 # the standard JSON
316 # (notice how all variables in <%...%> are now replaced):
317 # {"d" : [1,2,42],
318 # "username" : "yossarian",
319 # "configfile" : "/home/yossarian/B52/config/myapp.conf"
320 # }
321  
322  
323 # this "enhanced" JSON demonstrates "verbatim sections"
324 # the puprose of which is to make more readable JSON strings
325 # by allowing them to span over multiple lines.
326 # There is also no need for escaping double quotes.
327 # template variables (like above) will be substituted
328 # There will be no comments removal from the verbatim sections.
329 my $configdata = <<'EOJ';
330 {
331 "a" : <%begin-verbatim-section%>
332 This is a multiline
333 string
334 "quoted text" and 'quoted like this also'
335 will be retained in the string escaped.
336 White space from beginning and end will be chomped.
337
338 <%end-verbatim-section%>
339 ,
340 "b" = 123
341 }
342 EOJ
343 my $perldata = config2perl({
344 'string' => $configdata,
345 'commentstyle' => "C,shell,CPP",
346 });
347 die "call to config2perl() has failed" unless defined $perldata;
348 # the standard JSON (notice that "a" value is in a single line,
349 # here printed broken for readability):
350 # {"a" :
351 # "This is a multiline\nstring\n\"quoted text\" and 'quoted like
352 # this also'\nwill be retained in the string escaped.\nComments
353 # will not be removed.\nWhite space from
354 # beginning and end will be chomped.",
355 # "b" : 123
356 # };
357  
358  
359 =head1 EXPORT
360  
361 =over 4
362  
363 =item * C<config2perl> is exported by default.
364  
365 =back
366  
367  
368 =head1 SUBROUTINES
369  
370 =head2 C<config2perl>
371  
372 my $ret = config2perl($params);
373 die unless defined $ret;
374  
375 Arguments:
376  
377 =over 4
378  
379 =item * C<$params> : a hashref of input parameters.
380  
381 =back
382  
383 Return value:
384  
385 =over 4
386  
387 =item * the parsed content as a Perl data structure
388 on success or C<undef> on failure.
389  
390 =back
391  
392 Given input content in L<ENHANCED JSON FORMAT>, this sub removes comments
393 (as per preferences via input parameters),
394 replaces all template variables, if any,
395 compacts L<Verbatim Sections>, if any, into a single-line
396 string and then parses
397 what remains as standard JSON into a Perl data structure
398 which is returned to caller. JSON parsing is done with
399 L<Data::Roundtrip::json2perl>, which uses L<JSON>.
400  
401 Comments outside of JSON fields will always be removed,
402 otherwise JSON can not be parsed.
403  
404 Comments inside of JSON fields, keys, values, strings etc.
405 will not be removed unless input parameter C<remove-comments-in-strings>
406 is set to 1 by the caller.
407  
408 Comments (or what looks like comments with the current input parameters)
409 inside L<Verbatim Sections> will never be removed.
410  
411 The input content to-be-parsed can be specified
412 with one of the following input parameters (entries in the
413 C<$params>):
414  
415 =over 4
416  
417 =item * C<filename> : content is read from a file with this name.
418  
419 =item * C<filehandle> : content is read from a file which has already
420 been opened for reading by the caller.
421  
422 =item * C<string> : content is contained in this string.
423  
424 =back
425  
426 Additionally, input parameters can contain the following keys:
427  
428 =over 4
429  
430 =item * C<commentstyle> : specify what comment style(s) to be expected
431 in the input content (if any) as a B<comma-separated string>. For example
432 C<'C,CPP,shell,custom(E<lt>E<lt>)(E<gt>E<gt>),custom(REM)()'>.
433 These are the values it understands:
434  
435 =over 2
436  
437 =item * C<C> : comments take the form of C-style comments which
438 are exclusively within C</* and */>. For example C<* I am a comment */>.
439 This is the B<default comment style> if none specified.
440  
441 =item * C<CPP> : comments can the the form of C++-style comments
442 which are within C</* and */> or after C<//> until the end of line.
443 For example C</* I am a comment */>, C<// I am a comment to the end of line>.
444  
445 =item * C<shell> : comments can be after C<#> until the end of line.
446 For example, C<# I am a comment to the end of line>.
447  
448 =item * C<custom> : comments are enclosed (or preceded) by custom,
449 user-specified tags. The form is C<custom(OPENINGTAG)(CLOSINGTAG)>.
450 C<OPENINGTAG> is required. C<CLOSINGTAG> is optional meaning that
451 the comment extends to the end of line (just like C<shell> comments).
452 For example C<custom(E<lt>E<lt>)(E<gt>E<gt>)> or
453 C<custom({{)(})> or C<custom(REM)()> or C<custom(E<lt>E<lt>E<lt>E<lt>)(E<gt>E<gt>)>.
454 C<OPENINGTAG> and C<CLOSINGTAG> do not need to be of
455 the same character length as it is
456 obvious from the previous example. A word of warning:
457 the regex for identifying comments (and variables and verbatim sections)
458 has the custom tags escaped for special regex characters
459 (with the C<\Q ... \E> construct). So you are pretty safe in using
460 any character. Please report weird behaviour.
461  
462 B<Warning> : either opening or closing comment tags must not
463 be the same as opening or closing variables / verbatim section tags.
464  
465 =back
466  
467 =item * C<variable-substitutions> : a hashref whose keys are
468 variable names as they occur in the input I<Enhanced JSON> content
469 and their corresponding values should substitute them. I<Enhanced JSON>,
470 can contain template variables in the form C<E<lt>% my-var-1 %E<gt>>. These
471 must be replaced with data which is supplied to the call of C<config2perl()>
472 under the parameters key C<variable-substitutions>, for example:
473
474 config2perl({
475 "variable-substitutions" => {
476 "my-var-1" => 42,
477 "SCRIPTDIR" => "/home/abc",
478 },
479 "string" => '{"a":"<% my-var-1 %>", "b":"<% SCRIPTDIR %>/app.conf"}',
480 });
481  
482 Variable substitution will be performed in both
483 keys and values of the input JSON, including L<Verbatim Sections>.
484  
485 =item * C<remove-comments-in-strings> : by default no attempt
486 to remove what-looks-like-comments from JSON strings
487 (both keys and values). However, if this flag is set to
488 C<1> anything that looks like comments (as per the 'C<commentstyle>'
489 parameter) will be removed from inside all JSON strings
490 (keys or values) unless they were part of verbatim section.
491  
492 This does not apply for the content verbatim sections.
493 What looks like comments to us, inside verbatim sections
494 will be left intact.
495  
496 For example consider the JSON string C<"hello/*a comment*/">
497 (which can be a key or a value). If C<remove-comments-in-strings> is
498 set to 1, then the JSON string will become C<hello>. If set to
499 0 (which is the default) it will be unchanged.
500  
501 =item * C<tags> : specify the opening and closing tags for template
502 variables and verbatim section as an ARRAYref of exactly 2 items (the
503 opening and the closing tags). By default the opening tag is C<E<gt>%>
504 and the closing tag is C<%E<lt>>. A word of warning:
505 the regex for identifying variables and verbatim sections (and comments)
506 has the custom tags escaped for special regex characters
507 (with the C<\Q ... \E> construct). So you are pretty safe in using
508 any character. Please report weird behaviour.
509  
510 If you set C<tags => [ '[::', '::]' ]>
511 then your template variables should look like this: C<{:: var1 ::]> and
512 verbatim sections like this: C<[:: begin-verbatim-section ::]>.
513  
514 =item * C<debug> : set this to a positive integer to increase verbosity
515 and dump debugging messages. Default is zero for zero verbosity.
516  
517 =back
518  
519 See section L<ENHANCED JSON FORMAT> for details on the format
520 of B<what I call> I<enhanced JSON>.
521  
522 C<config2perl> returns the parsed content as a Perl data structure
523 on success or C<undef> on failure.
524  
525  
526 =head1 ENHANCED JSON FORMAT
527  
528 This is JSON with added reasonable, yet completely ad-hoc, enhancements
529 (from my point of view).
530  
531 These enhancements are:
532  
533 =over 4
534  
535 =item * B<Comments are allowed>:
536  
537 =over 2
538  
539 =item * C<C>-style comments take the form of C-style comments which
540 are exclusively within C</* and */>. For example C<* I am a comment */>
541  
542 =item * C<C++>-style comments can the the form of C++-style comments
543 which are within C</* and */> or after C<//> until the end of line.
544 For example C</* I am a comment */>, C<// I am a comment to the end of line.>
545  
546 =item * C<shell>-style comments can be after C<#> until the end of line.
547 For example, C<# I am a comment to the end of line.>
548  
549 =item * comments with C<custom>, user-specified, opening and
550 optional closing tags
551 which allows fine-tuning the process of deciding on something being a
552 comment.
553  
554 =back
555  
556 =item * B<Template variables support> : template-style
557 variables in the form of C<E<lt>% HOMEDIR %E<gt>>
558 will be substituded with values specified by the
559 user during parsing. Note that variable
560 names are case sensitive, they can contain spaces, hyphens etc.,
561 for example: C<E<lt>% abc- 123 - xyz %E<gt>> (the variable
562 name is C<abc- 123 - xyz>, notice
563 the multiple spaces between C<123> and C<xyz> and
564 also notice the absence of any spaces before C<abc> and after C<xyz>).
565  
566 The tags for denoting a template variable
567 are controled by the 'C<tags>' parameter to the sub L<config2perl>.
568 Defaults are C<E<lt>%> and C<%E<gt>>.
569  
570 =item * B<Verbatim Sections> : similar to here-doc, this feature allows
571 for string values to span over multiple lines and to contain
572 un-escpaed quotes. This is useful if you want a JSON value to
573 contain a shell script, for example. Verbatim sections can
574 also contain template variables which will be substituted. No
575 comment will be removed.
576  
577 =item * Unfortunately, there is not support for ignoring B<superfluous commas> in JSON,
578 in the manner of glorious Perl.
579  
580 B<Warning> : either opening or closing comment tags must not
581 be the same as opening or closing variables / verbatim section tags.
582  
583 =back
584  
585 =head2 Verbatim Sections
586  
587 A B<Verbaitm Section> in this ad-hoc, so-called I<Enhanced JSON> is content
588 enclosed within C<E<lt>%begin-verbatim-section%E<gt>>
589 and C<E<lt>%end-verbatim-section%E<gt>> tags.
590 A verbatim section's content may span multiple lines (which when converted to JSON will preserve them
591 by escaping. e.g. by replacing them with 'C<\n>') and can
592 contain template variables to be substituted with user-specified data.
593 All single and double quotes can be left un-escaped, the program will
594 escape them (hopefully correctly!).
595  
596 The content of Verbatim Sections will have all its
597 template variables substituted. Comments will
598 be left untouched.
599  
600 The tags for denoting the opening and closing a verbatim section
601 are controled by the 'C<tags>' parameter to the sub L<config2perl>.
602 Defaults are C<E<lt>%> and C<%E<gt>>.
603  
604 Here is an example of enhanced JSON which contains comments, a verbatim section
605 and template variables:
606  
607 my $con = <<'EOC';
608 {
609 "long bash script" : ["/usr/bin/bash",
610 /* This is a verbatim section */
611 <%begin-verbatim-section%>
612 # save current dir, this comment remains
613 pushd . &> /dev/null
614 # following quotes will be escaped
615 echo "My 'appdir' is \"<%appdir%>\""
616 echo "My current dir: " $(echo $PWD) " and bye"
617 # go back to initial dir
618 popd &> /dev/null
619 <%end-verbatim-section%>
620 /* the end of the verbatim section */
621 ],
622 // this is an example of a template variable
623 "expected result" : "<% expected-res123 %>"
624 }
625 EOC
626  
627 # Which, can be processed thusly:
628 my $res = config2perl({
629 'string' => $con,
630 'commentstyle' => 'C,CPP',
631 'variable-substitutions' => {
632 'appdir' => Cwd::abs_path($FindBin::Bin),
633 'expected-res123' => 42
634 },
635 });
636 die "call to config2perl() has failed" unless defined $res;
637  
638 # following is the dump of $res, note the breaking of the lines
639 # in the 'long bash script' is just for readability.
640 # In reality, it is one long line:
641 {
642 "expected result" => 42,
643 "long bash script" => [
644 "/usr/bin/bash",
645 "# save current dir, this comment remains\npushd . &> /dev/null\n
646 # following quotes will be escaped\necho \"My 'appdir' is
647 \\\"/home/babushka/Config-JSON-Enhanced/t\\\"\"\n
648 echo \"My current dir: \" \$(echo \$PWD) \" and bye\"\n# go back to
649 initial dir, this comment remains\npopd &> /dev/null"
650 ]
651 };
652  
653 A JSON string can contain comments which
654 you may want to retain (note:
655 comments filtering will not apply to verbatim sections).
656  
657 For example if the
658 content is a unix shell script it is
659 possible to contain comments like C<# comment>.
660 These will be removed along with all other comments
661 in the entire JSON input if you are using
662 C<shell> style comments. Another problem
663 is when JSON string contains comment opening
664 or closing tags. For example consider this
665 cron spec : C<*/15 * * * *> which contains
666 the closing string of a C-style comment and
667 will cass a big mess.
668  
669 You have two options
670 in order to deal with this problem:
671  
672 =over 2
673  
674 =item * Set 'remove-comments-in-strings'
675 parameter to sub L<config2perl> to 0. This will
676 keep ALL comments in all strings (both keys and values).
677 This is a one-size-fits-all solution and it is not ideal.
678  
679 =item * The B<best solution> is to change the comment style
680 of the input, so called Enhanced, JSON to something
681 different to the comments you are trying to keep in your
682 strings. So, for example, if you want to retain the comments
683 in a unix shell script then use C as the comment style for
684 the JSON.
685  
686 Note that it is possible (since version 0.03) to
687 use custom tags for comments. This greatly increases
688 your chances to make L<config2perl> understand what
689 comments you want to keep as part of your data.
690  
691 For example, make your comments like C<[::: comment :::]>
692 or even like C<E<lt>!-- comment --E<gt>> using
693 C<'commentstyle' =E<gt> 'custom([:::)(:::])'>
694 and C<'commentstyle' =E<gt> 'custom(E<lt>!--)(--E<gt>)'>,
695 respectively.
696  
697 =back
698  
699 =head1 TIPS
700  
701 You can change the tags used in denoting the template variables
702 and verbatim sections with the C<tags> parameter to the
703 sub L<config2perl>. Use this feature to change tags
704 to something else if your JSON contains
705 the same character sequence for these tags and avoid clashes
706 and unexpected substitutions. C<E<lt>%> and C<%E<gt>> are the default
707 tags.
708  
709 Similarly, C<custom> comment style (specifying what should be
710 the opening and, optionally, closing tags) can be employed if your
711 JSON strings contain something that looks like comments
712 and you want to avoid their removal.
713  
714 =head1 WARNINGS/CAVEATS
715  
716 In order to remove comments within strings, a simplistic regular
717 expression for
718 extracting quoted strings is employed. It finds anything
719 within two double quotes. It tries to handle escaped quotes within
720 quoted strings.
721 This regex may be buggy or may not
722 be complex enough to handle all corner cases. Therefore, it is
723 possible that setting parameter C<remove-comments-in-strings> to 1
724 to sub L<config2perl> to cause unexpected results. Please
725 report these cases, see L<SUPPORT>.
726  
727 The regex for identifying comments, variables and verbatim sections
728 has the custom tags escaped for special regex characters
729 (with the C<\Q ... \E> construct). So you are pretty safe in using
730 any character. Please report weird behaviour.
731  
732 =head1 AUTHOR
733  
734 Andreas Hadjiprocopis, C<< <bliako at cpan.org> >>
735  
736 =head1 HUGS
737  
738 ! Almaz !
739  
740  
741 =head1 BUGS
742  
743 Please report any bugs or feature requests to C<bug-config-json-enhanced at rt.cpan.org>, or through
744 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Config-JSON-Enhanced>. I will be notified, and then you'll
745 automatically be notified of progress on your bug as I make changes.
746  
747  
748 =head1 SUPPORT
749  
750 You can find documentation for this module with the perldoc command.
751  
752 perldoc Config::JSON::Enhanced
753  
754  
755 You can also look for information at:
756  
757 =over 4
758  
759 =item * RT: CPAN's request tracker (report bugs here)
760  
761 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Config-JSON-Enhanced>
762  
763 =item * CPAN Ratings
764  
765 L<https://cpanratings.perl.org/d/Config-JSON-Enhanced>
766  
767 =item * Search CPAN
768  
769 L<https://metacpan.org/release/Config-JSON-Enhanced>
770  
771 =back
772  
773  
774 =head1 ACKNOWLEDGEMENTS
775  
776  
777 =head1 LICENSE AND COPYRIGHT
778  
779 This software is Copyright (c) 2023 by Andreas Hadjiprocopis.
780  
781 This is free software, licensed under:
782  
783 The Artistic License 2.0 (GPL Compatible)
784  
785  
786 =cut
787  
788 15 1; # End of Config::JSON::Enhanced
↑ Summary script/configjson2json.pl »