| 1 | # Copyright 2011-2026, Paul Johnson (paul@pjcj.net) | ||
| 2 | |||
| 3 | # This software is free. It is licensed under the same terms as Perl itself. | ||
| 4 | |||
| 5 | # The latest version of this software should be available from my homepage: | ||
| 6 | # https://pjcj.net | ||
| 7 | |||
| 8 | package Devel::Cover::DB::IO::JSON; | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | use warnings; | ||
| 12 | |||
| 13 | use base "Devel::Cover::DB::IO::Base"; | ||
| 14 | |||
| 15 | use JSON::MaybeXS (); | ||
| 16 | |||
| 17 | our $VERSION = '1.52'; # VERSION | ||
| 18 | |||
| 19 | sub new { | ||
| 20 | my $class = shift; | ||
| 21 | my %args = @_; | ||
| 22 | my $json = JSON::MaybeXS->new(utf8 => 1, allow_blessed => 1); | ||
| 23 | $json->ascii->pretty->canonical | ||
| 24 | if exists $args{options} && $args{options} =~ /\bpretty\b/i; | ||
| 25 | my $self = $class->SUPER::new(%args, json => $json); | ||
| 26 | bless $self, $class | ||
| 27 | } | ||
| 28 | |||
| 29 | sub read { | ||
| 30 | my $self = shift; | ||
| 31 | my ($file) = @_; | ||
| 32 | $self->_read_fh( | ||
| 33 | $file, | ||
| 34 | sub { | ||
| 35 | my ($fh) = @_; | ||
| 36 | local $/; | ||
| 37 | my $data = eval { $self->{json}->decode(<$fh>) }; | ||
| 38 | die "Can't read $file with ", (ref $self->{json}), ": $@" if $@; | ||
| 39 | $data | ||
| 40 | } | ||
| 41 | ) | ||
| 42 | } | ||
| 43 | |||
| 44 | sub write { | ||
| 45 | my $self = shift; | ||
| 46 | my ($data, $file) = @_; | ||
| 47 | $self->_write_fh( | ||
| 48 | $file, | ||
| 49 | sub { | ||
| 50 | my ($fh) = @_; | ||
| 51 | print $fh $self->{json}->encode($data); | ||
| 52 | } | ||
| 53 | ) | ||
| 54 | } | ||
| 55 | |||
| 56 | 1 | ||
| 57 | |||
| 58 | __END__ |