check-changelog.py

 1#!/usr/bin/env python3
 2# -*- encoding: utf-8 -*-
 3# vim: set et ts=4 sts=4 sw=4
 4
 5import os
 6import re
 7import subprocess
 8import sys
 9
10
11if __name__ == '__main__':
12    # Skip this check if instructed
13    if re.search(r'skip.?changelog', os.environ['CI_COMMIT_MESSAGE'], flags=re.I) is not None:
14        print('Changelog skipped.')
15        sys.exit(0)
16
17    treeish = 'main..'
18    if os.environ['CI_PIPELINE_SOURCE'] == 'push' and os.environ['CI_COMMIT_REF_NAME'] == 'main':
19        treeish = '{}..'.format(os.environ['CI_COMMIT_BEFORE_SHA'])
20    if os.environ['CI_PIPELINE_SOURCE'] == 'merge_request_event':
21        treeish = '{}..'.format(os.environ['CI_MERGE_REQUEST_DIFF_BASE_SHA'])
22
23    diff=subprocess.run(
24        ['git', 'diff-tree', '--no-commit-id', '-r', treeish, '--'],
25        capture_output=True,
26    )
27
28    if diff.stderr:
29        print(f'An error occured: {diff.stderr}')
30        sys.exit(1)
31
32    print(f'Files in {treeish}:\n{diff.stdout}')
33
34    # Verify if at least a single changelog file has been added or edited
35    if re.search(rb'[AM]\s+\S*changelog', diff.stdout, flags=re.I) is None:
36        print(
37            'Please update the Changelog. Use "skip-changelog" '
38            'in the commit message to skip this check.',
39        )
40        sys.exit(1)
41
42    print('Changelog has been updated as expected.')