generated from ubiquity/ts-template
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathgithub.ts
251 lines (227 loc) · 8.31 KB
/
github.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
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
import { RestEndpointMethodTypes } from "@octokit/plugin-rest-endpoint-methods";
import { Octokit } from "@octokit/rest";
import _projects from "../projects.json";
import opt from "../opt.json";
export type GitHubIssue = RestEndpointMethodTypes["issues"]["get"]["response"]["data"];
export type GitHubLabel = {
id: number;
node_id: string;
url: string;
name: string;
description: string | null;
color: string | null;
default: boolean;
};
export const projects = _projects as {
urls: string[];
category?: Record<string, string>;
};
export const DEVPOOL_OWNER_NAME = "ubiquity";
export const DEVPOOL_REPO_NAME = "devpool-directory";
export enum LABELS {
PRICE = "Price",
UNAVAILABLE = "Unavailable",
}
export const octokit = new Octokit({ auth: process.env.DEVPOOL_GITHUB_API_TOKEN });
//=============
// Helpers
//=============
/**
* Closes issues that exist in the devpool but are missing in partner projects
*
* Devpool and partner project issues can be
* out of sync in the following cases:
* - partner project issue was deleted or transferred to another repo
* - partner project repo was deleted from https://github.com/ubiquity/devpool-directory/blob/development/projects.json
* - partner project repo was made private
* @param devpoolIssues all devpool issues array
* @param projectIssues all partner project issues array
*/
export async function forceCloseMissingIssues(devpoolIssues: GitHubIssue[], projectIssues: GitHubIssue[]) {
// for all devpool issues
for (const devpoolIssue of devpoolIssues) {
// if devpool issue does not exist in partners' projects then close it
if (!projectIssues.some((projectIssue) => projectIssue.node_id === getIssueLabelValue(devpoolIssue, "id:"))) {
if (devpoolIssue.state === "open") {
await octokit.rest.issues.update({
owner: DEVPOOL_OWNER_NAME,
repo: DEVPOOL_REPO_NAME,
issue_number: devpoolIssue.number,
state: "closed",
});
console.log(`Closed (missing in partners projects): ${devpoolIssue.html_url}`);
} else {
console.log(`Already closed (missing in partners projects): ${devpoolIssue.html_url}`);
}
}
}
}
/**
* Returns all issues in a repo
* @param ownerName owner name
* @param repoName repo name
* @returns array of issues
*/
export async function getAllIssues(ownerName: string, repoName: string) {
// get all project issues (opened and closed)
let issues: GitHubIssue[] = await octokit.paginate({
method: "GET",
url: `/repos/${ownerName}/${repoName}/issues?state=all`,
});
// remove PRs from the project issues
issues = issues.filter((issue) => !issue.pull_request);
return issues;
}
/**
* Returns all org repositories urls or owner/repo url
* @param orgOrRepo org or repository name
* @returns array of repository urls
*/
export async function getRepoUrls(orgOrRepo: string) {
const params = orgOrRepo.split("/");
let repos: string[] = [];
switch (params.length) {
case 1: // org
try {
const res = await octokit.paginate("GET /orgs/{org}/repos", {
org: orgOrRepo,
});
repos = res.map((repo) => repo.html_url);
} catch (e: unknown) {
console.warn(`Getting ${orgOrRepo} org repositories failed: ${e}`);
}
break;
case 2: // owner/repo
try {
const res = await octokit.rest.repos.get({
owner: params[0],
repo: params[1],
});
if (res.status === 200) {
repos.push(res.data.html_url);
} else console.warn(`Getting repo ${params[0]}/${params[1]} failed: ${res.status}`);
} catch (e: unknown) {
console.warn(`Getting repo ${params[0]}/${params[1]} failed: ${e}`);
}
break;
default:
console.warn(`Neither org or nor repo GitHub provided: ${orgOrRepo}.`);
}
return repos;
}
/**
* Returns array of labels for a devpool issue
* @param issue issue object
* @param projectUrl url of the project
*/
export function getDevpoolIssueLabels(issue: GitHubIssue, projectUrl: string) {
// get owner and repo name from issue's URL because the repo name could be updated
const [ownerName, repoName] = getRepoCredentials(issue.html_url);
// default labels
const devpoolIssueLabels = [
getIssuePriceLabel(issue), // price
`Partner: ${ownerName}/${repoName}`, // partner
`id: ${issue.node_id}`, // id
];
// if project is already assigned then add the "Unavailable" label
if (issue.assignee?.login) devpoolIssueLabels.push(LABELS.UNAVAILABLE);
const labels = issue.labels as GitHubLabel[];
// add all missing labels that exist in a project's issue and don't exist in devpool issue
for (const projectIssueLabel of labels) {
// skip the "Price" label in order to not accidentally generate a permit
if (projectIssueLabel.name.includes("Price")) continue;
// if project issue label does not exist in devpool issue then add it
if (!devpoolIssueLabels.includes(projectIssueLabel.name)) devpoolIssueLabels.push(projectIssueLabel.name);
}
// if project category for the project is defined, add its category label
if (projects.category && projectUrl in projects.category) devpoolIssueLabels.push(projects.category[projectUrl]);
return devpoolIssueLabels;
}
/**
* Returns issue by label
* @param issues issues array
* @param label label string
*/
export function getIssueByLabel(issues: GitHubIssue[], label: string) {
issues = issues.filter((issue) => {
const labels = (issue.labels as GitHubLabel[]).filter((obj) => obj.name === label);
return labels.length > 0;
});
return issues.length > 0 ? issues[0] : null;
}
/**
* Returns label value by label prefix
* Example: "Partner: my/repo" => "my/repo"
* Example: "id: 123qwe" => "123qwe"
* @param issue issue
* @param labelPrefix label prefix
*/
export function getIssueLabelValue(issue: GitHubIssue, labelPrefix: string) {
let labelValue = null;
const labels = issue.labels as GitHubLabel[];
for (const labelObj of labels) {
if (labelObj.name.includes(labelPrefix)) {
labelValue = labelObj.name.split(":")[1].trim();
break;
}
}
return labelValue;
}
/**
* Returns price label from an issue
* @param issue issue object
* @returns price label
*/
export function getIssuePriceLabel(issue: GitHubIssue) {
const defaultPriceLabel = "Pricing: not set";
const labels = issue.labels as GitHubLabel[];
const priceLabels = labels.filter((label) => label.name.includes("Price:") || label.name.includes("Pricing:"));
// NOTICE: we rename "Price" to "Pricing" because the bot removes all manually added price labels starting with "Price:"
return priceLabels.length > 0 ? priceLabels[0].name.replace("Price", "Pricing") : defaultPriceLabel;
}
/**
* Returns owner and repository names from a project URL
* @param projectUrl project URL
* @returns array of owner and repository names
*/
export function getRepoCredentials(projectUrl: string) {
const urlObject = new URL(projectUrl);
const urlPath = urlObject.pathname.split("/");
const ownerName = urlPath[1];
const repoName = urlPath[2];
if (!ownerName || !repoName) {
throw new Error(`Missing owner name or repo name in [${projectUrl}]`);
}
return [ownerName, repoName];
}
/**
* Returns text for social media (twitter, telegram, etc...)
* @param issue Github issue data
* @returns Social media text
* Example:
* ```
* 50 USD for <1 Hour
*
* https://github.com/ubiquity/pay.ubq.fi/issues/65
* ```
*/
export function getSocialMediaText(issue: GitHubIssue): string {
const labels = issue.labels as GitHubLabel[];
const priceLabel = labels.find((label) => label.name.includes("Pricing: "))?.name.replace("Pricing: ", "");
const timeLabel = labels.find((label) => label.name.includes("Time: "))?.name.replace("Time: ", "");
// `issue.body` contains URL to the original issue in partner's project
// while `issue.html_url` contains URL to the mirrored issue from the devpool directory
return `${priceLabel} for ${timeLabel}\n\n${issue.body}`;
}
export async function getProjectUrls() {
const projectUrls = new Set<string>(projects.urls);
for (const orgOrRepo of opt.in) {
const urls: string[] = await getRepoUrls(orgOrRepo);
urls.forEach((url) => projectUrls.add(url));
}
for (const orgOrRepo of opt.out) {
const urls: string[] = await getRepoUrls(orgOrRepo);
urls.forEach((url) => projectUrls.delete(url));
}
return projectUrls;
}