From 537ca8dec1982d32e1b6ff49478d2702d4621083 Mon Sep 17 00:00:00 2001 From: Michael Pyne Date: Wed, 20 Dec 2017 19:01:06 -0500 Subject: [PATCH] persistence: Serialize persistent data as JSON instead of Perl code. Will eventually result in one less `eval`, though this change was actually mostly instigated from a desire to be able to run jq(1) on the raw data. --- modules/ksb/BuildContext.pm | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/modules/ksb/BuildContext.pm b/modules/ksb/BuildContext.pm index 8ce6403..a69c9fb 100644 --- a/modules/ksb/BuildContext.pm +++ b/modules/ksb/BuildContext.pm @@ -14,6 +14,7 @@ use File::Basename; # dirname use IO::File; use POSIX qw(strftime); use Errno qw(:POSIX); +use JSON::PP; # We derive from ksb::Module so that BuildContext acts like the 'global' # ksb::Module, with some extra functionality. @@ -766,25 +767,30 @@ sub loadPersistentOptions return unless $fh; + # $persistent_data should be a JSON object which we can store directly as a + # hash. my $persistent_data; { local $/ = undef; # Read in whole file with <> operator. $persistent_data = <$fh>; } - # $persistent_data should be Perl code which, when evaluated will give us - # a hash called persistent_options which we can then merge into our - # persistent options. - my $persistent_options; - # eval must appear after declaration of $persistent_options - eval $persistent_data; - if ($@) - { - # Failed. - error ("Failed to read persistent module data: r[b[$@]"); - return; + eval { $persistent_options = decode_json($persistent_data); }; + if ($@) { + # Apparently wasn't JSON, try falling back to old format for compat. + # Previously, this was a Perl code which, when evaluated would give + # us a hash called persistent_options which we can then merge into our + # persistent options. + # TODO: Remove compat code after 2018-06-30 + eval $persistent_data; # Runs Perl code read from file + if ($@) + { + # Failed. + error ("Failed to read persistent module data: r[b[$@]"); + return; + } } # We need to keep persistent data with the context instead of with the @@ -812,6 +818,7 @@ sub storePersistentOptions return if pretending(); my $fh = IO::File->new($self->persistentOptionFileName(), '>'); + my $json = JSON::PP->new->ascii->pretty; if (!$fh) { @@ -819,10 +826,9 @@ sub storePersistentOptions return; } - print $fh "# AUTOGENERATED BY kdesrc-build $SCRIPT_VERSION\n"; + my $encodedJSON = $json->encode($self->{persistent_options}); - $Data::Dumper::Indent = 1; - print $fh Data::Dumper->Dump([$self->{persistent_options}], ["persistent_options"]); + print $fh $encodedJSON; undef $fh; # Closes the file }