-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
393 lines (375 loc) · 17 KB
/
Copy pathindex.js
File metadata and controls
393 lines (375 loc) · 17 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
const core = require("@actions/core");
const github = require("@actions/github");
const resolve = require('path').resolve;
const fs = require('fs')
let erroredCheck2 = false;
async function run() {
try {
const token = core.getInput("repo-token");
const octokit = github.getOctokit(token);
let sha
let isPull = false
if(typeof github.context.payload.pull_request != 'undefined'){
isPull = true
sha = github.context.payload.pull_request.head.sha
}else{
sha = github.context.sha
}
/* Create two seperate checks in Github */
const check1 = await octokit.rest.checks.create({
...github.context.repo,
head_sha: sha,
status: 'in_progress',
started_at: new Date().toISOString(),
name: 'Parsing JSON'
})
const check2 = await octokit.rest.checks.create({
...github.context.repo,
head_sha: sha,
status: 'queued',
started_at: new Date().toISOString(),
name: 'File checks'
})
const annotations1 = [];
const annotations2 = [];
/* Get changed files */
let changed
if(isPull){
changed = await octokit.rest.pulls.listFiles({
...github.context.repo,
pull_number: github.context.payload.pull_request.number,
})
} else {
changed = getAllFiles('.')
}
/* Compile list of items that need to be checked later + parse all JSON */
const items = []
let size
if(isPull)
size = changed.data.length
else
size = changed.length
for(let i = 0; i < size; i++){
let file
if(isPull)
file = changed.data[i];
else
file = changed[i];
if(isPull && file.filename.endsWith('.json') && file.status != 'deleted' || !isPull && file.endsWith('.json')){
let path
if(isPull)
path = file.filename
else
path = file
let string = fs.readFileSync(resolve(path))
string = string.toString();
try{
JSON.parse(string)
if(isPull && file.filename.includes('items/')){
items.push(file.filename)
}else if(!isPull && file.includes('items/')){
items.push(file)
}
}catch(err){
/* If parsing fails find line of error and set annotation */
const num = parseInt(err.message.split(' ')[err.message.split(' ').length - 1]);
let line = undefined;
if(typeof num == 'number'){
line = getlineNumberofChar(string, num)
}
core.error('Parsing JSON failed for ' + path);
annotations1.push({
title: 'Parsing JSON failed for ' + path,
message: err.message,
annotation_level: 'failure',
path: path,
start_line: line,
end_line: line
})
}
}
}
/* Update first check to completed and depeding if we have annotations failure or succes + start second check */
await octokit.rest.checks.update({
...github.context.repo,
check_run_id: check1.data.id,
commit_id: sha,
conclusion: (annotations1.length > 0 ? 'failure' : 'success'),
status: 'completed',
output: {
title: "Parsing JSON results",
summary: "The results after parsing all of the changed JSON files.",
annotations: annotations1.slice(0, 50)
}
})
await octokit.rest.checks.update({
...github.context.repo,
check_run_id: check2.data.id,
commit_id: sha,
status: 'in_progress',
})
/* Start item checks */
for(const i in items){
const item = items[i];
const file = require(resolve(item))
/* Check if some fields exist, these things will fail the check. */
if(typeof file.internalname == 'undefined'){
core.error(item + ' does not have mandatory field internalname.')
annotations2.push({
title: item + ' does not have mandatory field internalname.',
message: 'The field internalname is required and this file doesn\'t have it.',
annotation_level: 'failure',
path: item,
start_line: 1,
end_line: 1
})
erroredCheck2 = true;
}
if(typeof file.displayname == 'undefined'){
core.error(item + ' does not have mandatory field displayname.')
annotations2.push({
title: item + ' does not have mandatory field displayname.',
message: 'The field displayname is required and this file doesn\'t have it.',
annotation_level: 'failure',
path: item,
start_line: 1,
end_line: 1
})
erroredCheck2 = true;
}
if(typeof file.itemid == 'undefined'){
core.error(item + ' does not have mandatory field itemid.')
annotations2.push({
title: item + ' does not have mandatory field itemid.',
message: 'The field itemid is required and this file doesn\'t have it.',
annotation_level: 'failure',
path: item,
start_line: 1,
end_line: 1
})
erroredCheck2 = true;
}
/* Check if lore and nbt tag lore is the same + check that nbt tag doesn't include uuid or timestamp, these things will not cause
a failure but will simpely give a warning and an anotation, workflow will still succeed. */
let display = file.nbttag.split('display:{Lore:[')[1]
if (typeof display != 'undefined') {
display = display.split('],')[0]
let lines = display.split(/",[0-9]+:"/g)
lines[0] = lines[0].substring(3)
lines[lines.length -1] = lines[lines.length -1].substring(0, lines[lines.length -1].length-1)
same = true;
let line;
for(const l in lines){
lines[l] = lines[l].replace(/\\/g, '')
if(lines[l] != file.lore[l]){
same = false;
line = l;
break;
}
}
if(!same){
core.warning('The lore of the nbt tag and the lore in the array is not the same, please fix this for item ' + item + ' at line ' +
line + '\nNBT: ' + lines[line] + '\nLore: ' + file.lore[line])
annotations2.push({
title: 'The lore in the nbt tag and lore of ' + item + ' is not the same.',
message: 'The lore of the nbt tag and the lore in the array is not the same, please fix this for item ' + item + ' at line ' +
line + '\nNBT: ' + lines[line] + '\nLore: ' + file.lore[line],
annotation_level: 'warning',
path: item,
start_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"'),
end_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"')
})
}
if(file.nbttag.includes("uuid:\"")){
core.warning('The nbt tag for item ' + item + ' contains a uuid, this is not allowed.')
annotations2.push({
title: 'The nbt tag for item ' + item + ' contains a uuid.',
message: 'The nbt tag for item ' + item + ' contains a uuid, this is not allowed.',
annotation_level: 'warning',
path: item,
start_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"'),
end_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"')
})
}
if(file.nbttag.includes("timestamp:\"")){
core.warning('The nbt tag for item ' + item + ' contains a timestamp, this is not allowed.')
annotations2.push({
title: 'The nbt tag for item ' + item + ' contains a timestamp',
message: 'The nbt tag for item ' + item + ' contains a timestamp, this is not allowed.',
annotation_level: 'warning',
path: item,
start_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"'),
end_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"')
})
}
} else {
core.warning('The nbt tag for item ' + item + ' does not contain lore, please add this.')
annotations2.push({
title: 'The nbt tag for item ' + item + ' does not contain lore.',
message: 'The nbt tag for item ' + item + ' does not contain lore, please add this.',
annotation_level: 'warning',
path: item,
start_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"'),
end_line: getWordLine(fs.readFileSync(item).toString(), '"nbttag"')
})
}
function checkItem(name, property) {
if (name === "SKYBLOCK_COIN") return;
if (fs.existsSync(`items/${name}.json`)) return;
const message = `Item reference ${name} in ${item} is unknown, please check this.`;
const line = getWordLine(
fs.readFileSync(item).toString(),
typeof property != 'undefined' ? `"${property}": "${name}` : `"${name}"`
);
core.warning(message);
annotations2.push({
title: `Unknown item reference in ${item}`,
message,
annotation_level: 'warning',
path: item,
start_line: line,
end_line: line
});
}
function checkIngredient(ingredient, property) {
checkItem(ingredient.split(":")[0], property);
}
function checkCraftingRecipe(recipe, property) {
for (const x of [...Array(3).keys()].map(i => String.fromCharCode('A'.charCodeAt(0) + i))) {
for (const y of [...Array(3).keys()].map(i => i + 1)) {
const slot = x + y;
if (typeof recipe[slot] == 'undefined') {
const message = `The crafting recipe for item ${item} is missing ingredient slot ${slot}, please add this.`;
const line = getWordLine(fs.readFileSync(item).toString(), `"${property}":`);
core.warning(message);
annotations2.push({
title: `Crafting recipe for item ${item} is missing ingredients.`,
message,
annotation_level: 'failure',
path: item,
start_line: line,
end_line: line
});
erroredCheck2 = true;
} else {
if (recipe[slot] === "") continue;
checkIngredient(recipe[slot], slot);
}
}
if (typeof recipe.overrideOutputId != 'undefined') checkItem(recipe.overrideOutputId);
}
}
if (typeof file.recipe != 'undefined') {
checkCraftingRecipe(file.recipe, "recipe");
}
if (typeof file.recipes != 'undefined') {
for (const recipe of file.recipes) {
switch (recipe.type) {
case "crafting":
checkCraftingRecipe(recipe, "recipes");
break;
case "forge":
for (const ingredient of recipe.inputs) {
checkIngredient(ingredient);
}
if (typeof recipe.overrideOutputId != 'undefined') checkItem(recipe.overrideOutputId);
break;
case "trade":
checkIngredient(recipe.result, "result");
checkIngredient(recipe.cost, "cost");
break;
case "drops":
for (const drop of recipe.drops) {
if (typeof drop == 'object') {
checkIngredient(drop.id, "id");
} else {
checkIngredient(drop);
}
}
break;
case "npc-shop":
for (const ingredient of recipe.cost) {
checkIngredient(ingredient);
}
checkIngredient(recipe.result, "result");
break;
case "katgrade":
checkIngredient(recipe.output, "output")
checkIngredient(recipe.input, "input");
if (typeof recipe.items != 'undefined') {
for (const ingredient of recipe.items) {
checkIngredient(ingredient);
}
}
break;
}
}
}
}
/* Update final check to be succes if no warnings or errors, neutral if warnings and failure if errors */
await octokit.rest.checks.update({
...github.context.repo,
check_run_id: check2.data.id,
commit_id: sha,
conclusion: (erroredCheck2 ? 'failure' : (annotations2 > 0 ? 'neutral' : 'success')),
status: 'completed',
output: {
title: "File checks conclusions",
summary: "The results after checking all files for mistakes.",
annotations: annotations2.slice(0, 50)
}
})
/* Create a comment if any warnings or errors have been detected */
if(isPull && (annotations1.length > 0 || annotations2.length > 0)) {
await octokit.rest.issues.createComment({
...github.context.repo,
issue_number: github.context.payload.pull_request.number,
body: `I've detected some problems you might want to take a look at, you can see them as annotations in the files tab.`
})
}
/* Fail action if there were any errors */
if(annotations1.length > 0 || erroredCheck2){
core.setFailed('This action has failed, I have left some annotations in the files tab of the pull request.')
}
} catch (err) {
console.error(err)
core.setFailed(err);
}
}
function getlineNumberofChar(data, index) {
const line = data.split('\n');
let total_length = 0;
for (const i in line) {
total_length += line[i].length + 1;
if (total_length >= index)
return parseInt(i) + 1;
}
return line.length - 1;
}
function getWordLine(input, word){
const line = input.split('\n');
for (let i in line) {
if(line[i].includes(word))
return parseInt(i) + 1;
}
return 1;
}
function getAllFiles(path) {
const allFiles = fs.readdirSync(path, { withFileTypes: true });
const files = allFiles.filter(file => file.name.endsWith('json'));
const dirs = allFiles.filter(file => file.isDirectory());
const names = [];
for(const file in files) {
names.push(`${path}/${files[file].name}`);
}
for(const dir of dirs) {
const components = getAllFiles(`${path}/${dir.name}`);
for(const value in components) {
names.push(components[value]);
}
}
for (const i in names)
names[i] = names[i].replace('./', '');
return names;
}
run()