-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathtagLinearIssuesWithRelease.mjs
More file actions
331 lines (286 loc) · 9.67 KB
/
tagLinearIssuesWithRelease.mjs
File metadata and controls
331 lines (286 loc) · 9.67 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
#!/usr/bin/env node
/**
* This script automatically tags Linear issues with the release version
* when a new release is published.
*
* It works by:
* 1. Parsing the CHANGELOG.md to find PR numbers for a specific version
* 2. Using the Linear API to find issues that have GitHub PR attachments
* 3. Creating a label for the release version if it doesn't exist
* 4. Adding the release label to those issues
*
* Environment variables required:
* - LINEAR_API_KEY: Linear API key with write access
* - LINEAR_TEAM_ID: Linear team ID (e.g., "SOU")
*
* Usage:
* node scripts/tagLinearIssuesWithRelease.mjs <version>
* Example: node scripts/tagLinearIssuesWithRelease.mjs 4.11.4
*/
import * as fs from "fs";
import * as path from "path";
const LINEAR_API_URL = "https://api.linear.app/graphql";
const GITHUB_REPO = "sourcebot-dev/sourcebot";
async function linearGraphQL(query, variables = {}) {
const apiKey = process.env.LINEAR_API_KEY;
if (!apiKey) {
throw new Error("LINEAR_API_KEY environment variable is required");
}
const response = await fetch(LINEAR_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: apiKey,
},
body: JSON.stringify({ query, variables }),
});
const result = await response.json();
if (result.errors) {
throw new Error(`Linear API error: ${JSON.stringify(result.errors)}`);
}
return result.data;
}
/**
* Parse the changelog to extract PR numbers for a specific version
*/
function getPRsForVersion(changelogPath, version) {
const changelog = fs.readFileSync(changelogPath, "utf-8");
const lines = changelog.split("\n");
const prNumbers = [];
let inTargetVersion = false;
for (const line of lines) {
// Check if we're entering the target version section
const versionMatch = line.match(/^## \[([^\]]+)\]/);
if (versionMatch) {
if (versionMatch[1] === version) {
inTargetVersion = true;
continue;
} else if (inTargetVersion) {
// We've moved past the target version, stop parsing
break;
}
}
// If we're in the target version section, extract PR numbers
if (inTargetVersion) {
const prMatches = line.matchAll(/\[#(\d+)\]\([^)]+\)/g);
for (const match of prMatches) {
prNumbers.push(parseInt(match[1], 10));
}
}
}
return [...new Set(prNumbers)]; // Remove duplicates
}
/**
* Find Linear issues that have attachments linking to the given GitHub PRs
*/
async function findLinearIssuesForPRs(prNumbers) {
const issues = [];
for (const prNumber of prNumbers) {
const prUrl = `https://github.com/${GITHUB_REPO}/pull/${prNumber}`;
// Query Linear for attachments that match this PR URL
const data = await linearGraphQL(
`
query($url: String!) {
attachmentsForURL(url: $url) {
nodes {
id
url
issue {
id
identifier
title
labels {
nodes {
id
name
}
}
}
}
}
}
`,
{ url: prUrl }
);
if (data.attachmentsForURL?.nodes) {
for (const attachment of data.attachmentsForURL.nodes) {
if (attachment.issue) {
issues.push({
issueId: attachment.issue.id,
identifier: attachment.issue.identifier,
title: attachment.issue.title,
existingLabels: attachment.issue.labels?.nodes || [],
prNumber,
});
}
}
}
}
// Remove duplicate issues (same issue might be linked to multiple PRs)
const uniqueIssues = [];
const seenIds = new Set();
for (const issue of issues) {
if (!seenIds.has(issue.issueId)) {
seenIds.add(issue.issueId);
uniqueIssues.push(issue);
}
}
return uniqueIssues;
}
/**
* Get the team ID from the team key
*/
async function getTeamId(teamKey) {
const data = await linearGraphQL(
`
query($key: String!) {
team(id: $key) {
id
name
}
}
`,
{ key: teamKey }
);
if (!data.team) {
throw new Error(`Team with key "${teamKey}" not found`);
}
return data.team.id;
}
/**
* Find or create a label for the release version
*/
async function findOrCreateReleaseLabel(teamId, version) {
const labelName = `v${version}`;
// First, search for existing label
const searchData = await linearGraphQL(
`
query($teamId: String!) {
team(id: $teamId) {
labels {
nodes {
id
name
}
}
}
}
`,
{ teamId }
);
const existingLabel = searchData.team?.labels?.nodes?.find(
(label) => label.name === labelName
);
if (existingLabel) {
console.log(`Found existing label: ${labelName}`);
return existingLabel.id;
}
// Create the label if it doesn't exist
console.log(`Creating new label: ${labelName}`);
const createData = await linearGraphQL(
`
mutation($teamId: String!, $name: String!) {
issueLabelCreate(input: { teamId: $teamId, name: $name, color: "#10B981" }) {
issueLabel {
id
name
}
success
}
}
`,
{ teamId, name: labelName }
);
if (!createData.issueLabelCreate?.success) {
throw new Error(`Failed to create label: ${labelName}`);
}
return createData.issueLabelCreate.issueLabel.id;
}
/**
* Add a label to an issue
*/
async function addLabelToIssue(issueId, labelId, existingLabelIds) {
// Combine existing labels with the new one
const allLabelIds = [...new Set([...existingLabelIds, labelId])];
const data = await linearGraphQL(
`
mutation($issueId: String!, $labelIds: [String!]!) {
issueUpdate(id: $issueId, input: { labelIds: $labelIds }) {
success
issue {
identifier
}
}
}
`,
{ issueId, labelIds: allLabelIds }
);
return data.issueUpdate?.success;
}
async function main() {
const version = process.argv[2];
if (!version) {
console.error("Usage: node tagLinearIssuesWithRelease.mjs <version>");
console.error("Example: node tagLinearIssuesWithRelease.mjs 4.11.4");
process.exit(1);
}
const teamKey = process.env.LINEAR_TEAM_ID;
if (!teamKey) {
console.error("LINEAR_TEAM_ID environment variable is required");
process.exit(1);
}
console.log(`Tagging Linear issues for release v${version}`);
// Find the changelog file
const changelogPath = path.join(process.cwd(), "CHANGELOG.md");
if (!fs.existsSync(changelogPath)) {
console.error(`Changelog not found at: ${changelogPath}`);
process.exit(1);
}
// Step 1: Parse changelog for PR numbers
console.log("\n1. Parsing changelog for PR numbers...");
const prNumbers = getPRsForVersion(changelogPath, version);
if (prNumbers.length === 0) {
console.log(`No PRs found for version ${version}`);
process.exit(0);
}
console.log(` Found ${prNumbers.length} PRs: ${prNumbers.join(", ")}`);
// Step 2: Find Linear issues for these PRs
console.log("\n2. Finding Linear issues linked to these PRs...");
const issues = await findLinearIssuesForPRs(prNumbers);
if (issues.length === 0) {
console.log(" No Linear issues found linked to these PRs");
process.exit(0);
}
console.log(` Found ${issues.length} Linear issues:`);
for (const issue of issues) {
console.log(` - ${issue.identifier}: ${issue.title} (PR #${issue.prNumber})`);
}
// Step 3: Get team ID and find/create release label
console.log("\n3. Finding or creating release label...");
const teamId = await getTeamId(teamKey);
const labelId = await findOrCreateReleaseLabel(teamId, version);
// Step 4: Add label to all issues
console.log("\n4. Adding release label to issues...");
let successCount = 0;
for (const issue of issues) {
const existingLabelIds = issue.existingLabels.map((l) => l.id);
// Check if issue already has the label
if (issue.existingLabels.some((l) => l.name === `v${version}`)) {
console.log(` ${issue.identifier}: Already has label v${version}, skipping`);
successCount++;
continue;
}
const success = await addLabelToIssue(issue.issueId, labelId, existingLabelIds);
if (success) {
console.log(` ${issue.identifier}: Added label v${version}`);
successCount++;
} else {
console.error(` ${issue.identifier}: Failed to add label`);
}
}
console.log(`\nDone! Tagged ${successCount}/${issues.length} issues with v${version}`);
}
main().catch((error) => {
console.error("Error:", error.message);
process.exit(1);
});