-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
212 lines (181 loc) · 6.61 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* External dependencies
*/
const { getOctokit, context } = require( '@actions/github' );
const { setFailed, getInput } = require( '@actions/core' );
const sizeLimit = require( 'size-limit' );
const filePlugin = require( '@size-limit/file' );
const fs = require('fs/promises')
import prettyBytes from 'pretty-bytes';
const HEADING = '# WordPress Dependencies Report\n\n';
function computePercentageDiff(oldSize, newSize) {
if (oldSize === 0) {
return "+100% 🔼";
}
const value = ((newSize - oldSize) / oldSize) * 100;
const formatted =
(Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100;
if (value > 0) {
return `+${formatted}% 🔼`;
}
if (value === 0) {
return `${formatted}%`;
}
return `${formatted}% ⬇️`;
}
function computeSizeDiff(oldSize, newSize) {
return prettyBytes(newSize - oldSize, {signed: true}) +
" ( "+computePercentageDiff(oldSize, newSize) + " )";
}
async function fetchPreviousComment(
octokit,
repo,
pr
) {
const commentList = await octokit.paginate(
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
{
owner: repo.owner.login,
repo: repo.name,
// eslint-disable-next-line camelcase
issue_number: pr.number
}
);
const sizeLimitComment = commentList.find(comment =>
comment.body.startsWith(HEADING)
);
return !sizeLimitComment ? null : sizeLimitComment;
}
function emitErrorNoPermission(prefix, error) {
console.log(prefix+" This can happen on PR's originating from a fork without write permissions.");
console.log(error.message);
console.log(error.stack);
}
async function postOrEditComment(octokit, repo, pr, content, onlyUpdate = false) {
const previousComment = await fetchPreviousComment(octokit, repo, pr);
if (!previousComment) {
if ( onlyUpdate ) {
return;
}
try {
await octokit.rest.issues.createComment({
owner: repo.owner.login,
repo: repo.name,
issue_number: pr.number,
body: HEADING + content
});
} catch (error) {
emitErrorNoPermission("Error creating comment.", error);
}
} else {
try {
await octokit.rest.issues.updateComment({
owner: repo.owner.login,
repo: repo.name,
comment_id: previousComment.id,
body: HEADING + content
});
} catch (error) {
emitErrorNoPermission("Error updating comment.", error);
}
}
}
async function readJSON(filePath, defaultValue) {
try {
const content = await fs.readFile(filePath, 'utf8')
return JSON.parse(content);
} catch(e) {
return defaultValue;
}
}
async function run() {
const token = getInput( 'github-token', { required: true } );
const octokit = getOctokit( token );
const payload = context.payload;
const commit = payload.pull_request.head.sha;
const oldAssetsFolder = getInput( 'old-assets-folder', {
required: true,
} );
const oldAssetsBranch = getInput( 'old-assets-branch', {
required: true,
} );
const newAssetsFolder = getInput( 'new-assets-folder', {
required: true,
} );
const oldAssets = await readJSON(oldAssetsFolder + '/assets.json', {});
const newAssets = await readJSON( newAssetsFolder + '/assets.json', false );
if ( ! newAssets ) {
return;
}
let reportContent = '';
for (const [ asset, { dependencies } ] of Object.entries(newAssets)) {
const oldDependencies = oldAssets[asset] ? oldAssets[ asset ].dependencies : [];
const added = dependencies.filter(
( dependency ) =>
! oldDependencies.includes( dependency )
);
const removed = oldDependencies.filter(
( dependency ) => ! dependencies.includes( dependency )
);
const addedDeps = added.length
? '`' + added.join('`, `') + '`'
: '';
const removedDeps = removed.length
? '`' + removed.join('`, `') + '`'
: '';
const sizesPromises = [
sizeLimit([ filePlugin ], {
"checks": [{
"files": [newAssetsFolder+"/"+asset]
}]
})
];
if (oldAssets[asset]) {
sizesPromises.push(
sizeLimit([ filePlugin ], {
"checks": [{
"files": [oldAssetsFolder+"/"+asset]
}]
})
)
} else {
sizesPromises.push(Promise.resolve( [ {size: 0} ] ));
}
const sizes = await Promise.all(sizesPromises);
const sizeDiff = computeSizeDiff( sizes[1][0].size, sizes[0][0].size );
const totalSize = prettyBytes(sizes[0][0].size);
if (sizes[0][0].size === sizes[1][0].size || 0 === addedDeps.length || 0 === removedDeps.length ) {
// If there are no changes, don't document the line.
continue;
}
reportContent +=
`| \`${asset}\` | ${addedDeps} | ${removedDeps} | ${totalSize} | ${sizeDiff} |` +
'\n';
}
let onlyUpdate = false;
let reportTable = '| Script Handle | Added Dependencies | Removed Dependencies | Total Size | Size Diff |' +
'\n' +
'| ------------- | ------- | ------- | ------- | ------- | ' +
'\n' +
reportContent;
if (reportContent.length === 0) {
// If there were changes before (aka a comment was posted before), we update it to reflect that there
// were no changes detected anymore, so the edit history isn't lost.
reportTable = 'No changes detected in the current commit. But comment was left so it is possible to check for the edit history.';
// We only publish this comment IF there is an update. We never create a comment with this content.
onlyUpdate = true;
}
await postOrEditComment(octokit, payload.repository, payload.pull_request,
'The `github-action-wordpress-dependencies-report` action has detected some script changes between the commit ' + commit + ' and ' + oldAssetsBranch +
'. Please review and confirm the following are correct before merging.' +
'\n\n' +
reportTable +
'\n\n' +
'__This comment was automatically generated by the `github-action-wordpress-dependencies-report` action.__',
onlyUpdate
);
}
run().catch(function(error) {
console.log(error.stack);
setFailed(error.message);
});