#!/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.


###########################################################################
# 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.

### options
# Push options are supported, using "git push -o <option>".
# Note that this needs to be run on the server:
#   git config receive.advertisePushOptions true
# while cd'ed into the bare git repo.

# 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.
$skip = 0;

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

# default branch is usually 'master'. It is for SBo, anyway. Still,
# query repo for this instead of hardcoding (see set_default_branch()).
$default_branch = undef;

###

@errs = ();

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

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

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

sub check_message {
	my $full_msg = shift;
	my $hash = shift;
	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
# categories by checking that the directory exists. So we
# have to run 'git ls-tree' to get them, which slows this down
# slightly.
{
	my %cats;

	sub init_cats {
		open my $gitpipe, "git ls-tree -d --name-only $default_branch |" or die $!;
		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}++;
	}

	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";
}

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 {
		die "$SELF: unknown push option '-o $opt', try '-o help'\n";
	}
}

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 set_default_branch {
	chomp ($default_branch = `git config get init.defaultBranch`);
	debug("default branch is '$default_branch'");
}

sub init_colors {
	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();
set_default_branch();

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;
}

while(<STDIN>) {
	chomp;
	debug("STDIN line: $_");
	my($start, $end, $ref, undef) = split / /;

	if($start eq ('0' x 40)) {
		$range = "$default_branch..$end";
	} else {
		$range = "$start..$end";
	}
	debug("range $range");

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

	my $count = 0;
	open my $git, "$cmd |" or die $!;
	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 messages");
}

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;
