Skip Menu |

This queue is for tickets about the File-Type CPAN distribution.

Report information
The Basics
Id: 76376
Status: new
Priority: 0/
Queue: File-Type

People
Owner: Nobody in particular
Requestors: DDICK [...] cpan.org
Cc:
AdminCc:

Bug Information
Severity: (no value)
Broken in: (no value)
Fixed in: (no value)



Subject: PATCH: Adding filehandle support
This patch adds another (tested) method to allow the user to pass file handles to the File::Type module.
Subject: file_type_handle.patch
diff -Naur old/lib/File/Type.pm new/lib/File/Type.pm --- old/lib/File/Type.pm 2004-05-06 20:54:42.000000000 +1000 +++ new/lib/File/Type.pm 2012-04-07 21:13:45.323214256 +1000 @@ -35,6 +35,19 @@ return $self->checktype_contents($argument); } +sub checktype_handle { + # reads in 16k of selected handle, or returns undef on failure + # then checks contents + + my($self, $fh) = @_; + my $pos = tell $fh; + if ($pos == -1) { return undef; } + seek $fh, 0, Fcntl::SEEK_SET() or return undef; + read $fh, my $data, 16*1024 or return undef; + seek $fh, $pos, Fcntl::SEEK_SET(); + return $self->checktype_contents($data); +} + sub checktype_filename { # reads in 16k of selected file, or returns undef if can't open, # then checks contents @@ -1510,6 +1523,9 @@ # alternatively, check file from disk my $type_from_file = $ft->checktype_filename($file); + # alternatively, check file from handle + my $type_from_handle = $ft->checktype_handle($handle); + # convenient method for checking either a file or data my $type_1 = $ft->mime_type($file); my $type_2 = $ft->mime_type($data); @@ -1534,6 +1550,11 @@ argument through to the relevant method below. If the argument is a directory, returns undef. +=head2 checktype_handle($handle) + +reads data from handle (if possible; if not, returns undef) and returns the MIME +type of the file. + =head2 checktype_filename($filename) Opens $filename (if possible; if not, returns undef) and returns the MIME diff -Naur old/t/01type.t new/t/01type.t --- old/t/01type.t 2004-05-06 20:54:42.000000000 +1000 +++ new/t/01type.t 2012-04-07 21:14:02.755448105 +1000 @@ -34,7 +34,7 @@ "files/0001.wav" => "audio/x-wav", }; -plan tests => 2 * scalar keys %{ $types }; +plan tests => 3 * scalar keys %{ $types }; =for testing @@ -53,6 +53,9 @@ foreach my $filename (sort keys %$types) { my $mimetype = $types->{$filename}; is($ft->checktype_filename("t/$filename"), $mimetype, "check file $filename"); + open FILE, "t/$filename" or die; + is($ft->checktype_handle(\*FILE), $mimetype, "check file $filename"); + close FILE or die; my $data = read_file("t/$filename") || die; is($ft->checktype_contents($data), $mimetype, "check data $filename"); }