Subject: | LoadFile doesn't handle empty files. |
I just noticed some warnings in a test suite where LoadFile is passed a valid file handle to an
empty file. LoadFile doesn't check for this.
Attached is a patch with tests to fix this. I'm also sending you a github pull request with the
patch.
Subject: | patch.txt |
diff --git a/lib/YAML/Syck.pm b/lib/YAML/Syck.pm
index dd2a25d..449d5da 100644
--- a/lib/YAML/Syck.pm
+++ b/lib/YAML/Syck.pm
@@ -118,6 +118,7 @@ sub DumpFile {
sub LoadFile {
my $file = shift;
+ (!-e $file || -z $file )and die("Cannot load empty file");
if ( _is_openhandle($file) ) {
Load(do { local $/; <$file> });
}
diff --git a/t/11-loadfile.t b/t/11-loadfile.t
index 17f21b5..fd1c1b1 100644
--- a/t/11-loadfile.t
+++ b/t/11-loadfile.t
@@ -9,7 +9,7 @@ unless (-w $RealBin) {
exit;
}
-plan tests => 8;
+plan tests => 11;
*::LoadFile = *YAML::Syck::LoadFile;
@@ -36,7 +36,11 @@ sub write_file {
# write YAML to a file
write_file('loadfile.yml', "---\na simple scalar");
-END { unlink 'loadfile.yml' or die "can't delete 'loadfile.yml': $!" if -e 'loadfile.yml' }
+write_file('emptyfile.yml', "");
+END {
+ unlink 'loadfile.yml' or die "can't delete 'loadfile.yml': $!" if -e 'loadfile.yml';
+ unlink 'emptyfile.yml' or die "can't delete 'emptyfile.yml': $!" if -e 'emptyfile.yml';
+}
# using file names
is(LoadFile('loadfile.yml'), "a simple scalar", 'LoadFile works with file names');
@@ -84,6 +88,20 @@ SKIP : {
] }
+
+{ # Load empty file fails
+ my $yml = eval {LoadFile('emptyfile.yml')};
+ like($@, qr/^Cannot load empty file at/ms, "LoadFile dies loading an empty file");
+ is($yml, undef, "LoadFile returns undef loading an empty file");
+}
+
+{ # Load empty file handle fails
+ open(my $fh, '<', 'emptyfile.yml') or die;
+ my $yml = eval {LoadFile($fh)};
+ like($@, qr/^Cannot load empty file at/ms, "LoadFile dies loading an empty file");
+ is($yml, undef, "LoadFile returns undef loading an empty file");
+}
+
__DATA__
---
a simple scalar