summaryrefslogtreecommitdiff
path: root/source/github-helpers/pr-ci-status.ts
blob: 31e074fcd9486b3ab5e6ebbc08b4258205c1dacf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
import {$, lastElement} from 'select-dom';

import api from './api.js';
import {prCommit, prCommitStatusIcon} from './selectors.js';

export const SUCCESS = Symbol('Success');
export const FAILURE = Symbol('Failure');
export const PENDING = Symbol('Pending');
export type CommitStatus = false | typeof SUCCESS | typeof FAILURE | typeof PENDING;

export function getLastCommitReference(): string {
	return lastElement(`${prCommit} code`)!.textContent;
}

export function getLastCommitStatus(): CommitStatus {
	// Select the last commit first, THEN pick the icon, otherwise it might pick non-last commit while the CI is starting up
	const lastCommit = lastElement(prCommit)!;
	const lastCommitStatusIcon = $(prCommitStatusIcon, lastCommit);

	// Some commits don't have a CI status icon at all
	if (lastCommitStatusIcon) {
		if (lastCommitStatusIcon.classList.contains('octicon-check')) {
			return SUCCESS;
		}

		if (lastCommitStatusIcon.classList.contains('octicon-x')) {
			return FAILURE;
		}

		if (lastCommitStatusIcon.classList.contains('octicon-dot-fill')) {
			return PENDING;
		}
	}

	return false;
}

export async function getCommitStatus(commitSha: string): Promise<CommitStatus> {
	const {repository} = await api.v4uncached(`
		query getCommitStatus($owner: String!, $name: String!, $commitSha: GitObjectID!) {
			repository(owner: $owner, name: $name) {
				object(expression: $commitSha) {
					... on Commit {
						checkSuites(first: 100) {
							nodes {
								checkRuns { totalCount }
								status
								conclusion
							}
						}
					}
				}
			}
		}
	`, {variables: {commitSha}});

	if (repository.object.checkSuites.nodes === 0) {
		return false; // The commit doesn't have any CI checks associated to it
	}

	for (const {checkRuns, status, conclusion} of repository.object.checkSuites.nodes) {
		// Check suites with no runs will always have a status of "QUEUED" (e.g. Dependabot when it's disabled on the repo)
		if (checkRuns.totalCount === 0) {
			continue;
		}

		if (status !== 'COMPLETED') {
			return PENDING;
		}

		if (conclusion !== 'SUCCESS' && conclusion !== 'NEUTRAL' && conclusion !== 'SKIPPED') {
			return FAILURE;
		}
	}

	return SUCCESS;
}