forked from onivim/oni2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-changelog.js
189 lines (156 loc) · 5.22 KB
/
generate-changelog.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
/**
* Usage:
*
* node scripts/generate-changelog.js [--token <token>] <path>
*
* where <token> is a GitHub authentication token and <path> is the path to
* the changelog file. Typically assets/changelog.xml.
*
* If the changelog file already exists, only commits after the last commit
* in the file will be retrieved and added. Existing commits will not be
* updated.
*
* Note that if the changelog does *not* exist, this script may go over the
* GitHub API rate limit. To fix this, add a dummy commit in the file with
* a commit you would like to start from.
*/
const childProcess = require("child_process")
const initialLog = "<changelog>\n<changelog>"
// READ XML
function read(path) {
const fs = require("fs")
try {
return fs.readFileSync(path).toString()
} catch {
return null
}
}
function getLastCommit(xml) {
let result = xml.match(/<commit[^>]+hash="(.*?)"/)
return result && result[1]
}
// PARSING
function parseSubject(str) {
let result = str.match(/^([a-z]+)(?:\(([^\)^\/]+)(?:\/([^\)]+))?\))?:\s*(.*)$$/)
if (result) {
return {
type: result[1],
scope: result[2],
issue: (result[3] || "").replace(/^#/, ""),
subject: result[4],
}
} else {
return {
subject: str,
}
}
}
function extractPRNumber(str) {
let result = str.match(/\(#(\d+)\)$/)
return result && result[1]
}
function parseLogLine(line) {
return Object.assign(parseSubject(line.substr(20)), {
hash: line.substr(0, 8),
time: line.substr(9, 10),
pr: extractPRNumber(line),
})
}
// GENERATE NEW ENTRIES
function getLog(fromCommit) {
const range = fromCommit ? fromCommit + ".." : ""
const command = "git --no-pager log --format='%h %at %s' " + range
return childProcess
.execSync(command)
.toString()
.split("\n")
.filter((s) => s)
.map(parseLogLine)
}
function getPullRequest(token, number) {
const https = require("https")
const url = "https://api.github.com/repos/onivim/oni2/pulls/" + number
const headers = {
"User-Agent": "oni-fetch",
Authorization: token && `token ${token}`,
}
return new Promise((resolve, reject) =>
https.get(url, { headers }, (response) => {
if (response.statusCode == 200) {
const body = []
response.on("data", (chunk) => body.push(chunk))
response.on("end", () => resolve(JSON.parse(body.join(""))))
} else {
reject(response.statusCode + ": " + response.statusMessage)
}
}),
)
}
function extractLogEntry(body) {
let result = body.match(/```changelog\r?\n((.|[\s\S])*)\r?\n```/)
return result && result[1]
}
// GENERATE XML
function createCommitXml({ type, scope, issue, hash, pr, time, content, subject }) {
const typeAttr = type ? `type="${type}" ` : ""
const scopeAttr = scope ? `scope="${scope}" ` : ""
const issueAttr = issue ? `issue="${issue}" ` : ""
const prAttr = pr ? `pr="${pr}" ` : ""
return ` <commit ${typeAttr}${scopeAttr}${issueAttr}${prAttr}hash="${hash}" time="${time}">
${content ? content.replace(/\n/g, "\n ") : subject}
</commit>\n`
}
function addXmlCommits(xml, commits) {
const [before, after] = xml.split(/<changelog>\r?\n/, 2)
return before + "<changelog>\n" + commits.join("") + after
}
function write(path, content) {
const fs = require("fs")
fs.writeFileSync(path, content)
}
// MAIN
let path
let token
process.argv.slice(2).forEach((arg) => {
if (arg.startsWith("--token=")) {
token = arg.slice("--token=".length)
} else if (!arg.startsWith("--")) {
path = arg
} else {
throw new Error("invalid argument: " + arg)
}
})
const xml = read(path) || initialLog
const lastCommitHash = getLastCommit(xml)
console.log("Retrieving commits since " + lastCommitHash)
Promise.all(
getLog(lastCommitHash).map((commit) => {
const fluffTypes = ["test", "docs", "chore"]
// If the commit has an associated PR and is not "fluff", check the
// PR for more, and more up-to-date, information
if (commit.pr && !fluffTypes.includes(commit.type)) {
console.log(`Checking ${commit.hash} / #${commit.pr}`)
return getPullRequest(token, commit.pr)
.then((pr) => {
let logEntry = extractLogEntry(pr.body)
let parsed = parseSubject(pr.title)
return Object.assign({}, commit, parsed, { content: logEntry })
})
.catch((error) => {
console.error(`Error retrieving PR #${commit.pr} for ${commit.hash}: ${error}`)
return Promise.reject(error)
})
} else {
return commit
}
}),
)
.then((commits) => {
console.log("New commits:", commits)
const xmlCommits = commits.map(createCommitXml)
const newXml = addXmlCommits(xml, xmlCommits)
console.log("Writing to: " + path)
write(path, newXml)
console.log("Done.")
})
.catch((error) => console.error("Failed:", error))