get_workflow_status.py 2.5 KB
Newer Older
1
# coding: utf-8
2
3
4
5
6
7
8
"""Get the most recent status of workflow for the current PR.

[usage]
    python get_workflow_status.py TRIGGER_PHRASE

TRIGGER_PHRASE: Code phrase that triggers workflow.
"""
9
10
11
12
import json
from os import environ
from sys import argv, exit
from time import sleep
13

14
15
16
17
18
19
try:
    from urllib import request
except ImportError:
    import urllib2 as request


20
def get_runs(trigger_phrase):
21
22
23
24
    """Get all triggering workflow comments in the current PR.

    Parameters
    ----------
25
26
    trigger_phrase : string
        Code phrase that triggers workflow.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

    Returns
    -------
    pr_runs : list
        List of comment objects sorted by the time of creation in decreasing order.
    """
    pr_runs = []
    if environ.get("GITHUB_EVENT_NAME", "") == "pull_request":
        pr_number = int(environ.get("GITHUB_REF").split('/')[-2])
        req = request.Request(url="{}/repos/microsoft/LightGBM/issues/{}/comments".format(environ.get("GITHUB_API_URL"),
                                                                                          pr_number),
                              headers={"Accept": "application/vnd.github.v3+json"})
        url = request.urlopen(req)
        data = json.loads(url.read().decode('utf-8'))
        url.close()
        pr_runs = [i for i in data
                   if i['author_association'].lower() in {'owner', 'member', 'collaborator'}
44
                   and i['body'].startswith('/gha run {}'.format(trigger_phrase))]
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    return pr_runs[::-1]


def get_status(runs):
    """Get the most recent status of workflow for the current PR.

    Parameters
    ----------
    runs : list
        List of comment objects sorted by the time of creation in decreasing order.

    Returns
    -------
    status : string
        The most recent status of workflow.
        Can be 'success', 'failure' or 'in-progress'.
    """
    status = 'success'
    for run in runs:
        body = run['body']
        if "Status: " in body:
            if "Status: skipped" in body:
                continue
            if "Status: failure" in body:
                status = 'failure'
                break
            if "Status: success" in body:
                status = 'success'
                break
        else:
            status = 'in-progress'
            break
    return status


if __name__ == "__main__":
81
    trigger_phrase = argv[1]
82
    while True:
83
        status = get_status(get_runs(trigger_phrase))
84
85
86
87
88
        if status != 'in-progress':
            break
        sleep(60)
    if status == 'failure':
        exit(1)