-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject_repository.ts
More file actions
808 lines (707 loc) · 28.5 KB
/
project_repository.ts
File metadata and controls
808 lines (707 loc) · 28.5 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
import * as github from "@actions/github";
import { logDebugInfo, logError, logInfo } from "../../utils/logger";
import { ProjectResult } from "../graph/project_result";
import { ProjectDetail } from "../model/project_detail";
export class ProjectRepository {
private readonly priorityLabel = "Priority"
private readonly sizeLabel = "Size"
private readonly statusLabel = "Status"
/**
* Retrieves detailed information about a GitHub project
* @param projectId - The project number/ID
* @param token - GitHub authentication token
* @returns Promise<ProjectDetail> - The project details
* @throws {Error} If the project is not found or if there are authentication/network issues
*/
getProjectDetail = async (projectId: string, token: string): Promise<ProjectDetail> => {
try {
// Validate projectId is a valid number
const projectNumber = parseInt(projectId, 10);
if (isNaN(projectNumber)) {
throw new Error(`Invalid project ID: ${projectId}. Must be a valid number.`);
}
const octokit = github.getOctokit(token);
const { data: owner } = await octokit.rest.users.getByUsername({
username: github.context.repo.owner
}).catch(error => {
throw new Error(`Failed to get owner information: ${error.message}`);
});
const ownerType = owner.type === 'Organization' ? 'orgs' : 'users';
const projectUrl = `https://github.com/${ownerType}/${github.context.repo.owner}/projects/${projectId}`;
const ownerQueryField = ownerType === 'orgs' ? 'organization' : 'user';
const queryProject = `
query($ownerName: String!, $projectNumber: Int!) {
${ownerQueryField}(login: $ownerName) {
projectV2(number: $projectNumber) {
id
title
url
}
}
}
`;
const projectResult = await octokit.graphql<ProjectResult>(queryProject, {
ownerName: github.context.repo.owner,
projectNumber: projectNumber,
}).catch(error => {
throw new Error(`Failed to fetch project data: ${error.message}`);
});
const projectData = projectResult[ownerQueryField]?.projectV2;
if (!projectData) {
throw new Error(`Project not found: ${projectUrl}`);
}
logDebugInfo(`Project ID: ${projectData.id}`);
logDebugInfo(`Project Title: ${projectData.title}`);
logDebugInfo(`Project URL: ${projectData.url}`);
return new ProjectDetail({
id: projectData.id,
title: projectData.title,
url: projectData.url,
type: ownerQueryField,
owner: github.context.repo.owner,
number: projectNumber,
});
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
logError(`Error in getProjectDetail: ${errorMessage}`);
throw error;
}
};
private getContentId = async (
project: ProjectDetail,
owner: string,
repo: string,
issueOrPullRequestNumber: number,
token: string
): Promise<string | undefined> => {
const octokit = github.getOctokit(token);
// Search for the issue or pull request ID in the repository
const issueOrPrQuery = `
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
issueOrPullRequest: issueOrPullRequest(number: $number) {
... on Issue {
id
}
... on PullRequest {
id
}
}
}
}`;
const issueOrPrResult = await octokit.graphql<{ repository: { issueOrPullRequest?: { id: string } } }>(issueOrPrQuery, {
owner,
repo,
number: issueOrPullRequestNumber
});
if (!issueOrPrResult.repository.issueOrPullRequest) {
logError(`Issue or PR #${issueOrPullRequestNumber} not found in repository.`);
return undefined;
}
const contentId = issueOrPrResult.repository.issueOrPullRequest.id;
// Search for the item ID in the project with pagination
let cursor: string | null = null;
let projectItemId: string | undefined = undefined;
let totalItemsChecked = 0;
const maxPages = 100; // 100 * 100 = 10_000 items max to avoid runaway loops
let pageCount = 0;
do {
if (pageCount >= maxPages) {
logError(`Stopped after ${maxPages} pages (${totalItemsChecked} items). Issue or PR #${issueOrPullRequestNumber} not found in project.`);
break;
}
pageCount += 1;
const projectQuery = `
query($projectId: ID!, $cursor: String) {
node(id: $projectId) {
... on ProjectV2 {
items(first: 100, after: $cursor) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
content {
... on Issue {
id
}
... on PullRequest {
id
}
}
}
}
}
}
}`;
interface ProjectItemsNode { id: string; content?: { id?: string } }
type ProjectItemsResponse = { node: { items?: { nodes: ProjectItemsNode[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } } } | null };
const projectResult: ProjectItemsResponse = await octokit.graphql<ProjectItemsResponse>(projectQuery, {
projectId: project.id,
cursor
});
if (projectResult.node === null) {
logError(`Project not found for ID "${project.id}". Ensure the project is loaded via getProjectDetail (GraphQL node ID), not the project number.`);
throw new Error(
`Project not found or invalid project ID. The project ID must be the GraphQL node ID from the API (e.g. PVT_...), not the project number.`
);
}
const items = projectResult.node.items?.nodes ?? [];
totalItemsChecked += items.length;
const pageInfo = projectResult.node.items?.pageInfo;
const foundItem = items.find((item: ProjectItemsNode) => item.content?.id === contentId);
if (foundItem) {
projectItemId = foundItem.id;
break;
}
// Advance cursor only when there is a next page AND a non-null cursor (avoid missing pages)
const hasNextPage = pageInfo?.hasNextPage === true;
const endCursor = pageInfo?.endCursor ?? null;
if (hasNextPage && endCursor) {
cursor = endCursor;
} else {
if (hasNextPage && !endCursor) {
logError(`Project items pagination: hasNextPage is true but endCursor is null (page ${pageCount}, ${totalItemsChecked} items so far). Cannot fetch more.`);
}
cursor = null;
}
} while (cursor);
if (projectItemId === undefined) {
logError(
`Issue or PR #${issueOrPullRequestNumber} not found in project after checking ${totalItemsChecked} items (${pageCount} page(s)). ` +
`Link it to the project first, or wait for the board to sync.`
);
throw new Error(
`Issue or pull request #${issueOrPullRequestNumber} is not in the project yet (checked ${totalItemsChecked} items). Link it to the project first, or wait for the board to sync.`
);
}
return projectItemId;
};
isContentLinked = async (
project: ProjectDetail,
contentId: string,
token: string
): Promise<boolean> => {
const octokit = github.getOctokit(token);
let hasNextPage = true;
let endCursor: string | null = null;
let allItems: Array<{ content?: { id?: string } }> = [];
while (hasNextPage) {
const query = `
query($projectId: ID!, $after: String) {
node(id: $projectId) {
... on ProjectV2 {
items(first: 100, after: $after) {
nodes {
content {
... on PullRequest {
id
}
... on Issue {
id
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}
`;
// logDebugInfo(`Query: ${query}`);
// logDebugInfo(`Project ID: ${project.id}`);
// logDebugInfo(`Content ID: ${contentId}`);
// logDebugInfo(`After cursor: ${endCursor}`);
type ItemsResult = { node: { items: { nodes: Array<{ content?: { id?: string } }>; pageInfo: { hasNextPage: boolean; endCursor: string | null } } } };
const result: ItemsResult = await octokit.graphql<ItemsResult>(query, {
projectId: project.id,
after: endCursor,
});
// logDebugInfo(`Result: ${JSON.stringify(result, null, 2)}`);
const items = result.node.items.nodes;
allItems = allItems.concat(items);
hasNextPage = result.node.items.pageInfo.hasNextPage;
endCursor = result.node.items.pageInfo.endCursor;
}
return allItems.some(
(item) => item.content && item.content.id === contentId
);
};
linkContentId = async (project: ProjectDetail, contentId: string, token: string) => {
const alreadyLinked = await this.isContentLinked(project, contentId, token);
if (alreadyLinked) {
logDebugInfo(`Content ${contentId} is already linked to project ${project.id}.`);
return false;
}
const octokit = github.getOctokit(token);
const linkMutation = `
mutation($projectId: ID!, $contentId: ID!) {
addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) {
item {
id
}
}
}
`;
const linkResult = await octokit.graphql<{ addProjectV2ItemById?: { item?: { id: string } } }>(linkMutation, {
projectId: project.id,
contentId: contentId,
});
logDebugInfo(`Linked ${contentId} with id ${linkResult.addProjectV2ItemById?.item?.id ?? ''} to project ${project.id}`);
return true;
}
private setSingleSelectFieldValue = async (
project: ProjectDetail,
owner: string,
repo: string,
issueOrPullRequestNumber: number,
fieldName: string,
fieldValue: string,
token: string
): Promise<boolean> => {
const contentId = await this.getContentId(project, owner, repo, issueOrPullRequestNumber, token);
if (!contentId) {
logError(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`);
throw new Error(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`);
}
logDebugInfo(`Content ID: ${contentId}`);
const octokit = github.getOctokit(token);
// Get the field ID and current value
const fieldQuery = `
query($projectId: ID!, $after: String) {
node(id: $projectId) {
... on ProjectV2 {
fields(first: 20) {
nodes {
... on ProjectV2SingleSelectField {
id
name
options {
id
name
}
}
}
}
items(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
fieldValues(first: 20) {
nodes {
... on ProjectV2ItemFieldSingleSelectValue {
field {
... on ProjectV2SingleSelectField {
name
}
}
optionId
}
}
}
}
}
}
}
}`;
let hasNextPage = true;
let endCursor: string | null = null;
interface FieldNode { id: string; name: string; options?: Array<{ id: string; name: string }> }
interface ItemNode { id: string; fieldValues?: { nodes: Array<{ field?: { name: string }; optionId?: string }> } }
type FieldResult = { node: { fields: { nodes: FieldNode[] }; items: { nodes: ItemNode[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } } } };
let currentItem: ItemNode | null = null;
// Get the field and option information from the first page
const initialFieldResult = await octokit.graphql<FieldResult>(fieldQuery, {
projectId: project.id,
after: null
});
const targetField = initialFieldResult.node.fields.nodes.find(
(f: FieldNode) => f.name === fieldName
);
logDebugInfo(`Target field: ${JSON.stringify(targetField, null, 2)}`);
if (!targetField) {
logError(`Field '${fieldName}' not found or is not a single-select field.`);
throw new Error(`Field '${fieldName}' not found or is not a single-select field.`);
}
const targetOption = targetField.options?.find(
(opt: { id: string; name: string }) => opt.name === fieldValue
);
logDebugInfo(`Target option: ${JSON.stringify(targetOption, null, 2)}`);
if (!targetOption) {
logError(`Option '${fieldValue}' not found for field '${fieldName}'.`);
throw new Error(`Option '${fieldValue}' not found for field '${fieldName}'.`);
}
// Now search for the item through all pages
while (hasNextPage) {
const fieldResult: FieldResult = await octokit.graphql<FieldResult>(fieldQuery, {
projectId: project.id,
after: endCursor
});
// logDebugInfo(`Field result: ${JSON.stringify(fieldResult, null, 2)}`);
// Check current value in current page
currentItem = fieldResult.node.items.nodes.find((item: ItemNode) => item.id === contentId) ?? null;
if (currentItem) {
// logDebugInfo(`Current item: ${JSON.stringify(currentItem, null, 2)}`);
const currentFieldValue = currentItem.fieldValues?.nodes.find(
(value: { field?: { name: string }; optionId?: string }) => value.field?.name === fieldName
);
if (currentFieldValue && currentFieldValue.optionId === targetOption.id) {
logDebugInfo(`Field '${fieldName}' is already set to '${fieldValue}'. No update needed.`);
return false;
}
break; // Found the item, no need to continue pagination
}
hasNextPage = fieldResult.node.items.pageInfo.hasNextPage;
endCursor = fieldResult.node.items.pageInfo.endCursor;
}
logDebugInfo(`Target field ID: ${targetField.id}`);
logDebugInfo(`Target option ID: ${targetOption.id}`);
const mutation = `
mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
updateProjectV2ItemFieldValue(
input: {
projectId: $projectId,
itemId: $itemId,
fieldId: $fieldId,
value: { singleSelectOptionId: $optionId }
}
) {
projectV2Item {
id
}
}
}`;
const mutationResult = await octokit.graphql<{ updateProjectV2ItemFieldValue?: { projectV2Item?: { id: string } } }>(mutation, {
projectId: project.id,
itemId: contentId,
fieldId: targetField.id,
optionId: targetOption.id
});
return !!mutationResult.updateProjectV2ItemFieldValue?.projectV2Item;
};
setTaskPriority = async (
project: ProjectDetail,
owner: string,
repo: string,
issueOrPullRequestNumber: number,
priorityLabel: string,
token: string
): Promise<boolean> => this.setSingleSelectFieldValue(
project,
owner,
repo,
issueOrPullRequestNumber,
this.priorityLabel,
priorityLabel,
token
);
setTaskSize = async (
project: ProjectDetail,
owner: string,
repo: string,
issueOrPullRequestNumber: number,
sizeLabel: string,
token: string
): Promise<boolean> => this.setSingleSelectFieldValue(
project,
owner,
repo,
issueOrPullRequestNumber,
this.sizeLabel,
sizeLabel,
token
);
moveIssueToColumn = async (
project: ProjectDetail,
owner: string,
repo: string,
issueOrPullRequestNumber: number,
columnName: string,
token: string
): Promise<boolean> => this.setSingleSelectFieldValue(
project,
owner,
repo,
issueOrPullRequestNumber,
this.statusLabel,
columnName,
token
);
getRandomMembers = async (
organization: string,
membersToAdd: number,
currentMembers: string[],
token: string
): Promise<string[]> => {
if (membersToAdd === 0) {
return [];
}
const octokit = github.getOctokit(token);
try {
const {data: teams} = await octokit.rest.teams.list({
org: organization,
});
if (teams.length === 0) {
logDebugInfo(`${organization} doesn't have any team.`);
return [];
}
const membersSet = new Set<string>();
for (const team of teams) {
logDebugInfo(`Checking team: ${team.slug}`);
const {data: members} = await octokit.rest.teams.listMembersInOrg({
org: organization,
team_slug: team.slug,
});
logDebugInfo(`Members: ${members.length}`);
members.forEach((member) => membersSet.add(member.login));
}
const allMembers = Array.from(membersSet);
const availableMembers = allMembers.filter((member) => !currentMembers.includes(member));
if (availableMembers.length === 0) {
logDebugInfo(`No available members to assign for organization ${organization}.`);
return [];
}
if (membersToAdd >= availableMembers.length) {
logDebugInfo(
`Requested size (${membersToAdd}) exceeds available members (${availableMembers.length}). Returning all available members.`
);
return availableMembers;
}
const shuffled = availableMembers.sort(() => Math.random() - 0.5);
return shuffled.slice(0, membersToAdd);
} catch (error) {
logError(`Error getting random members: ${error}.`);
}
return [];
};
getAllMembers = async (
organization: string,
token: string
): Promise<string[]> => {
const octokit = github.getOctokit(token);
try {
const {data: teams} = await octokit.rest.teams.list({
org: organization,
});
if (teams.length === 0) {
logDebugInfo(`${organization} doesn't have any team.`);
return [];
}
const membersSet = new Set<string>();
for (const team of teams) {
const {data: members} = await octokit.rest.teams.listMembersInOrg({
org: organization,
team_slug: team.slug,
});
members.forEach((member) => membersSet.add(member.login));
}
return Array.from(membersSet);
} catch (error) {
logError(`Error getting all members: ${error}.`);
}
return [];
};
getUserFromToken = async (token: string): Promise<string> => {
const octokit = github.getOctokit(token);
const {data: user} = await octokit.rest.users.getAuthenticated();
return user.login;
};
/**
* Returns true if the actor (user who triggered the event) is allowed to run use cases
* that ask OpenCode to modify files (e.g. bugbot autofix, generic user request).
* - When the repo owner is an Organization: actor must be a member of that organization.
* - When the repo owner is a User: actor must be the owner (same login).
*/
isActorAllowedToModifyFiles = async (
owner: string,
actor: string,
token: string
): Promise<boolean> => {
try {
const octokit = github.getOctokit(token);
const { data: ownerUser } = await octokit.rest.users.getByUsername({ username: owner });
if (ownerUser.type === "Organization") {
try {
await octokit.rest.orgs.checkMembershipForUser({
org: owner,
username: actor,
});
return true;
} catch (membershipErr: unknown) {
const status = (membershipErr as { status?: number })?.status;
if (status === 404) return false;
logDebugInfo(`checkMembershipForUser(${owner}, ${actor}): ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
return false;
}
}
return actor === owner;
} catch (err) {
logDebugInfo(`isActorAllowedToModifyFiles(${owner}, ${actor}): ${err instanceof Error ? err.message : String(err)}`);
return false;
}
};
/** Name and email of the token user, for git commit author (e.g. bugbot autofix). */
getTokenUserDetails = async (token: string): Promise<{ name: string; email: string }> => {
const octokit = github.getOctokit(token);
const { data: user } = await octokit.rest.users.getAuthenticated();
const name = (user.name ?? user.login ?? "GitHub Action").trim() || "GitHub Action";
const email =
(typeof user.email === "string" && user.email.trim().length > 0)
? user.email.trim()
: `${user.login}@users.noreply.github.com`;
return { name, email };
};
private findTag = async (owner: string, repo: string, tag: string, token: string): Promise<{ object: { sha: string } } | undefined> => {
const octokit = github.getOctokit(token);
try {
const { data: foundTag } = await octokit.rest.git.getRef({
owner,
repo,
ref: `tags/${tag}`,
});
return foundTag;
} catch {
return undefined;
}
}
private getTagSHA = async (owner: string, repo: string, tag: string, token: string): Promise<string | undefined> => {
const foundTag = await this.findTag(owner, repo, tag, token);
if (!foundTag) {
logError(`The '${tag}' tag does not exist in the remote repository`);
return undefined;
}
return foundTag.object.sha;
}
updateTag = async (owner: string, repo: string, sourceTag: string, targetTag: string, token: string): Promise<void> => {
const sourceTagSHA = await this.getTagSHA(owner, repo, sourceTag, token);
if (!sourceTagSHA) {
logError(`The '${sourceTag}' tag does not exist in the remote repository`);
return;
}
const foundTargetTag = await this.findTag(owner, repo, targetTag, token);
const refName = `tags/${targetTag}`;
const octokit = github.getOctokit(token);
if (foundTargetTag) {
logDebugInfo(`Updating the '${targetTag}' tag to point to the '${sourceTag}' tag`);
await octokit.rest.git.updateRef({
owner,
repo,
ref: refName,
sha: sourceTagSHA,
force: true,
});
} else {
logDebugInfo(`Creating the '${targetTag}' tag from the '${sourceTag}' tag`);
await octokit.rest.git.createRef({
owner,
repo,
ref: `refs/${refName}`,
sha: sourceTagSHA,
});
}
}
updateRelease = async (owner: string, repo: string, sourceTag: string, targetTag: string, token: string): Promise<string | undefined> => {
// Get the release associated with sourceTag
const octokit = github.getOctokit(token);
const { data: sourceRelease } = await octokit.rest.repos.getReleaseByTag({
owner,
repo,
tag: sourceTag,
});
if (!sourceRelease.name || !sourceRelease.body) {
logError(`The '${sourceTag}' tag does not exist in the remote repository`);
return undefined;
}
logDebugInfo(`Found release for sourceTag '${sourceTag}': ${sourceRelease.name}`);
// Check if there is a release for targetTag
const { data: releases } = await octokit.rest.repos.listReleases({
owner,
repo,
});
const targetRelease = releases.find(r => r.tag_name === targetTag);
let targetReleaseId;
if (targetRelease) {
logDebugInfo(`Updating release for targetTag '${targetTag}'`);
// Update the target release with the content from the source release
await octokit.rest.repos.updateRelease({
owner,
repo,
release_id: targetRelease.id,
name: sourceRelease.name,
body: sourceRelease.body,
draft: sourceRelease.draft,
prerelease: sourceRelease.prerelease,
});
targetReleaseId = targetRelease.id;
} else {
console.log(`Creating new release for targetTag '${targetTag}'`);
// Create a new release for targetTag if it doesn't exist
const { data: newRelease } = await octokit.rest.repos.createRelease({
owner,
repo,
tag_name: targetTag,
name: sourceRelease.name,
body: sourceRelease.body,
draft: sourceRelease.draft,
prerelease: sourceRelease.prerelease,
});
targetReleaseId = newRelease.id;
}
logInfo(`Updated release for targetTag '${targetTag}'`);
return targetReleaseId.toString();
}
createRelease = async (owner: string, repo: string, version: string, title: string, changelog: string, token: string): Promise<string | undefined> => {
try {
const octokit = github.getOctokit(token);
const { data: release } = await octokit.rest.repos.createRelease({
owner,
repo,
tag_name: version,
name: `${version} - ${title}`,
body: changelog,
draft: false,
prerelease: false,
});
return release.html_url;
} catch (error) {
logError(`Error creating release: ${error}`);
return undefined;
}
}
createTag = async (owner: string, repo: string, branch: string, tag: string, token: string): Promise<string | undefined> => {
const octokit = github.getOctokit(token);
try {
// Check if tag already exists
const existingTag = await this.findTag(owner, repo, tag, token);
if (existingTag) {
logInfo(`Tag '${tag}' already exists in repository ${owner}/${repo}`);
return existingTag.object.sha;
}
// Get the latest commit SHA from the specified branch
const { data: ref } = await octokit.rest.git.getRef({
owner,
repo,
ref: `heads/${branch}`,
});
// Create the tag
await octokit.rest.git.createRef({
owner,
repo,
ref: `refs/tags/${tag}`,
sha: ref.object.sha,
});
logInfo(`Created tag '${tag}' in repository ${owner}/${repo} from branch '${branch}'`);
return ref.object.sha;
} catch (error) {
logError(`Error creating tag '${tag}': ${JSON.stringify(error, null, 2)}`);
return undefined;
}
}
}