1#!/bin/sh
2
3# Copyright (C) 2020 Free Software Foundation, Inc.
4#
5# This file is part of GCC.
6#
7# GCC is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 3, or (at your option)
10# any later version.
11#
12# GCC is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with GCC; see the file COPYING.  If not, write to
19# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20# Boston, MA 02110-1301, USA.
21
22COMMIT_MSG_FILE=$1
23COMMIT_SOURCE=$2
24SHA1=$3
25
26# We might be on a branch before the file was added.
27if ! [ -x contrib/mklog.py ]; then exit 0; fi
28
29# Can't do anything if $COMMIT_MSG_FILE isn't a file.
30if ! [ -f "$COMMIT_MSG_FILE" ]; then exit 0; fi
31
32# Don't do anything unless requested to.
33if [ -z "$GCC_FORCE_MKLOG" ]; then exit 0; fi
34
35if [ -z "$COMMIT_SOURCE" ] || [ $COMMIT_SOURCE = template ]; then
36    # No source or "template" means new commit.
37    cmd="diff --cached"
38
39elif [ $COMMIT_SOURCE = message ]; then
40    # "message" means -m; assume a new commit if there are any changes staged.
41    if ! git diff --cached --quiet; then
42	cmd="diff --cached"
43    else
44	cmd="diff --cached HEAD^"
45    fi
46
47elif [ $COMMIT_SOURCE = commit ]; then
48    # The message of an existing commit.  If it's HEAD, assume --amend;
49    # otherwise, assume a new commit with -C.
50    if [ $SHA1 = HEAD ]; then
51	cmd="diff --cached HEAD^"
52	if [ "$(git config gcc-config.mklog-hook-type)" = "smart-amend" ]; then
53	    # Check if the existing message still describes the staged changes.
54	    f=$(mktemp /tmp/git-commit.XXXXXX) || exit 1
55	    git log -1 --pretty=email HEAD > $f
56	    printf '\n---\n\n' >> $f
57	    git $cmd >> $f
58	    if contrib/gcc-changelog/git_email.py "$f" >/dev/null 2>&1; then
59		# Existing commit message is still OK for amended commit.
60		rm $f
61		exit 0
62	    fi
63	    rm $f
64	fi
65    else
66	cmd="diff --cached"
67    fi
68else
69    # Do nothing for merge or squash.
70    exit 0
71fi
72
73# Save diff to a file if requested.
74DIFF_FILE=$(git config gcc-config.diff-file)
75if ! [ -z "$DIFF_FILE" ]; then
76    tee="tee $DIFF_FILE"
77else
78    tee="cat"
79fi
80
81git $cmd | $tee | git gcc-mklog $GCC_MKLOG_ARGS -c "$COMMIT_MSG_FILE"
82