#!/usr/bin/perl -w

# git pre-receive hook for SBo.
# checks commit message formats, aborts push if any are bad.

# 20261123 bkw: initial version. may still need work.
# 20261123 bkw: added colors and -o mono, add test env instructions.
# 20261124 bkw: this is in git now, see sbo-maintainer-tools log for changes.


###########################################################################
# How to set up a testing environment for this
#
# 1. Create a bare git repo:
#    git clone --bare git://git.slackbuilds.org/slackbuilds.git ~/sbo.bare
#
# 2. Copy this file to the bare repo and make it executable:
#    cp /path/to/pre-receive ~/sbo.bare/hooks
#    chmod +x ~/sbo.bare/hooks/pre-receive
#
# 3. Enable this config option in the bare repo:
#    cd ~/sbo.bare
#    git config receive.advertisePushOptions true
#
# 4. Go to your regular git work dir, and create some commits with
#    deliberately bad messages. Leave off the category, make them
#    longer than the 68-character limit, etc.
#
# 5. Try to push these commits to your bare repo:
#    git push ~/sbo.bare
#
# 6. You should see error messages complaining about the bad commits,
#    and the push should be rejected.
#
# 7. You can see verbose debug info from this hook by doing this:
#    git push -o debug ~/sbo.bare
#
###########################################################################


# This is a "server side" hook. Installing it your regular worktree's
# .git/hooks/ won't do anything.

# This hook looks for "invalid" commit messages.
# A valid message looks like [1]:

# category/build: Message.

# Where:

# - The overall length must be <= 68 characters.
# - Category is one of the top-level dirs in the git repo [2].
# - Build consists only of upper/lowercase letters, numbers,
#   underscore, dash, period, or plus characters.
# - A single colon and space are required after the build.
# - The message can be anything.
# - Ideally, there should be a period (dot, full stop, ".") at
#   the end of the message, but this script doesn't enforce that,
#   since sometimes it has to be left out to squeeze the message in to
#   68 chars.

# [1] A message beginning with "Public www update" is considered valid,
#     since this is standard for weekly updates.

# [2] "git" is accepted as a category as well, since it's used for
#     changes to the CI system.

### End of user documentation, the rest is code.

### Options:

# Enable this with: git push -o debug
$debugging = 0;

# Enable this with: git push -o skip
# Gives the operator a way to work around this script, in case there's
# a bug in it. Also useful during 'crunch time', aka 'dev cycle', when
# we allow commits to break the "one commit per directory" rule, and
# use "all: <message>" or "python/*: <message>", etc.
$skip = 0;

# Disable colors with -o mono
$color_output = 1;

# Default branch is 'master' for SBo, despite newer releases of git
# chaning the dedault to 'main' for newly-created repos. We aren't
# going to change our existing (for 15+ years) repo.
$default_branch = 'master';

###

@errs = ();

($SELF = $0) =~ s,.*/,,;

sub debug {
	return unless $debugging;
	warn "$SELF: $_\n" for @_;
}

sub fatal {
	die "$SELF: $_[0]\n";
}

sub errmsg {
	return "  " . yellow($_[0]) . "\n";
}

# Meat and potatoes here. Eat hearty!
sub check_message {
	my $full_msg = shift;
	my $hash = shift; # not used except to print it

	my $result;

	debug("check_message(\"$full_msg\", \"$hash\")");

	# length check can be combined with the 'serious' errors.
	if(length($full_msg) > 68) {
		$result = errmsg("Length exceeds 68 characters");
	}

	for($full_msg) {
		# don't check these!
		return if /^Public www update:/;

		# first 3 errors are serious enough that we don't check
		# for the rest (hence the 'last').
		if(! /:/) {
			$result .= errmsg("No category/build (no colon)");
			last;
		}

		my ($catprg, $msg) = split /:/, $_, 2;
		if($catprg !~ m{/}) {
			$result .= errmsg("No category");
			last;
		}

		my ($cat, $prg, $junk) = split /\//, $catprg;
		if(defined($junk)) {
			$result .= errmsg("Invalid category/build (2 or more slashes)");
			last;
		}

		# the rest of these, we can have more than one of.
		if($prg =~ /[^-A-Za-z0-9_+.]/) {
			$result .= errmsg("Invalid character in build name '$prg'");
		}

		if(!category_ok($cat)) {
			$result .= errmsg("Invalid category '$cat'");
		}

		if($msg !~ /^ /) {
			$result .= errmsg("Missing space after colon");
		}

		if($msg =~ /^  /) {
			$result .= errmsg("Extra space after colon");
		}
	}

	if(defined $result) {
		push @errs, (
				red("* Malformed commit message for ") . yellow($hash). "\n",
				green($full_msg) . "\n",
				$result,
				"\n" );
	}
}

# Note that this runs *in a bare git repo*, so we can't check
# a category by checking that its directory exists. So we
# have to run 'git ls-tree' to get them, which slows this down
# slightly.
{
	my %cats;

	sub init_cats {
		my @cmd = ("git", "ls-tree", "-d", "--name-only", $default_branch);
		debug("executing " . join(" ", @cmd));
		open(my $gitpipe, "-|", @cmd) or fatal($!);

		while(my $l=<$gitpipe>) {
			next if $l =~ /^\./; # skip .forgejo and .github dirs
			chomp $l;
			$cats{$l}++;
		}
		close $gitpipe;

		# Allow "git" as a 'category', aclemons uses it in CI.
		$cats{git}++;

		debug("categories: " . join " ", sort { $a cmp $b } keys %cats);
	}

	sub category_ok {
		init_cats() unless %cats;
		return $cats{$_[0]};
	}
}

sub print_opt_help {
	print yellow("Options:") . "\n";
	print "  " . green("-o skip") .
		"   Accept all commit message as-is; skip error checking.\n";
	print "  " . green("-o debug") .
		"  Print debug messages about commit message checking.\n";
	print "  " . green("-o mono") .
		"   Don't colorize output.\n";
	print "  " . green("-o help") .
		"   Display this help and abort the commit.\n";
}

# Don't be picky about case or whether someone types "debugging"
# when they meant "debug".
sub process_push_opt {
	my $opt = lc shift;
	if($opt =~ /debug/) {
		$debugging++;
	} elsif($opt =~ /skip/) {
		$skip++;
	} elsif($opt =~ /mono/) {
		$color_output = 0;
		init_colors();
	} elsif($opt =~ /help/) {
		$help++;
	} else {
		fatal("$SELF: unknown push option '-o $opt', try '-o help'");
	}
}

# man page githooks(5) and git's pre-receive.sample explain
# how this works.
sub read_push_options {
	return unless my $count = $ENV{GIT_PUSH_OPTION_COUNT};
	for(my $i = 0; $i < $count; $i++) {
		process_push_opt($ENV{"GIT_PUSH_OPTION_" . $i});
	}
}

sub init_colors {
	# Good old ANSI colors. Really should be using 'tput' or something
	# to get these, but I don't think anyone's still using anything
	# that doesn't either support or at least know how to ignore these
	# escape codes.
	# Note that the "1;" means we're using bold. It looks nicer to
	# me, on my black-background urxvt, but YMMV.
	if($color_output) {
		$red =       "\x1b[1;31m";
		$yellow =    "\x1b[1;33m";
		$green =     "\x1b[1;32m";
		$color_off = "\x1b[0m";
	} else {
		$red = $yellow = $green = $color_off = "";
	}
}

sub red {
	return "$red$_[0]$color_off";
}

sub yellow {
	return "$yellow$_[0]$color_off";
}

sub green {
	return "$green$_[0]$color_off";
}

### main()

init_colors();
read_push_options();

if($help) {
	print_opt_help();
	exit 1;
}

if($debugging) {
	chomp(my $pwd = `pwd`);
	debug("$0 starting up in dir $pwd with -o debug");
}

if($skip) {
	debug("skipping commit message checks due to -o skip");
	exit 0;
}

# Lines of input look like:
# <start-hash> <end-hash> <ref>
# See git's pre-receive.sample.
# Normally we only get one line of input, but it's unclear to me
# whether this is *always* the case, hence the while loop.
while(<STDIN>) {
	chomp;
	debug("STDIN line: $_");
	my($start, $end, $ref, undef) = split / /;
	# $ref currently unused, but maybe it shouldn't be?

	if($start eq ('0' x 40)) {
		# all-zeroes start hash means, new branch being pushed
		$range = "$default_branch..$end";
	} else {
		$range = "$start..$end";
	}
	debug("range $range");

	my $cmd = "git log --pretty=format:%h%x09%s $range";
	my @cmd = ("git", "log", "--pretty=format:%h%x09%s", $range);
	debug("executing: " . join " ", @cmd);

	my $count = 0;
	open(my $git, "-|", @cmd) or fatal($!);
	while(<$git>) {
		chomp;
		debug("read line from git: $_\n");
		$count++;
		my($hash, $msg) = split /\t/, $_, 2;
		check_message($msg, $hash);
	}
	close $git;

	debug("checked $count commit message" . ($count == 1 ? "" : "s"));
}

if(@errs) {
	print red("!!! git push aborted; fix the errors below and try again.") .
		"\n  ...or, if you're " . red("100% certain") .
		" everything is correct, re-run the\n" .
		"  command as: " . yellow("git push -o skip") . "\n" .
		"  ...and let Urchlay know you found a bug in the pre-receive hook.\n\n";
	print for @errs;
}

exit @errs;
