#!/usr/bin/perl -w

# .git/hooks/commit-msg for SlackBuilds.Org.
# New Revised Hubris/Laziness/Impatience Edition.
# B. Watson <urchlay@slackware.uk>, WTFPL.

# If this hook ever causes problems, it can be bypassed with:
# export MSGOK=1

# Run "perldoc /path/to/commit-msg" to read the docs in a pager,
# or just keep reading if you don't mind reading POD.

#################################################################

=pod

=head1 NAME

B<hooks/commit-msg> - normalize commit messages to SBo standard.

=head1 SYNOPSIS

  cp commit-msg /path/to/git/worktree/.git/hooks
  chmod +x /path/to/git/worktree/.git/hooks/commit-msg
  git push

=head1 DESCRIPTION

These things happen here:

=over 4

=item 1.

If multiple directories had changes, abort the commit (unless it
uses an admin-only message; see below).

=item 2.

If the commit subject (first line of the message) is "v" or
"v,<something>", we generate an 'Updated for version x.y.z.' or
'Updated for version x.y.z, <something>.' message.

=item 3.

If the subject doesn't have "<category>/<prgnam>: " as a prefix,
the prefix gets prepended.

=item 4.

If the subject doesn't end with a period, and if it's
<= 67 characters[*] long, we add a period.

=item 5.

If the subject has what looks like a bogus prefix (e.g.
misspelled "system" as "sytsem", or "build: " without the
category, or missing a space after the colon), the commit
is aborted.

=item 6.

If the subject is longer than 68 characters (after possibly being
modified by (2) through (4)), the commit is aborted.

=back

[*] "Characters" really means bytes. If anyone uses non-ASCII
Unicode in a commit, codepoints above U+00ff are counted as two
or more bytes. If anyone uses a legacy encoding like ISO-8859-*,
git will complain about it already. It really doesn't matter:
there hasn't been a non-ASCII commit message in 12+ years.

=head1 NOTES

=head2 Multi-line Messages

In case of a multi-line commit message, only the first
line is checked. The rest of the lines don't show up in weekly update
emails or ready/ on the website, so they stay as-is.

=head2 Signed-off-by

If your previous commit-msg hook adds a Signed-off-by line, don't
modify this hook to do the same. Instead, use a prepare-commit-msg
hook, that looks like this:

  #!/bin/bash
  SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
  grep -qs "^$SOB" "$1" || echo -e "\n$SOB" >> "$1"

=head2 Admin-only Messages

Note for SBo admins: Commit messages beginning with these prefixes:

  "all: "
  "various: "
  "git: "
  "ChangeLog.txt: "
  "README: "
  "Public www update: "
  "(tag: "

...are accepted as-is, and the "only one directory per commit" rule
doesn't apply. If you're not an admin, you shouldn't be using these.

=head1 ENVIRONMENT

=over 4

=item MSGOK

Set this (to any value) to bypass this hook. Commit messages will not
be checked nor altered.

=item DRYRUN

Set this (to any value) to have the hook abort the commit after it's
completely processed.

=back

=head1 LICENSE

WTFPL; Do WTF you want with this.

=head1 AUTHOR

B. Watson <urchlay@slackware.uk>. Please send any bug reports or
feature requests via email.

=cut

#################################################################
BEGIN { exit 0 if $ENV{MSGOK}; };

$SELF = $0 =~ s,.*/,,r;

# I doubt this will ever change:
$MAXLEN = 68;

@admin_msgs = (
   "all: ",
   "various: ",
   "git: ",
   "ChangeLog.txt: ",
   "README: ",
   "Public www update: ",
	"(tag: ", # I'm not sure this actually does anything
);

abort("Hook called with no argument.") unless $ARGV[0];
abort("$ARGV[0] doesn't exist, huh?") unless -f $ARGV[0];
$msgfile = $ARGV[0];

# get list of directories with changes.
for(split /\0/, `git -P diff -z --cached --name-only`) {
	my ($cat, $prog, undef) = split /\//, $_, 3;
	next unless (defined $cat && defined $prog);
	$dirs{"$cat/$prog"}++;
}
@dirs = keys %dirs;

# no changes in any category/prgnam dir, assume the user knows
# what he's doing.
exit 0 unless @dirs;

@lines = <ARGV>;
chomp for @lines;

$msgline = $lines[0];

if(grep { index($msgline, $_) == 0 } @admin_msgs) {
	warn "$SELF: Skipping checks due to admin-only commit message.\n";
	exit 0;
}

if(@dirs > 1) {
	abort("Aborting due to changes in multiple directories:" .
			join("\n  ", "", @dirs));
}

$lines[0] = fix_message($msgline, $dirs[0]);
save_file($msgfile, @lines) if $msgline ne $lines[0];

if(exists($ENV{DRYRUN})) {
	warn "$SELF: commit message OK, not committing due to DRYRUN in env.\n";
	exit 1;
}

exit 0;

#################################################################
sub fix_message {
	my $msg = shift;
	my $catprg = shift;

	my $prefix = "$catprg: ";
	my $orig = $msg;

	# v => Updated for version <ver>
	# v,stuff => Updated for version <ver>, stuff
	if($msg =~ /^v(?:\s*,\s*(\S.*$))?/) {
		my $rest = defined $1 ? ", $1" : "";
		$msg = "Updated for version " . get_ver($catprg) . $rest;
	}

	# add prefix only if missing.
	if(index($msg, $prefix) != 0) {
		if($msg =~ /^(\S+:)(\s)?/) {
			my $err = "Commit message has bad prefix:\n" .
				"  '$1'\n    should be:\n  '$prefix'";
			if(!defined($2)) {
				$err .= "\n    Missing space after '$1'";
			}
			abort($err);
		}
		$msg = "$prefix$msg";
	}

	# add a period if there isn't one, and if there's room for one.
	if(length($msg) < $MAXLEN && ($msg !~ /.*\.$/)) {
		$msg .= ".";
	}

	if($msg ne $orig) {
		warn <<EOF;
=== Modified commit message
    was: '$orig'
    now: '$msg'
If this doesn't look correct, use 'git commit --amend' to fix it.
EOF
	}

	my $l = length $msg;
	if($l > $MAXLEN) {
		abort("Commit message too long ($l chars, max is $MAXLEN).");
	}

	return $msg;
}

#################################################################
# Saves the commit message file (overwrites the original).
sub save_file {
	my $file = shift;
	open my $f, ">", $file or abort("$file: $!");
	print $f "$_\n" for @_;
	close $f;
}

#################################################################
# Read VERSION from the .info file, return it.
sub get_ver {
	my $catprg = shift;
	my $prg = $catprg =~ s,.*/,,r;
	my $info = "$catprg/$prg.info";
	my $ver;

	open my $f, "<", $info or abort("Missing $info file");
	while(<$f>) {
		next unless /^VERSION="([^"]+)"/;
		$ver = $1;
		last;
	}
	close $f;

	abort("Can't read VERSION from $info") unless defined $ver;
	return $ver;
}

#################################################################
sub abort {
	warn "*** $_[0]\n" if $_[0];
	die "$SELF hook: Commit aborted due to bad commit message.\n";
}
