Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
282 lines (255 loc) · 9.91 KB
/
Copy pathindex.js
File metadata and controls
282 lines (255 loc) · 9.91 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
const core = require('@actions/core');
const { getInput, setFailed } = require('@actions/core');
const { getOctokit, context } = require('@actions/github');
const parser = require('conventional-commits-parser')
const githubApi = require('./githubapi');
const axios = require('axios');
const fs = require('fs');
async function validateSubscription() {
let repoPrivate;
const eventPath = process.env.GITHUB_EVENT_PATH;
if (eventPath && fs.existsSync(eventPath)) {
const payload = JSON.parse(fs.readFileSync(eventPath, "utf8"));
repoPrivate = payload?.repository?.private;
}
const upstream = 'ytanikin/pr-conventional-commits';
const action = process.env.GITHUB_ACTION_REPOSITORY;
const docsUrl = 'https://docs.stepsecurity.io/actions/stepsecurity-maintained-actions';
core.info('');
core.info('\u001b[1;36mStepSecurity Maintained Action\u001b[0m');
core.info(`Secure drop-in replacement for ${upstream}`);
if (repoPrivate === false) core.info('\u001b[32m✓ Free for public repositories\u001b[0m');
core.info(`\u001b[36mLearn more:\u001b[0m ${docsUrl}`);
core.info('');
if (repoPrivate === false) return;
const serverUrl = process.env.GITHUB_SERVER_URL || 'https://github.com';
const body = { action: action || '' };
if (serverUrl !== 'https://github.com') body.ghes_server = serverUrl;
try {
await axios.post(
`https://agent.api.stepsecurity.io/v1/github/${process.env.GITHUB_REPOSITORY}/actions/maintained-actions-subscription`,
body, { timeout: 3000 }
);
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 403) {
core.error(`\u001b[1;31mThis action requires a StepSecurity subscription for private repositories.\u001b[0m`);
core.error(`\u001b[31mLearn how to enable a subscription: ${docsUrl}\u001b[0m`);
process.exit(1);
}
core.info('Timeout or API not reachable. Continuing to next step.');
}
}
/**
* Main function to run the whole process.
*/
async function run() {
await validateSubscription();
const pr = context.payload.pull_request;
const titleRegex = getTitleRegex();
const commitDetail = await checkConventionalCommits();
await checkScope(commitDetail);
await checkTextMatches(titleRegex, pr.title); // validates against the whole title, including the leading commit type, e.g. `fix: `
await applyLabel(pr, commitDetail);
await applyScopeLabel(pr, commitDetail)
}
function parseConventionalCommit(pr) {
const titleAst = parser.sync(pr.title.trimStart(), {
headerPattern: /^(\w*)(?:\((.*?)\))?!?: (.*)$/,
breakingHeaderPattern: /^(\w*)(?:\((.*?)\))?!: (.*)$/
});
const cc = {
type: titleAst.type ? titleAst.type : '',
scope: titleAst.scope ? titleAst.scope : '',
breaking: titleAst.notes && titleAst.notes.some(note => note.title === 'BREAKING CHANGE'),
};
return cc;
}
/**
* Check the conventional commits of the task.
* Parse the title of the pull request and validate against the task type list.
* @returns {Promise<Object>} An object with details of the commit: type, scope and whether it's a breaking change.
*/
async function checkConventionalCommits() {
const taskTypeList = getTaskTypes();
if (taskTypeList === null) {
return;
}
const pr = context.payload.pull_request;
const cc = parseConventionalCommit(pr);
if (!cc.type || !taskTypeList.includes(cc.type)) {
setFailed(`Invalid or missing task type: '${cc.type}'. Must be one of: ${taskTypeList.join(', ')}`);
return;
}
return cc;
}
function getTaskTypes() {
const taskTypesInput = getInput('task_types');
if (!taskTypesInput) {
setFailed('Missing required input: task_types');
return null;
}
try {
const taskTypeList = JSON.parse(taskTypesInput);
if (!Array.isArray(taskTypeList)) {
throw new Error('Invalid format'); // Ensure the parsed result is an array
}
return taskTypeList;
} catch (err) {
setFailed('Invalid task_types input. Expecting a JSON array.');
return null;
}
}
/**
* Check the scope on the PR title.
*/
async function checkScope(commitDetail) {
if (!commitDetail) {
return;
}
const scopeTypes = getScopeTypes();
if (scopeTypes === null) {
return;
}
if (!scopeTypes.includes(commitDetail.scope)) {
setFailed(`Invalid or missing scope: '${commitDetail.scope}'. Must be one of: ${scopeTypes.join(', ')}`);
}
}
function getScopeTypes() {
const scopeTypesInput = getInput('scope_types');
if (!scopeTypesInput) {
return null;
}
try {
const scopeTypeList = JSON.parse(scopeTypesInput);
if (!Array.isArray(scopeTypeList)) {
throw new Error('Invalid format'); // Ensure the parsed result is an array
}
return scopeTypeList;
} catch (err) {
setFailed('Invalid scope_types input. Expecting a JSON array.');
return null;
}
}
// TODO Remove this function once `ticket_key_regex` is phased out
function getTitleRegex() {
const titleRegex = getInput('title_regex');
const deprecatedTitleRegex = getInput('ticket_key_regex');
if (deprecatedTitleRegex) {
console.warn('⚠️ DEPRECATION WARNING: "ticket_key_regex" parameter is deprecated. Please use "title_regex" instead.');
}
return titleRegex || deprecatedTitleRegex || null;
}
/**
* Validate text against the provided regex pattern.
* @param {string} regex - The regex pattern to validate against
* @param {string} text - The text to validate
*/
async function checkTextMatches(regex, text) {
if (regex && !text.match(new RegExp(regex))) {
setFailed(`The text is not compliant with the specified regex...\n 🢒 Actual text: "${text}"\n 🢒 Must match: "${regex}"`);
}
}
/**
* Apply labels to the pull request based on the details of the commit and any custom labels provided.
* @param {Object} pr The pull request object.
* @param {Object} commitDetail The object with details of the commit.
*/
async function applyLabel(pr, commitDetail) {
const addLabel = getInput('add_label');
if (addLabel !== undefined && addLabel.toLowerCase() === 'false') {
return;
}
const customLabelsInput = getInput('custom_labels');
const customLabels = parseCustomLabels(customLabelsInput);
if (customLabels === null) {
return;
}
await updateLabels(pr, commitDetail, customLabels);
}
function parseCustomLabels(customLabelsInput) {
if (!customLabelsInput) {
return {};
}
try {
const customLabels = JSON.parse(customLabelsInput);
// Validate that customLabels is an object and all its keys and values are strings
if (typeof customLabels !== 'object' || Array.isArray(customLabels) ||
Object.entries(customLabels).some(([k, v]) => typeof k !== 'string' || typeof v !== 'string')) {
setFailed('Invalid custom_labels input. Expecting a JSON object with string keys and values.');
return null;
}
return customLabels;
} catch (err) {
setFailed('Invalid custom_labels input. Unable to parse JSON.');
return null;
}
}
function extractConventionalCommitData(title) {
const titleAst = parser.sync(title.trimStart(), {
headerPattern: /^(\w*)(?:\(([\w$.\-/ ])\))?!?: (.*)$/,
breakingHeaderPattern: /^(\w*)(?:\(([\w$.\-/ ])\))?!: (.*)$/
});
const cc = {
type: titleAst.type ? titleAst.type : '',
scope: titleAst.scope ? titleAst.scope : '',
breaking: titleAst.notes && titleAst.notes.some(note => note.title === 'BREAKING CHANGE'),
};
return cc;
}
async function applyScopeLabel(pr, commitDetail) {
const addLabelEnabled = getInput('add_scope_label');
scopeName = commitDetail.scope;
if (addLabelEnabled !== undefined && addLabelEnabled.toLowerCase() === 'false' || scopeName === undefined || scopeName === "") {
return;
}
const octokit = getOctokit(getInput('token'));
const currentLabelsResult = await githubApi.getCurrentLabelsResult(octokit, pr);
const currentLabels = currentLabelsResult.data.map(label => label.name);
if (currentLabels.includes(scopeName)) {
return;
}
githubApi.createOrAddLabel(octokit, scopeName, pr)
}
/**
* Update labels on the pull request.
*/
async function updateLabels(pr, cc, customLabels) {
const token = getInput('token');
const octokit = getOctokit(token);
const currentLabelsResult = await githubApi.getCurrentLabels(octokit, pr);
const currentLabels = currentLabelsResult.data.map(label => label.name);
let taskTypesInput = getInput('task_types');
let taskTypeList = JSON.parse(taskTypesInput);
const managedLabels = taskTypeList.concat(['breaking change']);
// Include customLabels keys in managedLabels, if any
Object.values(customLabels).forEach(label => {
if (!managedLabels.includes(label)) {
managedLabels.push(label);
}
});
let newLabels = [customLabels[cc.type] ? customLabels[cc.type] : cc.type];
const breakingChangeLabel = 'breaking change';
if (cc.breaking && !newLabels.includes(breakingChangeLabel)) {
newLabels.push(breakingChangeLabel);
}
// Determine labels to remove and remove them
const labelsToRemove = currentLabels.filter(label => managedLabels.includes(label) && !newLabels.includes(label));
for (let label of labelsToRemove) {
await githubApi.removeLabel(octokit, pr, label)
}
// Ensure new labels exist with the desired color and add them
for (let label of newLabels) {
if (!currentLabels.includes(label)) {
await githubApi.createOrAddLabel(octokit, label, pr)
}
}
}
run().catch(err => setFailed(err.message));
module.exports = {
run,
checkConventionalCommits,
checkScope,
checkTextMatches,
applyLabel,
updateLabels
};