| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use utf8; | ||
| 7 | |||
| 8 | our $VERSION = '0.10'; | ||
| 9 | |||
| 10 | binmode STDERR, ':encoding(UTF-8)'; | ||
| 11 | binmode STDOUT, ':encoding(UTF-8)'; | ||
| 12 | binmode STDIN, ':encoding(UTF-8)'; | ||
| 13 | |||
| 14 | use Getopt::Long qw(:config no_ignore_case); | ||
| 15 | |||
| 16 | use Config::JSON::Enhanced; | ||
| 17 | use Data::Roundtrip qw/perl2dump no-unicode-escape-permanently/; | ||
| 18 | |||
| 19 | my $OUTPUT_FILE = undef; | ||
| 20 | my %params = ( | ||
| 21 | 'commentstyle' => 'custom(</*)(*/>)', | ||
| 22 | 'tags' => ['<%', '%>'] | ||
| 23 | ); | ||
| 24 | my %dr_params = ( | ||
| 25 | 'dont-bloody-escape-unicode' => 1, | ||
| 26 | 'terse' => 0, | ||
| 27 | 'indent' => 1 | ||
| 28 | ); | ||
| 29 | sub usage { return | ||
| 30 | "Usage : $0 [--I inputstring] [--i 'afile.json'] [--o afile] [--c commentstyle] [--tags tags] [--(no-)escape-unicode|-e] [--(no-)terse] [--(no-)indent]\n" | ||
| 31 | ."\nIt will read an Enhanced-JSON string from command line (-I), or from a file (-i)\n" | ||
| 32 | ."\nor from STDIN (beware 4K limit on linux terminal, see CAVEATS for workaround).\n" | ||
| 33 | ."It will print its contents as a Perl variable (dump) to STDOUT or to a file (--o).\n" | ||
| 34 | ."It can escape/un-escape unicode characters (--escape-unicode) and/or --terse and/or --indent.\n" | ||
| 35 | } | ||
| 36 | if( ! Getopt::Long::GetOptions( | ||
| 37 | 'i=s' => \$params{'filename'}, | ||
| 38 | 'I=s' => sub { $params{'string'} = Encode::decode_utf8($_[1]) }, | ||
| 39 | 'o=s' => \$OUTPUT_FILE, | ||
| 40 | 'commentstyle|c=s' => \$params{'commentstyle'}, | ||
| 41 | 'tags|t=s' => \$params{'tags'}, | ||
| 42 | 'terse|r!' => \$dr_params{'terse'}, | ||
| 43 | 'indent|d!' => \$dr_params{'indent'}, | ||
| 44 | 'escape-unicode|e!' => sub { $dr_params{'dont-bloody-escape-unicode'} = $_[1] ? 0 : 1 }, | ||
| 45 | ) ){ die usage() } | ||
| 46 | |||
| 47 | if( ! exists($params{'filename'}) && ! exists($params{'string'}) ){ | ||
| 48 | # read from STDIN | ||
| 49 | $params{'string'} = do { local $/; <STDIN> } | ||
| 50 | } | ||
| 51 | |||
| 52 | my $result = Config::JSON::Enhanced::config2perl(\%params); | ||
| 53 | if( ! defined $result ){ print STDERR "$0 : error, call to ".'Config::JSON::Enhanced::config2perl()'." has failed.\n"; exit(1) } | ||
| 54 | |||
| 55 | if( defined $OUTPUT_FILE ){ | ||
| 56 | my $FH; | ||
| 57 | if( ! open($FH, '>', $$OUTPUT_FILE) ){ | ||
| 58 | print STDERR "$0 : error, failed to open output file '$OUTPUT_FILE', $!\n"; | ||
| 59 | print STDOUT perl2dump($result, \%dr_params); | ||
| 60 | } else { | ||
| 61 | print $FH perl2dump($result, \%dr_params); | ||
| 62 | close $FH; | ||
| 63 | } | ||
| 64 | } else { | ||
| 65 | print STDOUT perl2dump($result, \%dr_params); | ||
| 66 | } | ||
| 67 | 1; | ||
| 68 | __END__ |