Add check for wrong number of newlines at the end of the file
[catagits/Test-EOL.git] / lib / Test / EOL.pm
index 2a04267..accd162 100644 (file)
@@ -1,16 +1,15 @@
 package Test::EOL;
+# ABSTRACT: Check the correct line endings in your project
 
 use strict;
 use warnings;
 
 use Test::Builder;
 use File::Spec;
-use FindBin qw($Bin);
 use File::Find;
+use Cwd qw/ cwd /;
 
-use vars qw( $VERSION $PERL $UNTAINT_PATTERN $PERL_PATTERN);
-
-$VERSION = '0.7';
+use vars qw( $PERL $UNTAINT_PATTERN $PERL_PATTERN);
 
 $PERL    = $^X || 'perl';
 $UNTAINT_PATTERN  = qr|^([-+@\w./:\\]+)$|;
@@ -23,7 +22,8 @@ my %file_find_arg = ($] <= 5.006) ? () : (
 );
 
 my $Test  = Test::Builder->new;
-my $updir = File::Spec->updir();
+
+my $no_plan;
 
 sub import {
     my $self   = shift;
@@ -34,21 +34,28 @@ sub import {
         *{$caller.'::all_perl_files_ok'} = \&all_perl_files_ok;
     }
     $Test->exported_to($caller);
+
+    if ($_[0] && $_[0] eq 'no_plan') {
+        shift;
+        $no_plan = 1;
+    }
     $Test->plan(@_);
 }
 
 sub _all_perl_files {
     my @all_files = _all_files(@_);
-    return grep { _is_perl_module($_) || _is_perl_script($_) } @all_files;
+    return grep { _is_perl_module($_) || _is_perl_script($_) || _is_pod_file($_) } @all_files;
 }
 
 sub _all_files {
-    my @base_dirs = @_ ? @_ : File::Spec->catdir($Bin, $updir);
+    my @base_dirs = @_ ? @_ : cwd();
+    my $options = pop(@base_dirs) if ref $base_dirs[-1] eq 'HASH';
     my @found;
     my $want_sub = sub {
-        return if ($File::Find::dir =~ m![\\/]?CVS[\\/]|[\\/]?.svn[\\/]!); # Filter out cvs or subversion dirs/
+        return if ($File::Find::dir =~ m![\\/]?CVS[\\/]|[\\/]?\.svn[\\/]!); # Filter out cvs or subversion dirs/
         return if ($File::Find::dir =~ m![\\/]?blib[\\/]libdoc$!); # Filter out pod doc in dist
         return if ($File::Find::dir =~ m![\\/]?blib[\\/]man\d$!); # Filter out pod doc in dist
+        return if ($File::Find::dir =~ m![\\/]?inc!); # Filter out Module::Install stuff
         return if ($File::Find::name =~ m!Build$!i); # Filter out autogenerated Build script
         return unless (-f $File::Find::name && -r _);
         push @found, File::Spec->no_upwards( $File::Find::name );
@@ -62,27 +69,89 @@ sub _all_files {
     return @found;
 }
 
+# Formats various human invisible symbols
+# to similar visible ones.
+# Perhaps ^M or something like that
+# would be more appropriate?
+
+sub _show_whitespace {
+    my $string = shift;
+    $string =~ s/\r/[\\r]/g;
+    $string =~ s/\t/[\\t]/g;
+    $string =~ s/ /[\\s]/g;
+    return $string;
+}
+
+# Format a line record for diagnostics.
+
+sub _debug_line {
+    my ( $options, $line ) = @_;
+    $line->[2] =~ s/\n\z//g if defined $line->[2];
+    return "line $line->[1]: $line->[0]" . (
+        $options->{show_lines} && defined $line->[2]
+            ? qq{: } . _show_whitespace( $line->[2] )
+            : q{}
+    );
+}
+
 sub eol_unix_ok {
     my $file = shift;
     my $test_txt;
     $test_txt   = shift if !ref $_[0];
-    $test_txt ||= "No windows line endings in '$file'";
+    $test_txt ||= "No incorrect line endings in '$file'";
     my $options = shift if ref $_[0] eq 'HASH';
     $options ||= {
         trailing_whitespace => 0,
+        trailing_newline => 0,
+        all_reasons => 0,
     };
     $file = _module_to_path($file);
+
     open my $fh, $file or do { $Test->ok(0, $test_txt); $Test->diag("Could not open $file: $!"); return; };
+    # Windows-- , default is :crlf, which hides \r\n  -_-
+    binmode( $fh, ':raw' );
     my $line = 0;
+    my $blank_lines = 0;
+    my (@fails, %fails);
     while (<$fh>) {
         $line++;
-        if (
-           (!$options->{trailing_whitespace} && /\r$/) ||
-           ( $options->{trailing_whitespace} && /(\r|[ \t]+)$/)
-        ) {
-          $Test->ok(0, $test_txt . " on line $line");
-          return 0;
+        if ( /(\r+)$/ ) {
+          my $match = $1;
+          push @fails, [ _show_whitespace($match) , $line , $_ ]
+              if !$fails{eol}++ or $options->{all_reasons};
+        }
+        if ( $options->{trailing_whitespace} && /([ \t]+)\r*$/ ) {
+          my $match = $1;
+          push @fails, [ _show_whitespace($match), $line , $_ ]
+              if !$fails{tws}++ or $options->{all_reasons};
+        }
+        if ( /\A\s*\z/ ) {
+          $blank_lines++;
         }
+        else {
+          $blank_lines = 0;
+        }
+        if ( $options->{trailing_newline} && eof ) {
+          push @fails, [ sprintf('%d blank line%s at end of file',
+                                 $blank_lines, $blank_lines > 1 ? 's' : ''),
+                         $line, undef ]
+            if $blank_lines;
+          push @fails, [ 'Missing "\n" at end of file', $line, undef ]
+            unless /\n\z/;
+        }
+        # Minor short-circuit for people who don't need the whole file scanned
+        # once there's an err.
+        last if( @fails > 0 && !$options->{all_reasons} );
+    }
+    if( @fails ){
+       $Test->ok( 0, $test_txt . " on "  . _debug_line({ show_lines => 0 } , $fails[0]  )  );
+       if ( $options->{all_reasons} || 1 ){
+          $Test->diag( "  Problem Lines: ");
+          for ( @fails ){
+            $Test->diag(_debug_line({ show_lines => 1 } , $_ ) );
+          }
+       }
+       return 0;
     }
     $Test->ok(1, $test_txt);
     return 1;
@@ -100,11 +169,15 @@ sub _is_perl_module {
     $_[0] =~ /\.pm$/i || $_[0] =~ /::/;
 }
 
+sub _is_pod_file {
+    $_[0] =~ /\.pod$/i;
+}
+
 sub _is_perl_script {
     my $file = shift;
     return 1 if $file =~ /\.pl$/i;
     return 1 if $file =~ /\.t$/;
-    open my $fh, $file or return;
+    open (my $fh, $file) or return;
     my $first = <$fh>;
     return 1 if defined $first && ($first =~ $PERL_PATTERN);
     return;
@@ -124,6 +197,7 @@ sub _module_to_path {
 }
 
 sub _make_plan {
+    return if $no_plan;
     unless ($Test->has_plan) {
         $Test->plan( 'no_plan' );
     }
@@ -136,17 +210,12 @@ sub _untaint {
 }
 
 1;
-__END__
-
-=head1 NAME
-
-Test::EOL - Check the correct line endings in your project
 
 =head1 SYNOPSIS
 
-C<Test::EOL> lets you check the presence of windows line endings in your
-perl code. It
-report its results in standard C<Test::Simple> fashion:
+C<Test::EOL> lets you check for the presence of trailing whitespace and/or
+windows line endings in your perl code. It reports its results in standard
+C<Test::Simple> fashion:
 
   use Test::EOL tests => 1;
   eol_unix_ok( 'lib/Module.pm', 'Module is ^M free');
@@ -177,6 +246,24 @@ or
   use Test::EOL;
   all_perl_files_ok({ trailing_whitespace => 1 }, @mydirs );
 
+or
+
+  use Test::More;
+  use Test::EOL 'no_test';
+  all_perl_files_ok();
+  done_testing;
+
+and if authors would like to check that there's a single newline and no
+blank lines at the end of each file:
+
+  use Test::EOL;
+  all_perl_files_ok({ trailing_newline => 1 });
+
+or
+
+  use Test::EOL;
+  all_perl_files_ok({ trailing_newline => 1 }, @mydirs );
+
 =head1 DESCRIPTION
 
 This module scans your project/distribution for any perl files (scripts,
@@ -187,44 +274,54 @@ modules, etc) for the presence of windows line endings.
 A list of functions that can be exported.  You can delete this section
 if you don't export anything, such as for a purely object-oriented module.
 
-=head1 FUNCTIONS
+=func all_perl_files_ok
 
-=head2 all_perl_files_ok( [ \%options ], [ @directories ] )
+  all_perl_files_ok( [ \%options ], [ @directories ] )
 
 Applies C<eol_unix_ok()> to all perl files found in C<@directories> (and sub
-directories). If no <@directories> is given, the starting point is one level
-above the current running script, that should cover all the files of a typical
-CPAN distribution. A perl file is *.pl or *.pm or *.t or a file starting
+directories). If no <@directories> is given, the starting point is the current
+working directory, as tests are usually run from the top directory in a typical
+CPAN distribution. A perl file is *.pl or *.pm or *.pod or *.t or a file starting
 with C<#!...perl>
 
-If the test plan is defined:
+Valid C<\%options> currently are:
 
-  use Test::EOL tests => 3;
-  all_perl_files_ok();
+=over
 
-the total number of files tested must be specified.
+=item * trailing_whitespace
 
-=head2 eol_unix_ok( $file [, $text] [, \%options ]  )
+By default Test::EOL only looks for Windows (CR/LF) line-endings. Set this
+to true to raise errors if any kind of trailing whitespace is present in
+the file.
 
-Run a unix EOL check on C<$file>. For a module, the path (lib/My/Module.pm) or the
-name (My::Module) can be both used.
+=item * trailing_newline
+
+Set this to true to raise an error if the file doesn't end with exactly
+one newline and no blank lines.
 
-=head1 AUTHOR
+=item * all_reasons
 
-Tomas Doran (t0m) C<< <bobtfish@bobtfish.net> >>
+Normally Test::EOL reports only the first error in every file (given that
+a text file originated on Windows will fail every single line). Set this
+a true value to register a test failure for every line with an error.
 
-=head1 BUGS
+=back
 
-Testing for EOL styles other than unix (\n) currently unsupported.
+If the test plan is defined:
+
+  use Test::EOL tests => 3;
+  all_perl_files_ok();
+
+the total number of files tested must be specified.
 
-The source code can be found on github, as listed in C< META.yml >,
-patches are welcome.
+=func eol_unix_ok
 
-Otherwise please report any bugs or feature requests to
-C<bug-test-eol at rt.cpan.org>, or through the web interface at
-L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-EOL>.
-I will be notified, and then you'll automatically be notified of progress on
-your bug as I make changes.
+  eol_unix_ok ( $file [, $text] [, \%options ] )
+
+Run a unix EOL check on C<$file>. For a module, the path (lib/My/Module.pm) or the
+name (My::Module) can be both used. C<$text> is the diagnostic label emited after
+the C<ok>/C<not ok> TAP output. C<\%options> takes the same values as described in
+L</all_perl_files_ok>.
 
 =head1 ACKNOWLEDGEMENTS
 
@@ -235,12 +332,4 @@ Shamelessly ripped off from L<Test::NoTabs>.
 L<Test::More>, L<Test::Pod>. L<Test::Distribution>, L<Test:NoWarnings>,
 L<Test::NoTabs>, L<Module::Install::AuthorTests>.
 
-=head1 COPYRIGHT & LICENSE
-
-Copyright 2009 Tomas Doran, some rights reserved.
-
-This program is free software; you can redistribute it and/or modify it
-under the same terms as Perl itself.
-
 =cut
-