-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
195 lines (160 loc) · 5.51 KB
/
index.js
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
const core = require("@actions/core");
const github = require("@actions/github");
const exec = require("@actions/exec");
const { Octokit } = require("@octokit/rest");
const fs = require('fs');
const convertBytes = function(bytes) {
const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
if (bytes == 0) {
return "n/a"
}
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))
if (i == 0) {
return bytes + " " + sizes[i]
}
return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
}
const main = async () => {
try {
const inputs = {
token: core.getInput("token"),
target_folder: core.getInput("target_folder"),
thrashold_size: core.getInput("thrashold_size")
};
const {
payload: { pull_request: pullRequest, repository },
} = github.context;
if (!pullRequest) {
core.error("This action only works on pull_request events");
return;
}
const { number: issueNumber } = pullRequest;
const { full_name: repoFullName } = repository;
const [owner, repo] = repoFullName.split("/");
const octokit = new Octokit({
auth: inputs.token,
});
let ignoreArray = [];
let myOutput = '';
let myError = '';
const options = {};
options.listeners = {
stdout: (data) => {
myOutput += data.toString();
},
stderr: (data) => {
myError += data.toString();
}
};
/**
* Check if array assets file name contains inside .ignore-assets file or not.
* If its contains then remove those images from sourceArray and return new array.
*
* @param {Array} sourceArray Array of all assets files.
* @returns Array of files.
*/
function getAssetsIgnoreFiles(sourceArray) {
const file=`.assets-ignore`;
try {
ignoreArray = fs.readFileSync(file).toString().split("\n");
if (ignoreArray.length > 0) {
return sourceArray.filter (v => {
const fileName = v.split(" ").slice(-1).pop()
if (!fileName) return true;
return ignoreArray.indexOf(fileName) === -1;
})
}
} catch (e) {
// File not found exception.
}
return sourceArray;
}
await exec.exec(`find ${inputs.target_folder} -type f \( -name "*.jpeg" -o -name "*.png" -o -name "*.svg" -o -name "*.gif" -o -name "*.jpg" \) -size +${inputs.thrashold_size}k -exec ls -lh {} \;`, null, options);
const arrayOutput = getAssetsIgnoreFiles(myOutput.split("\n"));
const count = arrayOutput.length - 1;
const invalidFiles = [...arrayOutput];
const successBody = ` Woohooo :rocket: !!! Congratulations, your all assets are less than ${inputs.thrashold_size}Kb.`
const errorBody = `Oops :eyes: !!! You have ${count} assets with size more than ${inputs.thrashold_size}Kb. Please optimize them. If you unable to optimize these assets, you can use .assets-ignore file and add these assets in .assets-ignore file. For more details read readme`
const getTableDataString = (invalidFiles) => {
let filteredFiles = [];
for(let item of invalidFiles) {
const fileName = item.split(" ").slice(-1).pop();
const fileSize = item.split(" ")[4];
if(fileName && fileSize) filteredFiles.push([fileName, fileSize]);
}
let res = `### Invalid Files\n|File Name|File Size|\n|-----|:-----:|\n`;
for(let item of filteredFiles) {
res += `|${item[0]}|${item[1]}|\n`
}
return res;
};
/**
* Get all Ignored file data as github comment string format.
*
* @param {Array} ignoreArray array of files which is added in .assets-ignore file.
* @returns Promise of github comment string.
*/
const getAllIgnoredFileString = (ignoreArray) => {
return new Promise((resolve, reject) => {
let res = `### All .assets-ignored Files\n|File Name|File Size\n|-----|:-----:|\n`;
for(let index=0; index < ignoreArray.length; index++) {
const item = ignoreArray[index];
fs.stat(item, (err, fileStats) => {
if (err) {
res += `|${item}|None|\n`
} else {
const result = convertBytes(fileStats.size)
res += `|${item}|${result}|\n`
}
if (index === ignoreArray.length-1) {
resolve(res);
}
})
}
})
};
/**
* Publish .assets-ignore entries in github comment.
*
* @param {Array} ignoreArray array of files which is added in .assets-ignore file.
*/
const publishIgnoreAssetsTable = async (ignoreArray) => {
if (ignoreArray.length) {
const body = await getAllIgnoredFileString(ignoreArray);
return octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body,
});
}
}
if(count > 0) {
octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: errorBody,
});
octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: getTableDataString(invalidFiles),
});
await publishIgnoreAssetsTable(ignoreArray);
core.setFailed('Invalid size assets exists !!!');
}else {
octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: successBody,
});
await publishIgnoreAssetsTable(ignoreArray);
}
} catch (error) {
core.setFailed(error.message);
}
};
main();