|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright (c) 2020-2022 The Bitcoin Core developers |
| 4 | +# Distributed under the MIT software license, see the accompanying |
| 5 | +# file COPYING or http://www.opensource.org/licenses/mit-license.php. |
| 6 | +# |
| 7 | +# Linter to check that commit messages have a new line before the body |
| 8 | +# or no body at all |
| 9 | + |
| 10 | +import argparse |
| 11 | +import os |
| 12 | +import sys |
| 13 | + |
| 14 | +from subprocess import check_output |
| 15 | + |
| 16 | + |
| 17 | +def parse_args(): |
| 18 | + """Parse command line arguments.""" |
| 19 | + parser = argparse.ArgumentParser( |
| 20 | + description=""" |
| 21 | + Linter to check that commit messages have a new line before |
| 22 | + the body or no body at all. |
| 23 | + """, |
| 24 | + epilog=f""" |
| 25 | + You can manually set the commit-range with the COMMIT_RANGE |
| 26 | + environment variable (e.g. "COMMIT_RANGE='47ba2c3...ee50c9e' |
| 27 | + {sys.argv[0]}"). Defaults to current merge base when neither |
| 28 | + prev-commits nor the environment variable is set. |
| 29 | + """) |
| 30 | + |
| 31 | + parser.add_argument("--prev-commits", "-p", required=False, help="The previous n commits to check") |
| 32 | + |
| 33 | + return parser.parse_args() |
| 34 | + |
| 35 | + |
| 36 | +def main(): |
| 37 | + args = parse_args() |
| 38 | + exit_code = 0 |
| 39 | + |
| 40 | + if not os.getenv("COMMIT_RANGE"): |
| 41 | + if args.prev_commits: |
| 42 | + commit_range = "HEAD~" + args.prev_commits + "...HEAD" |
| 43 | + else: |
| 44 | + # This assumes that the target branch of the pull request will be master. |
| 45 | + merge_base = check_output(["git", "merge-base", "HEAD", "master"], universal_newlines=True, encoding="utf8").rstrip("\n") |
| 46 | + commit_range = merge_base + "..HEAD" |
| 47 | + else: |
| 48 | + commit_range = os.getenv("COMMIT_RANGE") |
| 49 | + |
| 50 | + commit_hashes = check_output(["git", "log", commit_range, "--format=%H"], universal_newlines=True, encoding="utf8").splitlines() |
| 51 | + |
| 52 | + for hash in commit_hashes: |
| 53 | + commit_info = check_output(["git", "log", "--format=%B", "-n", "1", hash], universal_newlines=True, encoding="utf8").splitlines() |
| 54 | + if len(commit_info) >= 2: |
| 55 | + if commit_info[1]: |
| 56 | + print(f"The subject line of commit hash {hash} is followed by a non-empty line. Subject lines should always be followed by a blank line.") |
| 57 | + exit_code = 1 |
| 58 | + |
| 59 | + sys.exit(exit_code) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + main() |
0 commit comments