generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
automerge.ts
182 lines (163 loc) · 6.14 KB
/
automerge.ts
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, camelcase*/
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Octokit } from '@octokit/core';
import { Env } from '@salesforce/kit';
import { ensureString } from '@salesforce/ts-types';
import { Messages } from '@salesforce/core';
import { maxVersionBumpFlag, getOwnerAndRepo } from '../../dependabot.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-release-management', 'dependabot.automerge');
const messagesFromConsolidate = Messages.loadMessages(
'@salesforce/plugin-release-management',
'dependabot.consolidate'
);
type PullRequest = {
state: string;
title: string;
user: {
login: string;
};
html_url: string;
number: number;
head: {
sha: string;
ref: string;
};
}
type octokitOpts = {
owner: string;
repo: string;
pull_number: number;
commit_title?: string;
merge_method?: 'merge' | 'squash' | 'rebase';
};
export default class AutoMerge extends SfCommand<void> {
public static readonly summary = messages.getMessage('description');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly flags = {
owner: Flags.string({
// eslint-disable-next-line sf-plugin/dash-o
char: 'o',
summary: messagesFromConsolidate.getMessage('owner'),
dependsOn: ['repo'],
}),
repo: Flags.string({
char: 'r',
summary: messagesFromConsolidate.getMessage('repo'),
dependsOn: ['owner'],
}),
'max-version-bump': maxVersionBumpFlag,
dryrun: Flags.boolean({
summary: messagesFromConsolidate.getMessage('dryrun'),
char: 'd',
default: false,
}),
'skip-ci': Flags.boolean({
summary: messages.getMessage('flags.skip-ci.summary'),
char: 's',
default: false,
}),
'merge-method': Flags.string({
summary: messages.getMessage('flags.merge-method.summary'),
options: ['merge', 'squash', 'rebase'],
default: 'merge',
}),
};
// private props initialized early in run()
private octokit!: Octokit;
private baseRepoObject!: {
owner: string;
repo: string;
};
public async run(): Promise<void> {
const { flags } = await this.parse(AutoMerge);
const auth = ensureString(
new Env().getString('GH_TOKEN') ?? new Env().getString('GITHUB_TOKEN'),
'GH_TOKEN is required to be set in the environment'
);
this.baseRepoObject = await getOwnerAndRepo(flags.owner, flags.repo);
this.octokit = new Octokit({ auth });
this.log(`owner: ${this.baseRepoObject.owner}, scope: ${this.baseRepoObject.repo}`);
const eligiblePRs = (
await this.octokit.request('GET /repos/{owner}/{repo}/pulls', this.baseRepoObject)
).data.filter(
(pr) =>
pr.state === 'open' &&
(pr.user?.login === 'dependabot[bot]' ||
(pr.title.includes('refactor: devScripts update') && pr.user?.login === 'svc-cli-bot'))
) as PullRequest[];
const greenPRs = (await Promise.all(eligiblePRs.map((pr) => this.isGreen(pr)))).filter(isPrNotUndefined);
const mergeablePRs = (await Promise.all(greenPRs.map((pr) => this.isMergeable(pr)))).filter(isPrNotUndefined);
this.table(
mergeablePRs.map((pr) => ({ title: pr.title, html_url: pr.html_url })),
{
title: { header: 'Green, Mergeable PR' },
html_url: { header: 'Link' },
}
);
this.log('');
const prToMerge = mergeablePRs[0];
if (!prToMerge) {
this.log('No PRs can be automerged');
return;
}
if (flags.dryrun === false) {
this.log(`merging ${prToMerge.number.toString()} | ${prToMerge.title}`);
const opts: octokitOpts = {
...this.baseRepoObject,
// TODO: make oclif smarter about options on flags
merge_method: flags['merge-method'] as 'merge' | 'squash' | 'rebase',
pull_number: prToMerge.number,
};
if (flags['skip-ci']) {
opts.commit_title = `Merge pull request #${prToMerge.number} from ${prToMerge.head.ref} [skip ci]`;
}
const mergeResult = await this.octokit.request('PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge', opts);
this.styledJSON(mergeResult);
} else {
this.log(`dry run ${prToMerge.number.toString()} | ${prToMerge.title}`);
}
}
private async isGreen(pr: PullRequest): Promise<PullRequest | undefined> {
const statusResponse = await this.octokit.request('GET /repos/{owner}/{repo}/commits/{ref}/status', {
...this.baseRepoObject,
ref: pr.head.sha,
});
// no point looking at check runs if the commit status is not green
if (statusResponse.data.state !== 'success') {
return undefined;
}
const checkRunResponse = await this.octokit.request('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', {
...this.baseRepoObject,
ref: pr.head.sha,
});
this.styledJSON(checkRunResponse.data);
if (
checkRunResponse.data.check_runs.every(
(cr) => cr.status === 'completed' && cr.conclusion && ['success', 'skipped'].includes(cr.conclusion)
)
) {
return pr;
}
}
private async isMergeable(pr: PullRequest): Promise<PullRequest | undefined> {
const statusResponse = await this.octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}', {
...this.baseRepoObject,
pull_number: pr.number,
});
// mergeable_state of 'blocked' is ok because that's just missing an approval.
// We're screening out 'behind' which might be merge conflicts.
// Dependabot should rebase this PR eventually
if (statusResponse.data.mergeable === true && statusResponse.data.mergeable_state !== 'behind') {
return pr;
}
}
}
const isPrNotUndefined = (pr: PullRequest | undefined): pr is PullRequest => pr !== undefined;