|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +from collections.abc import Sequence |
| 6 | +from collections.abc import Set |
| 7 | +from os import environ |
| 8 | +from re import search |
| 9 | +from typing import SupportsIndex |
| 10 | +from urllib import request |
| 11 | + |
| 12 | + |
| 13 | +def get_ticket(commit_msg_filename: str) -> str | None: |
| 14 | + with open(commit_msg_filename, encoding='utf-8') as msg: |
| 15 | + lines = msg.readlines() |
| 16 | + ticketing = search(r'^([A-Z]{2,}-[1-9][0-9]*): .*', lines[0]) |
| 17 | + return None if not ticketing else ticketing.group(1) |
| 18 | + |
| 19 | + |
| 20 | +def fetch_jira( |
| 21 | + ticket: str, |
| 22 | + jira_uri: str, |
| 23 | + jira_pat: str, |
| 24 | +) -> SupportsIndex | slice | None: |
| 25 | + try: |
| 26 | + req = request.Request(f'{jira_uri}/rest/api/latest/issue/{ticket}') |
| 27 | + req.add_header('Authorization', f'Bearer {jira_pat}') |
| 28 | + resp = request.urlopen(req) |
| 29 | + return json.loads( |
| 30 | + resp.read().decode(resp.info().get_param('charset') or 'utf-8'), |
| 31 | + ) |
| 32 | + except json.decoder.JSONDecodeError: # unexpected response |
| 33 | + return None |
| 34 | + |
| 35 | + |
| 36 | +def get_ticket_version( |
| 37 | + ticket: str, |
| 38 | + jira_uri: str, |
| 39 | + jira_pat: str, |
| 40 | +) -> str | None: |
| 41 | + body = fetch_jira(ticket, jira_uri, jira_pat) |
| 42 | + if not body: |
| 43 | + return None |
| 44 | + try: |
| 45 | + fixVersions = body['fields']['fixVersions'] # type: ignore[index] |
| 46 | + return fixVersions[0]['name'] if len(fixVersions) == 1 else None |
| 47 | + except (KeyError, TypeError): # no .fields.fixVersions[0].name |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +def get_ticket_status_category( |
| 52 | + ticket: str, |
| 53 | + jira_uri: str, |
| 54 | + jira_pat: str, |
| 55 | +) -> str | None: |
| 56 | + body = fetch_jira(ticket, jira_uri, jira_pat) |
| 57 | + try: |
| 58 | + if body: |
| 59 | + return body['fields']['status']['statusCategory']['key'] # type: ignore[index] # noqa: E501 |
| 60 | + else: |
| 61 | + return None |
| 62 | + except (KeyError, TypeError): # no .fields.status.statusCategory.key |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +def check_ticket_status_category( |
| 67 | + ticket_status_category: str | None, |
| 68 | + allowed: Set[str], |
| 69 | + disallowed: Set[str], |
| 70 | +) -> bool: |
| 71 | + if not ticket_status_category: |
| 72 | + return False |
| 73 | + if ticket_status_category in allowed \ |
| 74 | + or ticket_status_category not in disallowed: |
| 75 | + return True |
| 76 | + return False |
| 77 | + |
| 78 | + |
| 79 | +def main(argv: Sequence[str] | None = None) -> int: |
| 80 | + parser = argparse.ArgumentParser() |
| 81 | + parser.add_argument('commit_msg', help='Filename of commit message') |
| 82 | + parser.add_argument( |
| 83 | + '-l', '--lenient', action='store_true', |
| 84 | + help='If set, and no JIRA URI is present,' |
| 85 | + ' this hook defaults to a NOOP', |
| 86 | + ) |
| 87 | + parser.add_argument( |
| 88 | + '-u', '--jira-uri', |
| 89 | + help='URI of JIRA instance, may be an environment variable' |
| 90 | + ' (starting with "$")', |
| 91 | + ) |
| 92 | + parser.add_argument( |
| 93 | + '-p', '--jira-pat', |
| 94 | + help='Personal access token (PAT) to use for JIRA authentication,' |
| 95 | + ' may be an environment variable (starting with "$")', |
| 96 | + ) |
| 97 | + parser.add_argument( |
| 98 | + '-i', '--allow-status-category', action='append', |
| 99 | + help='Ticket status category to be allowed,' |
| 100 | + ' may be specified multiple times;' |
| 101 | + ' has priority over disallowed status categories' |
| 102 | + ' (default: none)', |
| 103 | + ) |
| 104 | + parser.add_argument( |
| 105 | + '-e', '--disallow-status-category', action='append', |
| 106 | + help='Ticket status category to be disallowed,' |
| 107 | + ' may be specified multiple times' |
| 108 | + ' (default: "done")', |
| 109 | + ) |
| 110 | + parser.add_argument( |
| 111 | + '-v', '--allowed-fix-version', action='append', |
| 112 | + help='Fix version to be allowed;' |
| 113 | + ' not checked if none specified;' |
| 114 | + ' may be specified multiple times,' |
| 115 | + ' may any of them be an environment variable (starting with "$")' |
| 116 | + ' (default: none)', |
| 117 | + ) |
| 118 | + args = parser.parse_args(argv) |
| 119 | + default_value = '' # pragma: no mutate |
| 120 | + if args.jira_uri and args.jira_uri.startswith('$'): # pragma: no mutate |
| 121 | + args.jira_uri = environ.get(args.jira_uri[1:], default_value) |
| 122 | + if args.lenient and not (args.jira_uri and args.jira_uri.strip()): |
| 123 | + print('Lenient early exit, because no JIRA URI given') |
| 124 | + return 0 |
| 125 | + |
| 126 | + if args.jira_pat and args.jira_pat.startswith('$'): # pragma: no mutate |
| 127 | + args.jira_pat = environ.get(args.jira_pat[1:], default_value) |
| 128 | + if args.allowed_fix_version: |
| 129 | + resolved = [] |
| 130 | + for e in args.allowed_fix_version: |
| 131 | + if e.startswith('$'): # pragma: no mutate |
| 132 | + resolved.extend(environ.get(e[1:], default_value).split(',')) |
| 133 | + else: |
| 134 | + resolved.extend(e.split(',')) |
| 135 | + args.allowed_fix_version = filter(None, resolved) |
| 136 | + |
| 137 | + allowed = frozenset(args.allow_status_category or ()) |
| 138 | + disallowed = frozenset(args.disallow_status_category or ('done',)) |
| 139 | + version = frozenset(args.allowed_fix_version or ()) |
| 140 | + |
| 141 | + ticket = get_ticket(args.commit_msg) |
| 142 | + if not ticket: |
| 143 | + print('Could not reify ticket from commit message') |
| 144 | + return 4 |
| 145 | + print(f'Checking ticket "{ticket}"') |
| 146 | + |
| 147 | + if len(version) > 0: |
| 148 | + ticket_version = \ |
| 149 | + get_ticket_version(ticket, args.jira_uri, args.jira_pat) |
| 150 | + if not ticket_version: |
| 151 | + print('Ticket has no fix version, but it is expected') |
| 152 | + print( |
| 153 | + '\t(allowed versions are:' |
| 154 | + f' {str(version).replace("frozenset","")})', |
| 155 | + ) |
| 156 | + return 3 |
| 157 | + if ticket_version not in version: |
| 158 | + print(f'Fix version of ticket ("{ticket_version}") is not allowed') |
| 159 | + print( |
| 160 | + '\t(allowed versions are:' |
| 161 | + f' {str(version).replace("frozenset","")})', |
| 162 | + ) |
| 163 | + return 2 |
| 164 | + print(f'Ticket fix version ("{ticket_version}") is allowed') |
| 165 | + print( |
| 166 | + '\t(allowed versions are:' |
| 167 | + f' {str(version).replace("frozenset","")})', |
| 168 | + ) |
| 169 | + else: |
| 170 | + print('Ticket fix version not checked') |
| 171 | + |
| 172 | + category = get_ticket_status_category( |
| 173 | + ticket, args.jira_uri, args.jira_pat, |
| 174 | + ) |
| 175 | + if check_ticket_status_category(category, allowed, disallowed): |
| 176 | + print('Ticket is OK according to COJIRA rules') |
| 177 | + return 0 |
| 178 | + print(f'Ticket status category ("{category}") is not allowed') |
| 179 | + print( |
| 180 | + f'\t(allowed categories are: {str(allowed).replace("frozenset","")},', |
| 181 | + ) |
| 182 | + print( |
| 183 | + '\t disallowed categories are:' |
| 184 | + f' {str(disallowed).replace("frozenset","")})', |
| 185 | + ) |
| 186 | + return 1 |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == '__main__': |
| 190 | + raise SystemExit(main()) |
0 commit comments