#!/usr/bin/perl -wT
# $Id: weblint,v 1.11 2002/06/05 16:06:05 petdance Exp $

use strict;

use Getopt::Long;
use HTML::Lint;
use HTML::Lint::HTML4;

my $help;
my $context;

GetOptions(
    "help"    => \$help,
    "context:i" => \$context,
) or $help = 1;

if ( !@ARGV || $help ) {
    print "weblint v$HTML::Lint::VERSION\n";
    print <DATA>;
    exit 1;
}

my $lint = new HTML::Lint;
for my $url ( @ARGV ) {
    my @lines;
    $lint->newfile( $url );
    if ( $url =~ /^https?:/ ) {
	eval { require LWP::Simple };
	if ( $@ ) {
	    warn "Can't retrieve URLs without LWP::Simple installed";
	    next;
	}

	my $content = LWP::Simple::get( $url );
	if ( $content ) {
	    @lines = split( "\n", $content );
	} else {
	    warn "Unable to fetch $url\n";
	    next;
	}
    } else {
	open( my $fh, $url ) or die "Can't open $url: $!";
	@lines = <$fh>;
	close $fh;
    }
    $lint->parse( "$_\n" ) for @lines;
    $lint->eof();
    for my $error ( $lint->errors() ) {
	print $error->as_string(), "\n";
	if ( defined $context ) {
	    $context += 0;
	    my $lineno = $error->line - 1;

	    my $start = $lineno-$context;
	    $start = 0 if $start < 0;

	    my $end = $lineno+$context;
	    $end = $#lines if $end > $#lines;

	    print "    $_\n" for @lines[$start..$end];
	    print "\n";
	}
    }
    $lint->clear_errors();
} # for files

__END__
Usage: weblint [filename or url]... (filename - reads STDIN)
    --help	    This message
    --context[=n]   Show the offending line (and n surrounding lines)

