-
Notifications
You must be signed in to change notification settings - Fork 0
358 lines (348 loc) · 17.6 KB
/
Copy pathtask-issue-sync.yml
File metadata and controls
358 lines (348 loc) · 17.6 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
name: Task Issue Sync
on:
issues:
types: [opened, edited, reopened, closed]
workflow_dispatch:
inputs:
issue_number:
description: Managed issue number to sync
required: true
type: number
permissions:
contents: read
issues: write
repository-projects: write
jobs:
sync:
if: ${{ github.event_name == 'workflow_dispatch' || !github.event.issue.pull_request }}
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Sync task issue metadata
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
PROJECTS_TOKEN: ${{ secrets.PROJECTS_TOKEN }}
PROJECT_OWNER: ${{ vars.PROJECT_OWNER }}
PROJECT_OWNER_TYPE: ${{ vars.PROJECT_OWNER_TYPE }}
PROJECT_NUMBER: ${{ vars.PROJECT_NUMBER }}
PROJECT_NAME: ${{ vars.PROJECT_NAME }}
TASK_ISSUE_NUMBER: ${{ github.event.inputs.issue_number || '' }}
with:
script: |
const projectOwner = process.env.PROJECT_OWNER || context.repo.owner;
const projectOwnerType = (process.env.PROJECT_OWNER_TYPE || 'user').toLowerCase();
const projectNumber = Number(process.env.PROJECT_NUMBER || '1');
const projectName = process.env.PROJECT_NAME || 'Team Project';
const groupByPrefix = {
P: 'Product',
B: 'Backend',
F: 'Frontend',
D: 'DevOps',
Q: 'QA',
S: 'Special',
};
const groupLabelByGroup = {
Product: 'team:product',
Backend: 'team:backend',
Frontend: 'team:frontend',
DevOps: 'team:devops',
QA: 'team:qa',
Special: 'team:special',
};
const moduleLabelByModule = {
frontend: 'area:frontend',
backend: 'area:backend',
api: 'area:backend',
docs: 'area:docs',
ci: 'ci',
infra: 'area:devops',
testing: 'area:testing',
};
const trustedAuthorAssociations = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
const projectGraphql = async (query, variables = {}) => {
if (!process.env.PROJECTS_TOKEN) {
return github.graphql(query, variables);
}
const response = await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
authorization: `Bearer ${process.env.PROJECTS_TOKEN}`,
accept: 'application/vnd.github+json',
'content-type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
const payload = await response.json();
if (!response.ok || payload.errors?.length) {
const errors = payload.errors?.map((error) => error.message).join('; ') || `${response.status} ${response.statusText}`;
throw new Error(`GitHub GraphQL request failed: ${errors}`);
}
return payload.data;
};
const dispatchIssueNumber = Number(process.env.TASK_ISSUE_NUMBER || '0');
const issueNumber = dispatchIssueNumber > 0
? dispatchIssueNumber
: Number(context.payload.issue?.number || '0');
if (issueNumber <= 0) throw new Error('Task Issue Sync needs an issue event or workflow_dispatch issue_number.');
const getIssue = async () => {
const response = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
return response.data;
};
const parseTaskCode = (title) => {
const match = title.trim().match(/^\[([PBFDSQ]-\d{3})\]\s+.+$/u);
return match ? match[1] : '';
};
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const cleanValue = (value) => String(value || '').trim().replace(/^`|`$/g, '').replace(/`/g, '').trim();
const readFieldFromBody = (issueBody, label) => {
const pattern = new RegExp(`^-\\s*${escapeRegExp(label)}\\s*[::]\\s*(.+)$`, 'imu');
const match = issueBody.match(pattern);
return match ? cleanValue(match[1]) : '';
};
const parseHourNumber = (value, label, allowZero) => {
const normalized = cleanValue(value || '');
if (!normalized || normalized === '待估' || normalized === '未填写') {
if (allowZero) return { number: 0, text: '0' };
throw new Error(`${label} must be a positive hour number.`);
}
if (!/^\d+(?:\.\d+)?$/u.test(normalized)) {
throw new Error(`${label} must be a non-negative hour number without units.`);
}
const number = Number(normalized);
if (!Number.isFinite(number) || number < 0 || (!allowZero && number === 0)) {
throw new Error(`${label} must be ${allowZero ? 'non-negative' : 'greater than 0'}.`);
}
return { number, text: String(number) };
};
const isManagedIssue = (issue) => {
const issueBody = issue.body || '';
return !issue.pull_request &&
trustedAuthorAssociations.has(issue.author_association) &&
Boolean(parseTaskCode(issue.title || '')) &&
readFieldFromBody(issueBody, 'GitHub Project') === projectName;
};
const buildSyncSource = (issue) => {
if (!isManagedIssue(issue)) return null;
const issueBody = issue.body || '';
const readField = (label) => readFieldFromBody(issueBody, label);
const readHourField = (baseLabel) => readField(`${baseLabel}(小时数)`) || readField(baseLabel);
const taskCode = parseTaskCode(issue.title || '');
const prefix = taskCode[0];
const group = groupByPrefix[prefix];
const issueStatus = readField('状态') || 'Draft';
const priority = readField('优先级') || 'P1';
const batch = readField('批次') || 'Batch 0';
const modules = (readField('模块') || 'docs')
.split(/\s*(?:\/|/|,|,|、|\+|&)\s*/u)
.map(cleanValue)
.filter(Boolean);
const moduleName = modules[0] || 'docs';
const risk = issueStatus === 'Blocked'
? 'Blocked'
: (issueStatus === 'Draft' ? (readField('Risk') || 'Needs Decision') : (readField('Risk') || 'Normal'));
const dependency = readField('依赖任务') || '无';
const projectStatus = issue.state === 'closed'
? 'Done'
: ({ Draft: 'Todo', Ready: 'Todo', Blocked: 'In Progress', 'In Progress': 'In Progress', Review: 'In Progress', Done: 'Done' }[issueStatus] || 'Todo');
const expectedHours = parseHourNumber(
readHourField('预期工时'),
'预期工时(小时数)',
issueStatus === 'Draft'
);
const actualHours = parseHourNumber(readHourField('实际工时'), '实际工时(小时数)', true);
const fingerprint = JSON.stringify({
title: String(issue.title || '').trim(),
state: issue.state,
taskCode,
project: readField('GitHub Project'),
issueStatus,
group,
priority,
batch,
modules,
risk,
dependency,
expectedHours: expectedHours.number,
actualHours: actualHours.number,
});
return {
issue,
fingerprint,
taskCode,
group,
issueStatus,
priority,
batch,
modules,
moduleName,
risk,
dependency,
projectStatus,
expectedHours,
actualHours,
};
};
class SourceChangedError extends Error {
constructor(source) {
super('Task issue source changed during Project sync.');
this.source = source;
}
}
const readCurrentSource = async () => buildSyncSource(await getIssue());
const assertSourceCurrent = async (expectedFingerprint) => {
const currentSource = await readCurrentSource();
if (!currentSource || currentSource.fingerprint !== expectedFingerprint) {
throw new SourceChangedError(currentSource);
}
return currentSource;
};
const projectSelection = projectOwnerType === 'organization'
? `organization(login: $login) { projectV2(number: $number) { id title fields(first: 100) { nodes { ... on ProjectV2Field { id name dataType } ... on ProjectV2SingleSelectField { id name dataType options { id name } } } } } }`
: `user(login: $login) { projectV2(number: $number) { id title fields(first: 100) { nodes { ... on ProjectV2Field { id name dataType } ... on ProjectV2SingleSelectField { id name dataType options { id name } } } } } }`;
const projectQuery = `query($login: String!, $number: Int!) { ${projectSelection} }`;
const itemQuery = `query($issueId: ID!) { node(id: $issueId) { ... on Issue { projectItems(first: 50) { nodes { id project { id title } } } } } }`;
const addItemMutation = `mutation($projectId: ID!, $contentId: ID!) { addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { item { id } } }`;
const updateFieldMutation = `mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: ProjectV2FieldValue!) { updateProjectV2ItemFieldValue(input: { projectId: $projectId, itemId: $itemId, fieldId: $fieldId, value: $value }) { projectV2Item { id } } }`;
const buildUpdatePlan = (project, source) => {
const fieldByName = new Map(project.fields.nodes.filter(Boolean).map((field) => [field.name, field]));
const requireField = (fieldName, dataType) => {
const field = fieldByName.get(fieldName);
if (!field) throw new Error(`Project field '${fieldName}' is unavailable.`);
if (field.dataType !== dataType) {
throw new Error(`Project field '${fieldName}' must be ${dataType}, found ${field.dataType || 'unknown'}.`);
}
return field;
};
const singleSelectUpdate = (fieldName, optionName) => {
const field = requireField(fieldName, 'SINGLE_SELECT');
const option = field.options?.find((candidate) => candidate.name === optionName);
if (!option) throw new Error(`Project field '${fieldName}' option '${optionName}' is unavailable.`);
return { fieldId: field.id, value: { singleSelectOptionId: option.id } };
};
const textUpdate = (fieldName, text) => {
const field = requireField(fieldName, 'TEXT');
return { fieldId: field.id, value: { text } };
};
const numberUpdate = (fieldName, hours) => {
const field = requireField(fieldName, 'NUMBER');
return { fieldId: field.id, value: { number: hours.number } };
};
return [
singleSelectUpdate('Status', source.projectStatus),
singleSelectUpdate('Group', source.group),
singleSelectUpdate('Priority', source.priority),
singleSelectUpdate('Batch', source.batch),
singleSelectUpdate('Module', source.moduleName),
singleSelectUpdate('Risk', source.risk),
textUpdate('Dependency', source.dependency),
numberUpdate('ExpectedHours', source.expectedHours),
numberUpdate('ActualHours', source.actualHours),
textUpdate('OwnerNote', `自动同步自 issue #${source.issue.number};任务编号 ${source.taskCode}。`),
];
};
const syncLabels = async (source) => {
const labelsToAdd = new Set([groupLabelByGroup[source.group]].filter(Boolean));
for (const module of source.modules) {
if (moduleLabelByModule[module]) labelsToAdd.add(moduleLabelByModule[module]);
}
const existingLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
owner: context.repo.owner,
repo: context.repo.repo,
per_page: 100,
});
const existingLabelNames = new Set(existingLabels.map((label) => label.name));
const currentIssueLabels = new Set((source.issue.labels || []).map((label) => (
typeof label === 'string' ? label : label.name
)));
const managedLabels = new Set([
...Object.values(groupLabelByGroup),
...Object.values(moduleLabelByModule),
]);
const validLabels = [...labelsToAdd].filter((label) => existingLabelNames.has(label));
if (validLabels.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: validLabels,
});
}
for (const label of currentIssueLabels) {
if (!managedLabels.has(label) || labelsToAdd.has(label)) continue;
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label,
});
} catch (error) {
if (error.status !== 404) throw error;
}
}
};
let syncSucceeded = false;
let syncErrorMessage = '';
for (let attempt = 0; attempt < 3 && !syncSucceeded; attempt += 1) {
try {
const source = await readCurrentSource();
if (!source) {
core.info('Issue does not look like a managed task issue; skipping.');
return;
}
const projectResult = await projectGraphql(projectQuery, { login: projectOwner, number: projectNumber });
const ownerNode = projectOwnerType === 'organization' ? projectResult.organization : projectResult.user;
const project = ownerNode?.projectV2;
if (!project) throw new Error(`Project '${projectName}' was not found for ${projectOwner}.`);
if (project.title !== projectName) {
throw new Error(`Project number ${projectNumber} resolved to '${project.title}', expected '${projectName}'.`);
}
const updatePlan = buildUpdatePlan(project, source);
const itemResult = await projectGraphql(itemQuery, { issueId: source.issue.node_id });
let item = itemResult.node.projectItems.nodes.find((node) => node.project.id === project.id);
if (!item) {
await assertSourceCurrent(source.fingerprint);
const added = await projectGraphql(addItemMutation, {
projectId: project.id,
contentId: source.issue.node_id,
});
await assertSourceCurrent(source.fingerprint);
item = added.addProjectV2ItemById.item;
}
for (const update of updatePlan) {
await assertSourceCurrent(source.fingerprint);
await projectGraphql(updateFieldMutation, {
projectId: project.id,
itemId: item.id,
fieldId: update.fieldId,
value: update.value,
});
await assertSourceCurrent(source.fingerprint);
}
await assertSourceCurrent(source.fingerprint);
await syncLabels(source);
await assertSourceCurrent(source.fingerprint);
syncSucceeded = true;
} catch (error) {
if (error instanceof SourceChangedError) {
if (!error.source) {
core.warning(`Issue #${issueNumber} stopped matching the managed-task contract during sync.`);
return;
}
syncErrorMessage = error.message;
core.warning(`Task issue source changed; retrying Project sync (${attempt + 1}/3).`);
continue;
}
syncErrorMessage = error.message;
core.warning(`Task issue sync failed: ${error.message}`);
break;
}
}
if (!syncSucceeded) {
if (!syncErrorMessage) syncErrorMessage = 'Task issue source did not stabilize after 3 attempts.';
core.setFailed(`Task issue #${issueNumber} sync blocked. ${syncErrorMessage}`);
}