#!/usr/bin/perl -w
#
# cvsann: Annotate a file according to the checked-out version.
#
# $dotat: scripts/cvsann,v 1.3 2002/08/12 10:26:49 fanf2 Exp $

use strict;

use Getopt::Long;
use IO::Pipe;

sub dopipe (@);

#### parse options

sub usage () {
	die "usage: cvsann [-L] <file> [rev]\n",
	    "\t-L\tdon't run pager\n";
}

my %option;
Getopt::Long::Configure 'bundling';
GetOptions (\%option, "noless|L!")
    or usage;

usage if @ARGV < 1 or @ARGV > 2;

#### work out where to send output to

my $outpipe;
if ($option{noless} or not -t STDOUT) {
	$outpipe = new_from_fd IO::Handle fileno(STDOUT), "w";
	die "$0: fdopen: $!\n" unless defined $outpipe;
} else {
	$outpipe = new IO::Pipe;
	die "$0: pipe: $!\n" unless defined $outpipe;
	$outpipe->writer($ENV{PAGER});
}

#### main program

my $file = $ARGV[0];

# work out revision number
#
my $rev;
if(@ARGV > 1) {
	$rev = $ARGV[1];
} else {
	my $status = dopipe "cvs", "status", $file;
	$status =~ /Working revision:\s+([0-9.]+)/;
	$rev = $1;
}

# print annotation
#
$outpipe->print(dopipe "cvs", "annotate", "-r", $rev, $file);
$outpipe->close;

exit 0;

#### invoke cvs

sub dopipe (@) {
	# ensure that we don't have anything in our buffers when we fork
	flush STDOUT;
	my $pipe = new IO::Pipe;
	die "$0: pipe: $!\n" unless defined $pipe;
	$pipe->reader(@_);
	$pipe->input_record_separator(undef);
	my $text = $pipe->getline;
	$pipe->close or die "$0: close @_: $!\n";
	return $text;
}
