-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
258 lines (231 loc) · 9.56 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
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
const core = require("@actions/core");
const axios = require("axios");
const { Octokit } = require("@octokit/rest");
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
const getReadmeFile = async(url, requestOptions) => {
try {
const readme = await octokit.request(url, requestOptions);
console.log('Get README.md successful.');
return readme;
} catch (e) {
console.error("Get README.md failed, with error: ", e.message);
core.setFailed("Failed: ", e.message);
throw new Error(e.message);
}
}
const getActivityData = async(url, username) => {
try {
const activityData = await octokit.request(url, { username });
console.log('Get activityData successful.');
return activityData;
} catch (e) {
console.error("Get activityData, with error: ", e.message);
core.setFailed("Failed: ", e.message);
throw new Error(e.message);
}
}
const updateReadme = async(url, requestOptions, repoImagsInfo, recentRepos) => {
try {
await octokit.request(url, requestOptions);
core.setOutput("repositories", Array.from(recentRepos), JSON.stringify(repoImagsInfo));
console.log('Update readme successful.');
} catch (e) {
console.error("Update readme failed with error: ", e.message);
core.setFailed("Failed: ", e.message);
throw new Error(e.message);
}
}
const chunkArray = (array, size) => {
let chunked = [];
let index = 0;
while (index < array.length) {
chunked.push(array.slice(index, size + index));
index += size;
}
return chunked;
}
const getTrafficData = async(apiPath, reponame, retryCount = 5, interval = 30) => {
console.log(`Get traffic data. retryCount: ${retryCount}, interval: ${interval}`);
if (!Number(retryCount)) {
retryCount = 5;
}
if (!Number(interval)) {
interval = 30;
}
let tryCount = 0;
const url = `${apiPath}/${reponame}?aggregate=true`;
try {
const response = await axios.get(url);
return response.data.data;
} catch {
return new Promise((resolve, reject) => {
const timer = setInterval(async() => {
try {
const response = await axios.get(url);
console.log(`${new Date()}: the ${tryCount + 1} times retry request ${url} successfully.`);
if (response && response.data && response.data.isSuccess) {
clearInterval(timer);
resolve(response.data.data);
}
} catch (error) {
console.error(`${new Date()}: the ${tryCount + 1} times retry request ${url} failed with error: ${error.message}`);
} finally {
++tryCount;
if (tryCount === retryCount) {
clearInterval(timer);
reject(new Error('No response from server, please check your server health.'));
}
}
}, interval * 1000);
});
}
}
(async () => {
try {
const apiPath = core.getInput('apiPath');
const retryCount = core.getInput('retryCount');
const interval = core.getInput('interval');
const ref = core.getInput('ref');
const repoCount = parseInt(core.getInput('repoCount'));
const repoPerRow = parseInt(core.getInput('reposPerRow'));
const imageSize = parseInt(core.getInput('imageSize'));
const path = core.getInput('path');
const excludeActivity = core.getInput('excludeActivity');
const repos = core.getInput('repos');
const customReadmeFile = core.getInput("customReadmeFile");
const header = core.getInput('header');
const subhead = core.getInput('subhead');
const footer = core.getInput('footer');
const showTrafficData = core.getInput('showTrafficData');
const trafficDataPosition = core.getInput('trafficDataPosition');
const includeReposOrExcludeRepos = core.getInput('includeReposOrExcludeRepos');
const isIncludeRepos = includeReposOrExcludeRepos === 'include';
const username = process.env.GITHUB_REPOSITORY.split("/")[0];
const repo = process.env.GITHUB_REPOSITORY.split("/")[1];
console.log(`Job begin at: ${new Date()}`);
let viewsData = {};
let clonesData = {};
try {
const response = await getTrafficData(apiPath, repo, retryCount, interval);
viewsData = response.viewsData[0];
clonesData = response.clonesData[0];
} catch (error) {
console.error(error.message);
}
console.log(`Get traffic data sucessful, viewsData: ${JSON.stringify(viewsData)}, clonesData: ${JSON.stringify(clonesData)}`);
console.log('Get README.md.');
const readmeFiles = await getReadmeFile('GET /repos/{owner}/{repo}/contents/{path}', {
owner: username,
repo,
path,
});
const sha = readmeFiles.data.sha;
let recentReposHaveImage = [];
let recentRepos = new Set();
console.log(`Get recentRepos info, repoCount: ${repoCount}`);
/** GitHub Activity pagination is limited at 100 records x 3 pages */
for (let i = 0; recentRepos.size < repoCount && i < 3; i++) {
const activityData = await getActivityData(`GET /users/{username}/events/public?per_page=100&page=${i}`, username);
const { data = {} } = activityData;
for (const value of data) {
let activityRepo = value.repo.name;
if (value.type === "ForkEvent") {
activityRepo = value.payload.forkee.full_name;
}
if (!JSON.parse(excludeActivity).includes(value.type)) {
if(isIncludeRepos) {
if (JSON.parse(repos).includes(activityRepo)) {
console.log(`RecentRepos add ${activityRepo}`);
recentRepos.add(activityRepo);
}
} else {
if (!JSON.parse(repos).includes(activityRepo)) {
console.log(`RecentRepos add ${activityRepo}`);
recentRepos.add(activityRepo);
}
}
}
if (recentRepos.size >= repoCount) {
break;
}
}
}
const repoImagsInfo = [];
if (repoCount > 0) {
console.log('Get repo display image.');
}
for await(const repo of recentRepos) {
await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {
owner: repo.split("/")[0],
repo: repo.split("/")[1],
path: 'DISPLAY.jpg',
}).then((response) => {
if (response.data.name === 'DISPLAY.jpg') {
console.log('Get repo display image sucessful.');
recentReposHaveImage.push(true);
} else {
repoImagsInfo.push(`Waring: can't find 'DISPLAY.jpg' in ${repo}. Please upload 'DISPLAY.jpg'.`)
recentReposHaveImage.push(false);
}
}).catch(e => {
console.log('Get repo display image failed with error: ', e.message);
repoImagsInfo.push(`Waring: can't find display.jpg in ${repo}. Please upload 'DISPLAY.jpg'.`)
recentReposHaveImage.push(false);
})
}
const generateRepoTable = () => {
let tableContent = chunkArray(Array.from(recentRepos), repoPerRow).map((value, row) => {
return `|${value.map(value => `[${value}](https://github.com/${value}) |`)}
|${value.map(() => ` :-: |`)}
|${value.map((value, col) => `<a href="https://github.com/${value}"><img src="https://github.com/${recentReposHaveImage[row * repoPerRow + col] ? value : `${username}/${repo}`}/raw/${ref}/DISPLAY.jpg" alt="${value}" title="${value}" width="${imageSize}" height="${imageSize}"></a> |`
)}\n\n`
}).toString().replace(/,/g, "");
if (repoCount > 0) {
tableContent = `---\n${tableContent}\n---\n`;
}
return tableContent;
}
const startDate = new Date(viewsData.startDate) > new Date(clonesData.startDate) ? viewsData.startDate : clonesData.startDate;
const endDate = new Date(viewsData.endDate) > new Date(clonesData.endDate) ? viewsData.endDate : clonesData.endDate;
const readmeContentData = customReadmeFile.replace(/\${\w{0,}}/g, (match) => {
switch (match) {
case "${repoTable}":
return generateRepoTable();
case "${header}":
return header;
case "${subhead}":
if (showTrafficData && trafficDataPosition === 'subhead') {
return subhead.replace(/'{repo}'/g, repo)
.replace(/'{startDate}'/g, startDate).replace(/'{endDate}'/g, endDate)
.replace(/'{viewsData}'/g, `{ count: ${viewsData.countTotal}, uniques: ${viewsData.uniquesTotal} }`)
.replace(/'{clonesData}'/g, `{ count: ${clonesData.countTotal}, uniques: ${clonesData.uniquesTotal} }`);
}
return subhead;
case "${footer}":
if (showTrafficData && trafficDataPosition === 'footer') {
return footer.replace(/'{repo}'/g, repo)
.replace(/'{startDate}'/g, startDate).replace(/'{endDate}'/g, endDate)
.replace(/'{viewsData}'/g, `{ count: ${viewsData.countTotal}, uniques: ${viewsData.uniquesTotal} }`)
.replace(/'{clonesData}'/g, `{ count: ${clonesData.countTotal}, uniques: ${clonesData.uniquesTotal} }`);
}
return footer;
default:
console.error(`${match} is not recognized`);
return '';
}
});
console.log('readmeContentData: ', readmeContentData);
await updateReadme('PUT /repos/{owner}/{repo}/contents/{path}', {
owner: username,
repo,
path,
message: '(Automated) Update README.md',
content: Buffer.from(readmeContentData, "utf8").toString('base64'),
sha: sha,
}, repoImagsInfo, recentRepos);
console.log(`Job complete at: ${new Date()}`);
} catch (e) {
console.error("Error occrence with error: ", e.message)
core.setFailed("Failed: ", e.message)
}
})()