xref: /aosp_15_r20/external/cronet/android/tools/githooks/post-commit (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1#!/bin/bash
2
3# Copyright 2023 Google Inc. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17set -eu
18
19main() {
20    # Check if the last commit included changes to a .gn or .gni file, which need
21    # to be reflected in a .patch
22    if git diff --name-only HEAD~..HEAD | egrep -q '[.]gni?$'; then
23        echo "INFO: changes to a .gn|.gni file detected."
24    else
25        # no patch needed
26        exit 0
27    fi
28
29    # HACK: checking for the existence of rebase-merge may not always work as
30    # expected.
31    # TODO: find a better solution. One option is to parse `git status` output and
32    # grep for the "rebase in progress" string.
33    if [[ -d "$(git rev-parse --git-dir)/rebase-merge" ]]; then
34        # interactive rebase in progress.
35        echo "WARNING! .patch files are not updated during interactive rebase"
36        exit 0
37    fi
38
39    # There is no flag to skip the post-commit hook (--no-verify only works for
40    # pre-commit and commit-msg hooks). Briefly remove the executable
41    # permission to prevent recursion.
42    chmod -x .git/hooks/post-commit
43    # Ensure chmod +x is always run, even when script exits early
44    trap "chmod +x .git/hooks/post-commit" EXIT
45
46    # Remove any existing .patch files from the commit
47    local -r patches_dir="${ANDROID_BUILD_TOP}/external/cronet/patches"
48    git reset HEAD~ -- "${patches_dir}/*.patch"
49    git -c "advice.ignoredHook=false" commit --amend --no-edit
50
51    # Create patch (which only reflects changes to .gn and .gni files).
52    local -r number_of_patches=$(git ls-tree -r HEAD~ -- "${patches_dir}" | wc -l)
53    local -r patch_name=$(git format-patch -1 -N --start-number "${number_of_patches}" -o "${patches_dir}" HEAD -- "*.gn" "*.gni")
54    git add "${patch_name}"
55    git -c "advice.ignoredHook=false" commit --amend --no-edit
56
57    echo "INFO: a .patch file was added to your CL"
58}
59
60main "$@"; exit
61
62