1

conf.pm: Use JSON::XS insead of PP, improve error handling

This commit is contained in:
eleksir
2020-04-12 02:12:59 +03:00
parent 694f64e501
commit 58dbe97064

View File

@@ -2,9 +2,10 @@ package conf;
use strict; use strict;
use warnings "all"; use warnings "all";
use diagnostics;
use vars qw/$VERSION/; use vars qw/$VERSION/;
use JSON::PP; use Fcntl qw(O_WRONLY O_CREAT O_TRUNC);
use JSON::XS;
use utf8;
use Exporter qw(import); use Exporter qw(import);
our @EXPORT = qw(loadConf saveConf); our @EXPORT = qw(loadConf saveConf);
@@ -13,10 +14,21 @@ $VERSION = "1.0";
sub loadConf() { sub loadConf() {
my $c = "data/myapi.json"; my $c = "data/myapi.json";
my $sep = $/; open (C, "<", $c) or die "[FATA] No conf at $c: $!\n";
$/ = ''; my $len = (stat($c))[7];
open (C, $c) or die "No conf at $c\n"; my $json;
my $json = <C>; my $readlen = read(C, $json, $len);
unless ($readlen) {
close C;
die "[FATA] Unable to read $c: $!\n";
}
if ($readlen != $len) {
close C;
die "[FATA] File $c is $len bytes on disk, but we read only $readlen bytes\n";
}
close C; close C;
return decode_json($json); return decode_json($json);
} }
@@ -24,11 +36,26 @@ sub loadConf() {
sub saveConf($) { sub saveConf($) {
my $c = shift; my $c = shift;
my $file = "data/myapi.json"; my $file = "data/myapi.json";
my $j = JSON::PP->new->pretty->canonical->indent_length(4); my $j = JSON::XS->new->pretty->canonical->indent(1);
my $json = $j->encode($c); my $json = $j->encode($c);
$j = undef; undef $j;
use bytes;
my $len = length($json);
no bytes;
# TODO: make it transactional # TODO: make it transactional
open (C, ">", $file) or die "Unable to open $file\n"; sysopen (C, $file, O_WRONLY|O_CREAT|O_TRUNC) or die "[FATA] Unable to open $file: $!\n";
print C $json; binmode C, ':utf8';
my $written = syswrite(C, $json, $len);
unless (defined($written)) {
die "[FATA] Unable to write to $file: $!";
}
unless ($written != $len) {
die "[FATA] We wrote $written bytes to $file, bu buffer length id $len bytes\n";
}
close C; close C;
} }