-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
253 lines (222 loc) · 9.79 KB
/
index.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
252
253
/******************************************************/
/**
* @author Vedansh (offensive-vk)
* @url https://github.com/offensive-vk/auto-label/
* @lang TypeScript + Node.js + Octokit
* @type Github Action for Applying Labels on PRs.
* @runs Nodejs v20.x
* @bundler esbuild
*/
/******************************************************/
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as yaml from 'js-yaml';
import * as fs from 'fs';
import { minimatch } from 'minimatch';
import { Octokit } from '@octokit/rest';
const context = github.context;
interface LabelConfig {
label: string;
match: Array<string>;
description?: string;
}
async function getChangedFiles(octokit: Octokit, owner: string, repo: string, prNumber: number): Promise<string[]> {
const { data: files } = await octokit.rest.pulls.listFiles({
owner,
repo,
pull_number: prNumber,
});
const filenames = files.map((file: any) => file.filename);
core.debug(`Changed files: ${filenames.join(', ')}`);
return filenames;
}
function parseConfigFile(filePath: string): Array<LabelConfig> {
const fileContent = fs.readFileSync(filePath, 'utf8');
let parsedData;
if (filePath.endsWith('.yml') || filePath.endsWith('.yaml')) {
parsedData = yaml.load(fileContent);
} else if (filePath.endsWith('.json')) {
parsedData = JSON.parse(fileContent);
} else {
throw new Error(`Unsupported file type: ${filePath}`);
}
if (typeof parsedData === 'object' && parsedData !== null) {
return Object.entries(parsedData).map(([label, patterns]) => {
if (!Array.isArray(patterns)) {
throw new Error(`Patterns for label "${label}" should be an array.`);
}
return { label, match: patterns as string[] };
});
} else {
throw new Error(`Parsed data from ${filePath} is not an object or is empty.`);
}
}
async function ensureLabelsExist(
octokit: any,
owner: string,
repo: string,
labels: Array<{ label: string; description?: string }>
) {
const tasks = labels.map(({ label, description }) =>
ensureLabelExists(octokit, owner, repo, label, description)
);
await Promise.all(tasks);
}
async function ensureLabelExists(octokit: any, owner: string, repo: string, label: string, description?: string) {
try {
await octokit.rest.issues.getLabel({ owner, repo, name: label });
core.debug(`Label "${label}" already exists.`);
} catch (error: any) {
if (error.status === 404) {
const randomColor = getRandomColor();
core.info(`Label "${label}" not found. Creating it with color #${randomColor}.`);
await octokit.rest.issues.createLabel({
owner,
repo,
name: label,
color: randomColor,
description: description || '',
});
core.info(`Label "${label}" created successfully.`);
} else {
core.warning(error);
}
}
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color.slice(1);
}
function getMatchedLabels<T extends LabelConfig>(content: Array<string>, labels: Array<T>):
Array<{ label: string; description?: string }> | undefined {
const matchedLabels: Array<{ label: string; description?: string }> = [];
labels.forEach(({ label, match, description }) => {
core.debug(`Checking label "${label}" with patterns: ${match.join(', ')}`);
if (match.some(pattern => content.some(item => minimatch(item, pattern)))) {
matchedLabels.push({ label, description });
}
});
return matchedLabels.length > 0 ? matchedLabels : undefined;
}
function resolvePath (path: string) {
return path.replace(/\$([A-Z_]+)/g, (_, name) => process.env[name] || '');
};
(async () => {
try {
const token = core.getInput('github-token') || process.env.GITHUB_TOKEN || '';
const octokit = github.getOctokit(token);
const debugMode = core.getBooleanInput('debug') || true;
const { owner: contextOwner, repo: contextRepo } = github.context.repo;
const owner = core.getInput('owner') || contextOwner;
const repo = core.getInput('repo') || contextRepo;
const actionNumber = core.getInput('number') || undefined;
const prConfigPath = resolvePath(core.getInput('pr-config') || '.github/pr.yml');
const issueConfigPath = resolvePath(core.getInput('issue-config') || '.github/issues.yml');
if (debugMode) {
core.debug(`PR Config Path: ${prConfigPath}`);
core.debug(`Issue Config Path: ${issueConfigPath}`);
}
const eventType = context.eventName;
const labelsToApply: string[] = [];
let targetNumber;
if (eventType === 'pull_request' && context.payload.pull_request) {
const prNumber = context.payload.pull_request.number;
targetNumber = prNumber;
if (!prConfigPath) {
core.setFailed('Missing "pr-config" input for pull request labeling.');
return;
}
const changedFiles = await getChangedFiles(octokit as unknown as Octokit, owner, repo, prNumber);
const fileLabelMapping = parseConfigFile(prConfigPath);
const matchedLabels = getMatchedLabels(changedFiles, fileLabelMapping);
if (matchedLabels) {
for (const { label, description } of matchedLabels) {
labelsToApply.push(label);
await ensureLabelsExist(octokit, owner, repo, [{label: label, description: description}]);
}
} else {
core.warning('No labels matched the file changes in this pull request.');
}
} else if (eventType === 'issues' && context.payload.issue) {
const issueNumber = context.payload.issue.number;
targetNumber = issueNumber;
if (!issueConfigPath) {
core.setFailed('Missing "issue-config" input for issue labeling.');
return;
}
const titleAndBody = [`${context.payload.issue.title}`, `${context.payload.issue.body || ''}`];
const issueLabelMapping = parseConfigFile(issueConfigPath);
const matchedLabels = getMatchedLabels(titleAndBody, issueLabelMapping);
if (matchedLabels) {
for (const { label, description } of matchedLabels) {
labelsToApply.push(label);
await ensureLabelExists(octokit, owner, repo, label, description);
}
} else {
core.warning('No labels matched the issue title or body.');
}
} else if (eventType == 'workflow_dispatch' && actionNumber != 'undefined') {
targetNumber = actionNumber as unknown as number;
if (context.payload.issue) {
if (!issueConfigPath) {
core.setFailed('Missing "issue-config" input for issue labeling.');
return;
}
const titleAndBody = [`${context.payload.issue.title}`, `${context.payload.issue.body || ''}`];
const issueLabelMapping = parseConfigFile(issueConfigPath);
const matchedLabels = getMatchedLabels(titleAndBody, issueLabelMapping);
if (matchedLabels) {
for (const { label, description } of matchedLabels) {
labelsToApply.push(label);
await ensureLabelExists(octokit, owner, repo, label, description);
}
} else {
core.warning('No labels matched the issue title or body.');
}
}
if (context.payload.pull_request) {
if (!prConfigPath) {
core.setFailed('Missing "pr-config" input for pull request labeling.');
return;
}
const changedFiles = await getChangedFiles(octokit as unknown as Octokit, owner, repo, targetNumber);
const fileLabelMapping = parseConfigFile(prConfigPath);
const matchedLabels = getMatchedLabels(changedFiles, fileLabelMapping);
if (matchedLabels) {
for (const { label, description } of matchedLabels) {
labelsToApply.push(label);
await ensureLabelsExist(octokit, owner, repo, [{label: label, description: description}]);
}
} else {
core.warning('No labels matched the file changes in this pull request.');
}
}
} else {
core.warning(`Event Type "${eventType}" is not supported.`);
}
if (targetNumber && labelsToApply.length > 0) {
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: targetNumber,
labels: labelsToApply,
});
core.info(`Issue Labels Applied: ${labelsToApply.join(', ')}`);
} else {
core.warning('No labels were applied.');
}
console.log(`
--------------------------------------------------------------
🎉 Success! Labels have been applied to Issue/PR.
✨ Thank you for using this action! – Vedansh
--------------------------------------------------------------
`);
} catch (error: any) {
core.error(`Error: ${error.message}`);
core.setFailed(`Failed to label PR based on file changes: \n${error.message}`);
}
})();