IO/Moose/File.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 32 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 285 CC 26 SCAR 40.1
CC
26
Cov
0%
sysopen
110.0
open
90.0
binmode
56.0
CRAP 55.0
1 #!/usr/bin/perl -c
2  
3 package IO::Moose::File;
4  
5 =head1 NAME
6  
7 IO::Moose::File - Reimplementation of IO::File with improvements
8  
9 =head1 SYNOPSIS
10  
11 use IO::Moose::File;
12 my $file = IO::Moose::File->new( file => "/etc/passwd" );
13 my @passwd = $file->getlines;
14  
15 =head1 DESCRIPTION
16  
17 This class provides an interface mostly compatible with L<IO::File>. The
18 differences:
19  
20 =over
21  
22 =item *
23  
24 It is based on L<Moose> object framework.
25  
26 =item *
27  
28 It uses L<Exception::Base> for signaling errors. Most of methods are throwing
29 exception on failure.
30  
31 =item *
32  
33 It doesn't export any constants. Use L<Fcntl> instead.
34  
35 =back
36  
37 =for readme stop
38  
39 =cut
40  
41  
42 use 5.008;
43 use strict;
44 use warnings FATAL => 'all';
45  
46 our $VERSION = '0.1004';
47  
48 use Moose;
49  
50  
51 =head1 INHERITANCE
52  
53 =over 2
54  
55 =item *
56  
57 extends L<IO::Moose::Seekable>
58  
59 =over 2
60  
61 =item *
62  
63 extends L<IO::Moose::Handle>
64  
65 =over 2
66  
67 =item *
68  
69 extends L<MooseX::GlobRef::Object>
70  
71 =over 2
72  
73 =item *
74  
75 extends L<Moose::Object>
76  
77 =back
78  
79 =back
80  
81 =back
82  
83 =item *
84  
85 extends L<IO::File>
86  
87 =over 2
88  
89 =item *
90  
91 extends L<IO::Seekable>
92  
93 =over 2
94  
95 =item *
96  
97 extends L<IO::Handle>
98  
99 =back
100  
101 =back
102  
103 =back
104  
105 =cut
106  
107 extends 'IO::Moose::Seekable', 'IO::File';
108  
109  
110 use MooseX::Types::OpenModeWithLayerStr;
111 use MooseX::Types::PerlIOLayerStr;
112  
113  
114 =head1 EXCEPTIONS
115  
116 =over
117  
118 =item L<Exception::Argument>
119  
120 Thrown whether method is called with wrong argument.
121  
122 =item L<Exception::Fatal>
123  
124 Thrown whether fatal error is occurred by core function.
125  
126 =back
127  
128 =cut
129  
130 use Exception::Base (
131 '+ignore_package' => [ __PACKAGE__, 'Carp', 'File::Temp' ],
132 );
133  
134  
135 use constant::boolean;
136 use English '-no_match_vars';
137  
138 use Scalar::Util 'looks_like_number', 'reftype';
139  
140  
141 # For new_tmpfile
142 use File::Temp;
143  
144  
145 # Assertions
146 use Test::Assert ':assert';
147  
148 # Debugging flag
149 use if $ENV{PERL_DEBUG_IO_MOOSE_FILE}, 'Smart::Comments';
150  
151  
152 =head1 ATTRIBUTES
153  
154 =over
155  
156 =item file : Str|FileHandle|OpenHandle {ro}
157  
158 File (file name, file handle or IO object) as a parameter for new object or
159 C<open> method.
160  
161 =cut
162  
163 has '+file' => (
164 isa => 'Str | FileHandle | OpenHandle',
165 );
166  
167 =item mode : OpenModeWithLayerStr|CanonOpenModeStr = "<" {ro}
168  
169 File mode as a parameter for new object or C<open> method. Can be Perl-style
170 string (E<lt>, E<gt>, E<gt>E<gt>, etc.) with optional PerlIO layer after colon
171 (i.e. C<E<lt>:encoding(UTF-8)>) or C-style string (C<r>, C<w>, C<a>, etc.)
172  
173 =cut
174  
175 has '+mode' => (
176 isa => 'OpenModeWithLayerStr | CanonOpenModeStr',
177 );
178  
179 =item sysmode : Num {ro}
180  
181 File mode as a parameter for new object or C<sysopen> method. Can be decimal
182 number (C<O_RDONLY>, C<O_RDWR>, C<O_CREAT>, other constants from standard
183 module L<Fcntl>).
184  
185 =cut
186  
187 has 'sysmode' => (
188 is => 'ro',
189 isa => 'Num',
190 writer => '_set_sysmode',
191 clearer => '_clear_sysmode',
192 predicate => 'has_sysmode',
193 );
194  
195 =item perms : Num = 0666 {ro}
196  
197 Permissions to use in case a new file is created and mode was decimal number.
198 The permissions are always modified by umask.
199  
200 =cut
201  
202 has 'perms' => (
203 is => 'ro',
204 isa => 'Num',
205 default => oct(666),
206 lazy => TRUE,
207 reader => 'perms',
208 writer => '_set_perms',
209 clearer => '_clear_perms',
210 predicate => 'has_perms',
211 );
212  
213 =item layer : PerlIOLayerStr = "" {ro}
214  
215 PerlIO layer string.
216  
217 =cut
218  
219 has 'layer' => (
220 is => 'ro',
221 isa => 'PerlIOLayerStr',
222 reader => 'layer',
223 writer => '_set_layer',
224 clearer => '_clear_layer',
225 predicate => 'has_layer',
226 );
227  
228 =back
229  
230 =cut
231  
232  
233 use namespace::clean -except => 'meta';
234  
235  
236 ## no critic qw(ProhibitBuiltinHomonyms)
237 ## no critic qw(RequireArgUnpacking)
238 ## no critic qw(RequireCheckingReturnValueOfEval)
239  
240 =head1 CONSTRUCTORS
241  
242 =over
243  
244 =item new( I<args> : Hash ) : Self
245  
246 Creates an object. If I<file> is defined and is a string or array
247 reference, the C<open> method is called; if the open fails, the object
248 is destroyed. Otherwise, it is returned to the caller.
249  
250 $io = IO::Moose::File->new;
251 $io->open("/etc/passwd");
252  
253 $io = IO::Moose::File->new( file => "/var/log/perl.log", mode => "a" );
254  
255 If I<file> is a file handler, the C<fdopen> method is called.
256  
257 $tmp = IO::Moose::File->new( file => \*STDERR, mode => 'w' );
258 $tmp->say("Some important message");
259  
260 If I<layer> is defined, the C<binmode> method is called.
261  
262 $io = IO::Moose::File->new( file => "test.txt", layer => ":utf8" );
263  
264 =cut
265  
266 override '_open_file' => sub {
267 ### IO::Moose::File::_open_file: @_
268  
269 my ($self) = @_;
270  
271 # Open file with our method
272 if ($self->has_file) {
273 # call fdopen if it was handler
274 if ((reftype $self->file || '') eq 'GLOB') {
275 $self->fdopen( $self->file, $self->mode );
276 if ($self->has_layer) {
277 $self->binmode( $self->layer );
278 };
279 return TRUE;
280 }
281 else {
282 # call open otherwise
283 if ($self->has_perms) {
284 $self->open( $self->file, $self->mode, $self->perms );
285 }
286 else {
287 $self->open( $self->file, $self->mode );
288 };
289 if (defined $self->layer) {
290 $self->binmode( $self->layer );
291 };
292 return TRUE;
293 };
294 };
295  
296 return FALSE;
297 };
298  
299 =item new_tmpfile( I<args> : Hash ) : Self
300  
301 Creates the object with opened temporary and anonymous file for read/write.
302 If the temporary file cannot be created or opened, the object is destroyed.
303 Otherwise, it is returned to the caller.
304  
305 All I<args> will be passed to the L<File::Temp> and L<IO::Moose::Handle>
306 constructors.
307  
308 $io = IO::Moose::File->new_tmpfile( UNLINK => 1, SUFFIX => '.jpg' );
309 $pos = $io->getpos; # save position
310 $io->say("foo");
311 $io->setpos($pos); # rewind
312 $io->slurp; # prints "foo"
313  
314 $tmp = IO::Moose::File->new_tmpfile( output_record_separator => "\n" );
315 $tmp->print("say"); # with eol
316  
317 =cut
318  
319 sub new_tmpfile {
320 ### IO::Moose::File::new_tmpfile: @_
321  
322 my $class = shift;
323  
324 my $io;
325  
326 eval {
327 # Pass arguments to File::Temp constructor
328 my $tmp = File::Temp->new( @_ );
329  
330 # create new empty object with new default mode
331 $io = $class->new( @_, file => $tmp, mode => '+>', copyfh => TRUE );
332 };
333 if ($EVAL_ERROR) {
334 my $e = Exception::Fatal->catch;
335 $e->throw( message => 'Cannot new_tmpfile' );
336 };
337 assert_not_null($io) if ASSERT;
338  
339 return $io;
340 };
341  
342 =back
343  
344 =head1 METHODS
345  
346 =over
347  
348 =item open( I<file> : Str, I<mode> : OpenModeWithLayerStr|CanonOpenModeStr = "<" ) : Self
349  
350 Opens the I<file> with L<perlfunc/open> function and returns self object.
351  
352 $io = IO::Moose::File->new;
353 $io->open("/etc/passwd");
354  
355 $io = IO::Moose::File->new;
356 $io->open("/var/tmp/output", "w");
357  
358 =cut
359  
360 # Wrapper for CORE::open
361 sub open {
362 ### IO::Moose::File::open: @_
363 my $self = shift;
364  
365 Exception::Argument->throw(
366 message => 'Usage: $io->open(FILENAME [,MODE]) or $io->open(FILENAME, IOLAYERS)'
367 ) if not blessed $self or @_ < 1 or @_ > 2 or ref $_[0];
368  
369 my ($file, $mode) = @_;
370 my $layer = '';
371  
372 my $status;
373 eval {
374 # check constraints
375 $file = $self->_set_file($file);
376 $mode = defined $mode ? $self->_set_mode($mode) : do { $self->_clear_mode; $self->mode };
377  
378 if ($mode =~ s/(:.*)//) {
379 $layer = $self->_set_layer($1);
380 $mode = $self->_set_mode($mode);
381 };
382  
383 ### open: "open(fh, $mode, $file)"
384 $status = CORE::open( $self->fh, $mode, $file );
385 };
386 if (not $status) {
387 $self->_set_error(TRUE);
388 my $e = $EVAL_ERROR ? Exception::Fatal->catch : Exception::IO->new;
389 $e->throw( message => 'Cannot open' );
390 };
391 assert_true($status) if ASSERT;
392  
393 $self->_set_error(FALSE);
394  
395 $self->_open_tied if $self->tied;
396  
397 if (${^TAINT} and not $self->tainted) {
398 $self->untaint;
399 };
400  
401 return $self;
402 };
403  
404 =item sysopen( I<file> : Str, I<sysmode> : Num, I<perms> : Num = 0600 ) : Self
405  
406 Opens the I<file> with L<perlfunc/sysopen> function and returns self object.
407 The I<sysmode> is decimal value (it can be C<O_XXX> constant from standard
408 module L<Fcntl>). The default I<perms> are set to C<0666>. The C<mode>
409 attribute is set based on I<sysmode> value.
410  
411 use Fcntl;
412 $io = IO::Moose::File->new;
413 $io->open("/etc/hosts", O_RDONLY);
414 print $io->mode; # prints "<"
415  
416 =cut
417  
418 sub sysopen {
419 ### IO::Moose::File::sysopen: @_
420 my $self = shift;
421  
422 Exception::Argument->throw(
423 message => 'Usage: $io->sysopen(FILENAME, SYSMODE [,PERMS]])'
424 ) if not blessed $self or @_ < 2 or @_ > 3 or ref $_[0];
425  
426 my ($file, $sysmode, $perms) = @_;
427 my $layer = '';
428  
429 my $status;
430 eval {
431 # check constraints
432 $file = $self->_set_file($file);
433 $sysmode = $self->_set_sysmode($sysmode);
434 $perms = defined $perms ? $self->_set_perms($perms) : do { $self->_clear_perms; $self->perms };
435  
436 # normalize mode string for tied handler
437 my $mode = ($sysmode & 2 ? '+' : '') . ($sysmode & 1 ? '>' : '<');
438 $self->_set_mode($mode);
439  
440 ### open: "sysopen(fh, $file, $mode, $perms)"
441 $status = CORE::sysopen( $self->fh, $file, $sysmode, $perms );
442 };
443 if (not $status) {
444 $self->_set_error(TRUE);
445 my $e = $EVAL_ERROR ? Exception::Fatal->catch : Exception::IO->new;
446 $e->throw( message => 'Cannot open' );
447 };
448 assert_true($status) if ASSERT;
449  
450 $self->_set_error(FALSE);
451  
452 $self->_open_tied if $self->tied;
453  
454 if (${^TAINT} and not $self->tainted) {
455 $self->untaint;
456 };
457  
458 return $self;
459 };
460  
461  
462 # Also clear sysmode on close
463 after 'close' => sub {
464 ### IO::Moose::File::close: @_
465  
466 my ($self) = @_;
467 $self->_clear_sysmode;
468  
469 return $self;
470 };
471  
472  
473 =item binmode(I<>) : Self
474  
475 =item binmode( I<layer> : PerlIOLayerStr ) : Self
476  
477 Sets binmode on the underlying IO object. On some systems (in general, DOS
478 and Windows-based systems) binmode is necessary when you're not working with
479 a text file.
480  
481 It can also sets PerlIO layer (C<:bytes>, C<:crlf>, C<:utf8>,
482 C<:encoding(XXX)>, etc.). More details can be found in L<PerlIO::encoding>.
483  
484 In general, C<binmode> should be called after C<open> but before any I/O is
485 done on the file handler.
486  
487 Returns self object.
488  
489 $io = IO::Moose::File->new( file => "/tmp/picture.png", mode => "w" );
490 $io->binmode;
491  
492 $io = IO::Moose::File->new( file => "/var/tmp/fromdos.txt" );
493 $io->binmode(":crlf");
494  
495 =cut
496  
497 # Wrapper for CORE::binmode
498 sub binmode {
499 ### IO::Moose::File::binmode: @_
500  
501 my $self = shift;
502  
503 Exception::Argument->throw(
504 message => 'Usage: $io->binmode([LAYER])'
505 ) if not blessed $self or @_ > 1;
506  
507 my ($layer) = @_;
508  
509 $layer = $self->_set_layer($layer) if defined $layer;
510  
511 my $status;
512 eval {
513 if (defined $layer) {
514 $status = CORE::binmode( $self->fh, $layer );
515 }
516 else {
517 $status = CORE::binmode( $self->fh );
518 };
519 };
520  
521 if (not $status) {
522 $self->_set_error(FALSE);
523 my $e = $EVAL_ERROR ? Exception::Fatal->catch : Exception::IO->new;
524 $e->throw( message => 'Cannot open' );
525 };
526 assert_true($status) if ASSERT;
527  
528 return $self;
529 };
530  
531 =back
532  
533 =cut
534  
535  
536 # Aliasing tie hooks to real functions
537 __PACKAGE__->meta->add_method( 'BINMODE' => sub {
538 ### IO::Moose::File::BINMODE: @_
539 shift()->binmode(@_);
540 } );
541  
542 __PACKAGE__->meta->add_method( 'OPEN' => sub {
543 ### IO::Moose::File::OPEN: @_
544 my $self = shift;
545 return $self->sysopen(@_) if defined $_[1] and looks_like_number $_[1];
546 return $self->open(@_);
547 } );
548  
549  
550 # Make immutable finally
551 __PACKAGE__->meta->make_immutable;
552  
553  
554 1;
555  
556  
557 =begin umlwiki
558  
559 = Class Diagram =
560  
561 [ IO::Moose::File
562 -----------------------------------------------------------------
563 +file : Str|FileHandle|OpenHandle {ro}
564 +mode : OpenModeWithLayerStr|CanonOpenModeStr = "<" {ro}
565 +sysmode : Num {ro}
566 +perms : Num = 0666 {ro}
567 +layer : PerlIOLayerStr = "" {ro}
568 -----------------------------------------------------------------
569 +new( args : Hash ) : Self
570 +new_tmpfile( args : Hash ) : Self
571 +open( file : Str, mode : OpenModeWithLayerStr|CanonOpenModeStr = "<" ) : Self
572 +sysopen( file : Str, sysmode : Num, perms : Num = 0600 ) : Self
573 +binmode() : Self
574 +binmode( layer : PerlIOLayerStr ) : Self
575 ]
576  
577 [IO::Moose::File] ---|> [IO::Moose::Seekable] [IO::File]
578  
579 [IO::Moose::File] ---> <<exception>> [Exception::Fatal] [Exception::IO]
580  
581 =end umlwiki
582  
583 =head1 SEE ALSO
584  
585 L<IO::File>, L<IO::Moose>, L<IO::Moose::Handle>, L<IO::Moose::Seekable>,
586 L<File::Temp>.
587  
588 =head1 BUGS
589  
590 The API is not stable yet and can be changed in future.
591  
592 =for readme continue
593  
594 =head1 AUTHOR
595  
596 Piotr Roszatycki <dexter@cpan.org>
597  
598 =head1 LICENSE
599  
600 Copyright 2008, 2009 by Piotr Roszatycki <dexter@cpan.org>.
601  
602 This program is free software; you can redistribute it and/or modify it
603 under the same terms as Perl itself.
604  
605 See L<http://www.perl.com/perl/misc/Artistic.html>