/
InteractiveApproval.ts
109 lines (103 loc) · 2.09 KB
/
InteractiveApproval.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
import { Pull } from './APIClient'
/**
* Driver for the Interactive Approval flow.
*/
export interface InteractiveApprovalDriver {
/**
* Select the pulls to approve.
*
* @param pulls
*/
prompt(pulls: Pull[]): Promise<PromptResponse>
/**
* Called when a PR is approved.
*
* @param message
*/
onApprove(pull: Pull): void
/**
* Called when a PR is approved.
*
* @param message
*/
onApproveFailed(pull: Pull, message: string): void
/**
* Called when there are no PRs to approve.
*/
onEmpty(): void
/**
* Report an error.
*
* @param message
*/
onError(message: string): void
}
/**
* Prompt response.
*/
export interface PromptResponse {
/**
* Selected Pulls to approve.
*/
selected: Pull[]
/**
* The approval text to use.
*/
approvalText: string
}
/**
* Result from interactive approval.
*/
export interface InteractiveApprovalResult {
/**
* The PRs that were approved.
*/
approvedPulls: Pull[]
/**
* The PRs that failed to be approved.
*/
failedPulls: Pull[]
}
export const InteractiveApprovalResult = {
/**
* Empty result.
*/
empty: {
approvedPulls: [],
failedPulls: [],
} as InteractiveApprovalResult,
}
/**
* Interactive approval flow.
*
* @param fetchPulls getter for the pulls
* @param driver
*/
export async function InteractiveApproval(
fetchPulls: () => Promise<Pull[]>,
approve: (pull: Pull, approvalText: string) => Promise<void>,
driver: InteractiveApprovalDriver
): Promise<InteractiveApprovalResult> {
const pulls = await fetchPulls()
const approvedPulls: Pull[] = []
const failedPulls: Pull[] = []
if (pulls.length === 0) {
driver.onEmpty()
return InteractiveApprovalResult.empty
}
const { selected, approvalText } = await driver.prompt(pulls)
for (const pull of selected) {
try {
await approve(pull, approvalText)
approvedPulls.push(pull)
driver.onApprove(pull)
} catch (error) {
failedPulls.push(pull)
driver.onApproveFailed(pull, error.message)
}
}
return {
approvedPulls,
failedPulls,
}
}