-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandleJira.ts
More file actions
254 lines (223 loc) · 8.51 KB
/
handleJira.ts
File metadata and controls
254 lines (223 loc) · 8.51 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import { Context } from 'probot';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const mdToAdf = require('md-to-adf') as (markdown: string) => { toJSON: () => { type: string; version: number; content: unknown[] } };
const JIRA_ISSUE_KEY_REGEX = /^[A-Z][A-Z0-9]+-\d+$/i;
interface AdfBlock {
type: string;
content?: unknown[];
attrs?: unknown;
}
function prBodyToAdfContent(body: string | null): AdfBlock[] {
const raw = body?.trim() || 'no description';
try {
const adf = mdToAdf(raw);
const json = adf?.toJSON?.();
const content = json?.content;
if (Array.isArray(content) && content.length > 0) {
return content as AdfBlock[];
}
} catch {
// fallback to plain text
}
return [
{
type: 'paragraph',
content: [{ type: 'text', text: `PR description: ${raw}` }],
},
];
}
export const isJiraTaskKey = (arg: string): boolean => JIRA_ISSUE_KEY_REGEX.test(arg.trim());
interface HandleJiraArg {
context: Context;
boardName: string;
parentTaskKey?: string;
pr: {
number: number;
title: string;
body: string | null;
html_url: string;
labels: string[];
milestone?: string | null;
user?: {
login?: string;
} | null;
draft?: boolean;
state?: string;
merged?: boolean;
mergeable_state?: string;
};
requestedBy: string;
commentId: number;
}
const getEnv = (name: string): string => {
const value = process.env[name];
if (!value?.trim()) {
throw new Error(`Missing required env var: ${name}`);
}
return value.trim();
};
const jiraFetch = async (jiraBaseUrl: string, jiraApiToken: string, path: string, options?: { method?: string; body?: string }) => {
const res = await fetch(`${jiraBaseUrl}${path}`, {
method: options?.method ?? 'GET',
headers: {
'Authorization': `Basic ${jiraApiToken}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: options?.body,
});
return { ok: res.ok, status: res.status, text: () => res.text(), json: () => res.json() as Promise<unknown> };
};
async function projectHasVersion(jiraBaseUrl: string, jiraApiToken: string, projectKey: string, versionName: string): Promise<boolean> {
const res = await jiraFetch(jiraBaseUrl, jiraApiToken, `/rest/api/3/project/${encodeURIComponent(projectKey)}/versions`);
if (!res.ok) return false;
const versions = (await res.json()) as { name?: string }[];
return Array.isArray(versions) && versions.some((v) => v.name === versionName);
}
function buildDescriptionContent(usePlainText: boolean, pr: HandleJiraArg['pr'], requestedBy: string): AdfBlock[] {
const rawBody = pr.body?.trim() || 'no description';
const descriptionBlock = usePlainText
? [{ type: 'paragraph' as const, content: [{ type: 'text' as const, text: `PR description: ${rawBody}` }] }]
: prBodyToAdfContent(pr.body);
return [
{ type: 'paragraph', content: [{ type: 'text', text: 'Task automatically created by dionisio-bot.' }] },
{ type: 'paragraph', content: [{ type: 'text', text: `PR: ${pr.html_url}` }] },
{ type: 'paragraph', content: [{ type: 'text', text: 'PR description:' }] },
...descriptionBlock,
{ type: 'paragraph', content: [{ type: 'text', text: `PR author: ${pr.user?.login ?? 'unknown'}` }] },
{ type: 'paragraph', content: [{ type: 'text', text: `Requested by: ${requestedBy}` }] },
];
}
export const handleJira = async ({ context, boardName, parentTaskKey, pr, requestedBy }: HandleJiraArg): Promise<string> => {
const jiraBaseUrl = getEnv('JIRA_BASE_URL').replace(/\/$/, '');
const jiraApiToken = getEnv('JIRA_API_TOKEN');
const hasCommunityLabel = pr.labels.some((label) => label.toLowerCase() === 'community');
const isSubtask = Boolean(parentTaskKey);
const projectKey = parentTaskKey ? parentTaskKey.replace(/-\d+$/, '') : boardName;
const milestoneName = pr.milestone?.trim();
let useFixVersions = Boolean(milestoneName);
let milestoneNotOnBoard = false;
if (useFixVersions && milestoneName) {
const exists = await projectHasVersion(jiraBaseUrl, jiraApiToken, projectKey, milestoneName);
if (!exists) {
useFixVersions = false;
milestoneNotOnBoard = true;
}
}
const buildPayload = (usePlainTextDescription: boolean) => ({
fields: {
project: { key: projectKey },
...(isSubtask ? { parent: { key: parentTaskKey } } : {}),
summary: `${pr.title} [PR #${pr.number}]`,
issuetype: { name: isSubtask ? 'Sub-task' : 'Task' },
...(hasCommunityLabel ? { labels: ['community'] } : {}),
...(useFixVersions && milestoneName ? { fixVersions: [{ name: milestoneName }] } : {}),
description: {
type: 'doc',
version: 1,
content: buildDescriptionContent(usePlainTextDescription, pr, requestedBy),
},
},
});
const headers = {
'Authorization': `Basic ${jiraApiToken}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
};
let response = await fetch(`${jiraBaseUrl}/rest/api/3/issue`, {
method: 'POST',
headers,
body: JSON.stringify(buildPayload(false)),
});
let usedPlainTextDescription = false;
if (!response.ok && response.status === 400) {
const errorBody = await response.text();
const errLower = errorBody.toLowerCase();
const isFixVersionsError = /fixversions|fix version|version/i.test(errorBody);
const isDescriptionError = /description|body|content|invalid.*document|adf/i.test(errLower) || /content.*invalid/i.test(errLower);
if (isFixVersionsError && useFixVersions) {
useFixVersions = false;
milestoneNotOnBoard = true;
response = await fetch(`${jiraBaseUrl}/rest/api/3/issue`, {
method: 'POST',
headers,
body: JSON.stringify(buildPayload(false)),
});
} else if (isDescriptionError) {
usedPlainTextDescription = true;
response = await fetch(`${jiraBaseUrl}/rest/api/3/issue`, {
method: 'POST',
headers,
body: JSON.stringify(buildPayload(true)),
});
}
}
if (!response.ok) {
const body = await response.text();
throw new Error(`Jira request failed (${response.status}): ${body}`);
}
const task = (await response.json()) as { key?: string };
await context.octokit.issues.update({
...context.issue(),
body: `${pr.body?.trim() || 'no description'} \n\n Task: [${task.key}]`,
});
async function updateJiraStatus(issueKey: string, targetStatus: string) {
const transitionsRes = await jiraFetch(jiraBaseUrl, jiraApiToken, `/rest/api/3/issue/${issueKey}/transitions`);
if (!transitionsRes.ok) throw new Error('Failed to fetch Jira transitions');
const transitionsData = (await transitionsRes.json()) as { transitions: { id: string; to: { name: string } }[] };
const transitions = transitionsData.transitions;
const transition = transitions.find((t) => t.to.name.toLowerCase() === targetStatus.toLowerCase());
if (!transition) throw new Error(`No Jira transition found for status: ${targetStatus}`);
const transitionRes = await jiraFetch(jiraBaseUrl, jiraApiToken, `/rest/api/3/issue/${issueKey}/transitions`, {
method: 'POST',
body: JSON.stringify({ transition: { id: transition.id } }),
});
if (!transitionRes.ok) throw new Error(`Failed to transition Jira issue to ${targetStatus}`);
}
let jiraTargetStatus: string | null = null;
if (pr.merged) {
jiraTargetStatus = 'Done';
} else if (pr.mergeable_state && pr.mergeable_state.toLowerCase().includes('queue')) {
jiraTargetStatus = 'QA Tested';
} else if (pr.state === 'open' && pr.draft) {
jiraTargetStatus = 'In Progress';
} else if (pr.state === 'open') {
// Check for approval status
const { owner, repo } = context.repo();
const reviews = await context.octokit.pulls.listReviews({
owner,
repo,
pull_number: pr.number,
});
const approved = reviews.data.some((review: { state: string }) => review.state === 'APPROVED');
if (approved) {
jiraTargetStatus = 'QA Tested';
} else {
jiraTargetStatus = 'Waiting Review';
}
}
if (task.key && jiraTargetStatus) {
try {
await updateJiraStatus(task.key, jiraTargetStatus);
} catch (err: unknown) {
await context.octokit.issues.createComment({
...context.issue(),
body: `⚠️ **Dionisio (Jira)**\n\nFailed to update Jira status to "${jiraTargetStatus}": ${(err as Error).message}`,
});
}
}
const warnings: string[] = [];
if (milestoneNotOnBoard && milestoneName) {
warnings.push(`The milestone **"${milestoneName}"** does not exist on the Jira board; the task was created without Fix version.`);
}
if (usedPlainTextDescription) {
warnings.push('The PR description was sent as plain text because Jira rejected the formatted body.');
}
if (warnings.length > 0) {
await context.octokit.issues.createComment({
...context.issue(),
body: `⚠️ **Dionisio (Jira)**\n\n${warnings.join('\n\n')}`,
});
}
return task.key ?? '';
};