#!/usr/bin/env perl

# Simple wrapper to the editor for svn: remove trailing whitespace and
# trailing newlines from log messages.  It can be run in various ways,
# e.g. by setting $SVN_EDITOR to the path to this wrapper.

# Copyright (c) 2008 Vincent Lefevre <vincent@vinc17.org>.

# This program is free software; you may redistribute it
# and/or modify it under the same terms as Perl itself.

use strict;
use warnings;
use POSIX qw(WIFSIGNALED WTERMSIG WIFEXITED WEXITSTATUS);

my ($proc) = '$Id: svneditor 23247 2008-06-17 23:13:27Z lefevre $'
  =~ /^.Id: (\S+) / or die;

# svn currently calls the editor with one argument: the file name.
@ARGV == 1 or $! = 1, die "Usage: $proc <file>\n";

sub getmtime ($)
  {
    my $mtime = (stat $_[0])[9];
    # If mtime isn't available, something wrong could have occurred.
    defined $mtime or die "$proc: can't stat file $_[0]: $!\n";
    return $mtime;
  }

my $file = $ARGV[0];
my $mtime1 = getmtime $file;

# If $EDITOR isn't set, run emacs because this is what I like.
# Feel free to change it to something else. :)
system $ENV{EDITOR} || 'emacs', @ARGV;
$? == -1 and die "$proc: cannot execute editor: $!\n";
$? and die "$proc: editor died (".
  (WIFSIGNALED($?) ? 'signal: '.WTERMSIG($?) :
   WIFEXITED($?) ? 'exit value: '.WEXITSTATUS($?) : '').")\n";

# Exit without touching anything if file hasn't been modified.
my $mtime2 = getmtime $file;
exit if $mtime2 == $mtime1;

my $changed = 0;
my $s = '';
open FILE, '<', $file or die "$proc: can't open file $file (R): $!\n";
while (<FILE>)
  {
    last if $_ eq "--This line, and those below, will be ignored--\n";
    s/[\t ]+$// and $changed = 1;
    $s .= $_;
  }
close FILE or die "$proc: can't close file $file (R): $!\n";
$s =~ s/\n+\z// || $changed or exit;

print "Log message has been cleaned up\n";
open FILE, '>', $file or die "$proc: can't open file $file (W): $!\n";
print FILE $s or die "$proc: can't write to file $file: $!\n";
close FILE or die "$proc: can't close file $file (W): $!\n";


