Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Check if the file is a zip archive or not

  • Loading branch information...
commit 2810786a4f9d2e92d0da38e69c9c3b4a2a499a7b 1 parent 1d1fff2
Alan Haggai Alavi authored
Showing with 24 additions and 1 deletion.
  1. +17 −0 lib/Archive/Zip/Parser.pm
  2. +6 −1 t/01_main.t
  3. +1 −0  test_files/not_a_zip
17 lib/Archive/Zip/Parser.pm
View
@@ -3,6 +3,8 @@ package Archive::Zip::Parser;
use strict;
BEGIN { $^W = 1 }
+use constant CHUNK_SIZE => 10_240;
+
sub new {
my ( $self, $file ) = @_;
@@ -12,7 +14,22 @@ sub new {
open my $fh, "<$file" or die "Error opening file[$file]: $!";
+ # Check if the file is a zip file or not. All zip files begin with the
+ # 0x504B0304 signature. However, the signature can be anywhere in the file.
+ # Skip until it is found.
+
+ my $chunk;
+ read $fh, $chunk, CHUNK_SIZE;
+
+ my $signature = q{\x50\x4B\x03\x04};
+ while ( defined $fh && $chunk !~ /$signature/ ) {
+ die "$file is not a zip file";
+ }
+
+ # now the file handle points just after the signature
+
return bless { 'fh' => $fh }, shift;
}
+
1;
7 t/01_main.t
View
@@ -3,7 +3,7 @@
use strict;
BEGIN { $^W = 1 }
-use Test::More 'tests' => 4;
+use Test::More 'tests' => 5;
use_ok 'Archive::Zip::Parser';
my $parser;
@@ -25,3 +25,8 @@ eval {
$parser = Archive::Zip::Parser->new('test_files/foo.zip');
};
is !$@, 1, 'new: opens existing file';
+
+eval {
+ $parser = Archive::Zip::Parser->new('test_files/not_a_zip');
+};
+like $@, qr/not a zip file/, 'new: not a zip file';
1  test_files/not_a_zip
View
@@ -0,0 +1 @@
+This is not a zip file!
Please sign in to comment.
Something went wrong with that request. Please try again.