-
Notifications
You must be signed in to change notification settings - Fork 1
/
action.js
82 lines (73 loc) · 2.49 KB
/
action.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
const core = require('@actions/core');
const github = require('@actions/github');
const { Buffer } = require('buffer');
function run() {
const repoToken = core.getInput('repoToken');
const octokit = github.getOctokit(repoToken);
const config = {
owner: 'hacker0limbo',
repo: 'my-blog',
};
octokit.rest.issues
.listForRepo({
...config,
})
.then((res) => {
// { 2019: [{ title: xxx, url: xxx }, {...}], 2020: [...] }
const issuesByYear = res.data.reduce((result, issue) => {
const { created_at, title, html_url: url } = issue;
const year = created_at.slice(0, 4);
if (result.hasOwnProperty(year)) {
result[year].push({ title, url });
} else {
result[year] = [{ title, url }];
}
return result;
}, {});
const content = Object.entries(issuesByYear).reduce((result, [year, info]) => {
const titlesByYear = info.reduce((r, { title, url }) => r + `- [${title}](${url})\r\n`, '');
result += `## ${year}\r\n${titlesByYear}`;
return result;
}, '# 个人博客\r\n');
const filePath = { path: 'README.md' };
octokit.rest.repos
.getContent({
...config,
...filePath,
})
.then((res) => {
// https://swizec.com/blog/using-javascript-to-commit-to-github-codewithswiz-7/
// need to get sha before you update a file
const { sha } = res.data;
octokit.rest.repos
.createOrUpdateFileContents({
...config,
path: 'README.md',
message: 'feat: update readme through github action',
content: Buffer.from(content).toString('base64'),
sha,
})
.then((res) => {
core.info(
`Successfully update and commit README.md, commit id: ${res.data.commit.sha}`
);
})
.catch((error) => {
core.setFailed(
`Failed to update README.md with a status of ${error.status}, error: ${error.response.data.message}`
);
});
})
.catch((error) => {
core.setFailed(
`Failed to get file sha with a status of ${error.status}, error: ${error.response.data.message}`
);
});
})
.catch((error) => {
core.setFailed(
`Failed to fetch issues with a status of ${error.status}, error: ${error.response.data.message}`
);
});
}
run();