generated from actions/javascript-action
-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.ts
248 lines (210 loc) · 7.41 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
import * as core from '@actions/core';
import * as github from '@actions/github';
import {execFile} from 'child_process';
import * as micromatch from 'micromatch';
import {promisify} from 'util';
const execFileP = promisify(execFile);
const octokit = github.getOctokit(core.getInput('token'));
const context = github.context;
const {repo} = context;
const event_type = context.eventName;
const lfsFileContentStart = 'version https://git-lfs.github.com/spec/v1';
const lfsFileContentStartInBase64 = Buffer.from(
// Every 3 characters, we get a fixed 4 char base64 string
// Shorting in the case that last character in base64 encoded string
// could vary depending on next file contents
lfsFileContentStart.slice(0, Math.floor(lfsFileContentStart.length / 3) * 3)
).toString('base64');
async function run() {
const fsl = getFileSizeLimitBytes();
core.info(`Default configured filesizelimit is set to ${fsl} bytes...`);
core.info(
`Name of Repository is ${repo.repo} and the owner is ${repo.owner}`
);
core.info(`Triggered event is ${event_type}`);
const labelName = core.getInput('labelName');
const labelColor = core.getInput('labelColor');
await getOrCreateLfsWarningLabel(labelName, labelColor);
if (event_type === 'pull_request') {
const pullRequestNumber = context.payload.pull_request?.number;
if (pullRequestNumber === undefined) {
throw new Error('Could not get PR number');
}
core.info(`The PR number is: ${pullRequestNumber}`);
const prFilesWithBlobSize = await getPrFilesWithBlobSize(pullRequestNumber);
core.debug(`prFilesWithBlobSize: ${JSON.stringify(prFilesWithBlobSize)}`);
const largeFiles: string[] = [];
const accidentallyCheckedInLsfFiles: string[] = [];
for (const file of prFilesWithBlobSize) {
const {fileblobsize, filename} = file;
if (fileblobsize !== null && fileblobsize > Number(fsl)) {
largeFiles.push(filename);
} else {
// look for files below threshold that should be stored in LFS but are not
const shouldBeStoredInLFS = (
await execFileP('git', ['check-attr', 'filter', filename])
).stdout.includes('filter: lfs');
if (shouldBeStoredInLFS) {
let isStoredInLFS = false;
if (file.patch) {
isStoredInLFS = Boolean(file.patch.includes(lfsFileContentStart));
} else if (file.filecontents) {
// For PDF files, seems GitHub doesn't have the .patch property set
// in the API response. Reading file contents instead
// https://github.com/ActionsDesk/lfs-warning/issues/135
isStoredInLFS = file.filecontents.startsWith(
lfsFileContentStartInBase64
);
}
if (!isStoredInLFS) {
accidentallyCheckedInLsfFiles.push(filename);
}
}
}
}
const lsfFiles = largeFiles.concat(accidentallyCheckedInLsfFiles);
const issueBaseProps = {
...repo,
issue_number: pullRequestNumber,
};
if (lsfFiles.length > 0) {
core.info('Detected file(s) that should be in LFS: ');
core.info(lsfFiles.join('\n'));
const body = getCommentBody(
largeFiles,
accidentallyCheckedInLsfFiles,
fsl
);
await Promise.all([
octokit.rest.issues.addLabels({
...issueBaseProps,
labels: [labelName],
}),
octokit.rest.issues.createComment({
...issueBaseProps,
body,
}),
]);
core.setOutput('lfsFiles', lsfFiles);
core.setFailed(
'Large file(s) detected! Setting PR status to failed. Consider using git-lfs to track the LFS file(s)'
);
} else {
core.info('No large file(s) detected...');
const {data: labels} = await octokit.rest.issues.listLabelsOnIssue({
...issueBaseProps,
});
if (labels.map(l => l.name).includes(labelName)) {
await octokit.rest.issues.removeLabel({
...issueBaseProps,
name: labelName,
});
core.info(`label ${labelName} removed`);
}
}
} else {
core.info('No Pull Request detected. Skipping LFS warning check');
}
}
run().catch(error => {
core.setFailed(error.message);
});
function getFileSizeLimitBytes() {
const fsl = core.getInput('filesizelimit');
const lastTwoChars = fsl.slice(-2).toLowerCase();
if (lastTwoChars === 'mb') {
return Number(fsl.slice(0, -2)) * 1024 * 1024;
} else if (lastTwoChars === 'gb') {
return Number(fsl.slice(0, -2)) * 1024 * 1024 * 1024;
} else if (lastTwoChars[1] === 'b') {
return fsl.slice(0, -1);
} else {
return fsl;
}
}
async function getOrCreateLfsWarningLabel(
labelName: string,
labelColor: string
) {
try {
await octokit.rest.issues.getLabel({
...repo,
name: labelName,
});
} catch (error) {
if (error instanceof Error) {
if (error.message === 'Not Found') {
await octokit.rest.issues.createLabel({
...repo,
name: labelName,
color: labelColor,
description:
'Warning Label for use when LFS is detected in the commits of a Pull Request',
});
core.info('No lfs warning label detected. Creating new label ...');
core.info('LFS warning label created');
} else {
core.error(`getLabel error: ${error.message}`);
}
}
}
}
async function getPrFilesWithBlobSize(pullRequestNumber: number) {
const {data: dataWithRemoved} = await octokit.rest.pulls.listFiles({
...repo,
pull_number: pullRequestNumber,
});
const data = dataWithRemoved.filter(({status}) => status !== 'removed');
const exclusionPatterns = core.getMultilineInput('exclusionPatterns');
const files =
exclusionPatterns.length > 0
? data.filter(({filename}) => {
const isExcluded = micromatch.isMatch(filename, exclusionPatterns);
if (isExcluded) {
core.info(`${filename} has been excluded from LFS warning`);
}
return !isExcluded;
})
: data;
const prFilesWithBlobSize = await Promise.all(
files
// Cannot get blobs for files without sha (e.g. happens when only changing a permission bit on the file)
.filter(file => file.sha != null)
.map(async file => {
const {filename, sha, patch} = file;
const {data: blob} = await octokit.rest.git.getBlob({
...repo,
file_sha: sha,
});
return {
filename,
filesha: sha,
fileblobsize: blob.size,
filecontents: blob.content,
patch,
};
})
);
return prFilesWithBlobSize;
}
function getCommentBody(
largeFiles: string[],
accidentallyCheckedInLsfFiles: string[],
fsl: string | number
) {
const largeFilesBody = `The following file(s) exceeds the file size limit: ${fsl} bytes, as set in the .yml configuration files:
${largeFiles.join(', ')}
Consider using git-lfs to manage large files.
`;
const accidentallyCheckedInLsfFilesBody = `The following file(s) are tracked in LFS and were likely accidentally checked in:
${accidentallyCheckedInLsfFiles.join(', ')}
`;
const body = `## :warning: Possible file(s) that should be tracked in LFS detected :warning:
${largeFiles.length > 0 ? largeFilesBody : ''}
${
accidentallyCheckedInLsfFiles.length > 0
? accidentallyCheckedInLsfFilesBody
: ''
}`;
return body;
}