-
Notifications
You must be signed in to change notification settings - Fork 15
/
action.js
307 lines (264 loc) · 8.09 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
const core = require('@actions/core')
const github = require('@actions/github/lib/utils')
const semver = require('semver')
const process = require('process')
const { throttling } = require('@octokit/plugin-throttling')
const { retry } = require('@octokit/plugin-retry')
const { Octokit } = require('@octokit/core');
const GitClient = github.GitHub.plugin(throttling, retry)
const gitClient = new GitClient({
auth: core.getInput('github_token', { required: true }),
throttle: {
onRateLimit: (_retryAfter, options, _gitClient) => {
core.info(`Rate limit exceeded for ${options.method} ${options.url}`)
return true
},
onAbuseLimit: (_retryAfter, options, _gitClient) => {
core.info(
`Abuse detected for ${options.method} ${options.url}. Not retrying.`
)
},
},
})
const octokit = new Octokit({
auth: core.getInput('github_token', { required: true })
})
const [owner, repo] = process.env['GITHUB_REPOSITORY'].split('/', 2)
const requestOpts = { owner, repo }
const Scheme = {
Continuous: 'continuous',
Semantic: 'semantic',
}
const Semantic = {
Major: 'major',
Minor: 'minor',
Patch: 'patch',
Premajor: 'premajor',
Preminor: 'preminor',
Prepatch: 'prepatch',
Prerelease: 'prerelease',
}
function isNullString(string) {
return (
!string || string.length == 0 || string == 'null' || string == 'undefined'
)
}
function initialTag(tag) {
const isPrerelease = core.getInput('version_type') == Semantic.Prerelease
const suffix = core.getInput('prerelease_suffix')
return isPrerelease ? `${tag}-${suffix}` : tag
}
async function existingTags() {
core.info('Fetching tags.')
return await octokit
.graphql(
`{
repository(owner: "${owner}", name: "${repo}") {
refs(
first: ${core.getInput('tag_fetch_depth') || 10}
refPrefix: "refs/tags/"
orderBy: { field: TAG_COMMIT_DATE, direction: DESC }
) {
nodes {
ref: name
object: target {
sha: oid
}
}
}
}
}`
).then((result) => {
return result.repository.refs.nodes
})
.catch((e) => {
core.setFailed(`Failed to fetch tags: ${e}`)
})
}
async function latestTagForBranch(allTags, branch) {
const options = gitClient.rest.repos.listCommits.endpoint.merge({
...requestOpts,
// Set pagination per_page param to max allowed (100).
// Default is 30 per page, which can hit rate limits on repositories with
// a lot of commits.
per_page: 100,
sha: branch,
})
core.info(
`Fetching commits for ref ${branch}. This may take a while on large repositories.`
)
return await gitClient
.paginate(options, (response, done) => {
for (const commit of response.data) {
if (allTags.find((tag) => tag.object.sha === commit.sha)) {
core.info('Finished fetching commits, found a tag match.')
done()
break
}
}
return response.data
})
.then((commits) => {
core.info(`Fetched ${commits.length} commits`)
let latestTag
for (const commit of commits) {
latestTag = allTags.find((tag) => tag.object.sha === commit.sha)
if (latestTag) break
}
return latestTag
})
.catch((e) => {
core.setFailed(`Failed to fetch commits for branch '${branch}' : ${e}`)
})
}
function semanticVersion(tag) {
try {
const [version, pre] = tag.split('-', 2)
const sem = semver.parse(semver.coerce(version))
if (!isNullString(pre)) {
// reset the raw string values tracked in the object to ensure future
// calculations are performed correctly
sem.raw = `${sem.raw}-${pre}`
sem.version = `${sem.version}-${pre}`
sem.prerelease = semver.prerelease(`0.0.0-${pre}`)
}
return sem
} catch (_) {
// semver will return null if it fails to parse, maintain this behavior in our API
return null
}
}
function determineContinuousBumpType(semTag) {
const type = core.getInput('version_type') || 'prerelease'
const hasExistingPrerelease = semTag.prerelease.length > 0
switch (type) {
case Semantic.Prerelease:
return hasExistingPrerelease ? Semantic.Prerelease : Semantic.Premajor
case Semantic.Premajor:
return Semantic.Premajor
default:
return Semantic.Major
}
}
function determinePrereleaseName(semTag) {
const hasExistingPrerelease = semTag.prerelease.length > 0
if (hasExistingPrerelease && !core.getInput('prerelease_suffix')) {
const [name, _] = semTag.prerelease
return name
} else {
return core.getInput('prerelease_suffix') || 'beta'
}
}
function computeNextContinuous(semTag) {
const bumpType = determineContinuousBumpType(semTag)
const preName = determinePrereleaseName(semTag)
const nextSemTag = semver.parse(semver.inc(semTag, bumpType, preName))
const tagSuffix =
nextSemTag.prerelease.length > 0
? `-${nextSemTag.prerelease.join('.')}`
: ''
return [semTag.options.tagPrefix, nextSemTag.major, tagSuffix].join('')
}
function computeNextSemantic(semTag) {
try {
const type = core.getInput('version_type') || 'prerelease'
const preName = determinePrereleaseName(semTag)
switch (type) {
case Semantic.Major:
case Semantic.Minor:
case Semantic.Patch:
case Semantic.Premajor:
case Semantic.Preminor:
case Semantic.Prepatch:
case Semantic.Prerelease:
return `${semTag.options.tagPrefix}${semver.inc(semTag, type, preName)}`
default:
core.setFailed(
`Unsupported semantic version type ${type}. Must be one of (${Object.values(
Semantic
).join(', ')})`
)
}
} catch (error) {
core.setFailed(`Failed to compute next semantic tag: ${error}`)
}
}
async function findMatchingLastTag(tags, branch = null) {
if (branch) {
const latestTag = await latestTagForBranch(tags, branch)
if (latestTag) {
return latestTag.ref.replace('refs/tags/', '')
} else {
core.setFailed(`Failed to find a tag for any commit on branch: ${branch}`)
}
} else {
return tags.shift().ref.replace('refs/tags/', '')
}
}
async function computeLastTag(givenTag, branch = null) {
if (isNullString(givenTag)) {
const recentTags = await existingTags()
if (recentTags.length < 1) {
return null
} else {
return findMatchingLastTag(recentTags, branch).catch((error) => {
core.setFailed(`Failed to find matching last tag with error ${error}`)
})
}
} else {
return givenTag
}
}
async function computeNextTag() {
const scheme = core.getInput('version_scheme')
const branch = core.getInput('branch')
const givenTag = core.getInput('tag')
const lastTag = await computeLastTag(givenTag, branch)
// Handle zero-state where no tags exist for the repo
if (!lastTag) {
switch (scheme) {
case Scheme.Continuous:
return initialTag('v1')
case Scheme.Semantic:
return initialTag('v1.0.0')
default:
core.setFailed(`Unsupported version scheme: ${scheme}`)
return
}
}
core.info(`Computing the next tag based on: ${lastTag}`)
core.setOutput('previous_tag', lastTag)
const semTag = semanticVersion(lastTag)
if (semTag == null) {
core.setFailed(`Failed to parse tag: ${lastTag}`)
return
} else {
semTag.options.tagPrefix = lastTag.startsWith('v') ? 'v' : ''
}
switch (scheme) {
case 'continuous':
return computeNextContinuous(semTag)
case 'semantic':
return computeNextSemantic(semTag)
default:
core.setFailed(
`Invalid version_scheme: '${scheme}'. Must be one of (${Object.values(
Scheme
).join(', ')})`
)
}
}
async function run() {
const nextTag = await computeNextTag().catch((error) => {
core.setFailed(`Failed to compute next tag with error ${error}`)
})
core.info(`Computed the next tag as: ${nextTag}`)
core.setOutput('next_tag', nextTag)
}
try {
run().catch((error) => {
core.setFailed(`Action failed with error ${error}`)
})
} catch (error) {
core.setFailed(`Action failed with error ${error}`)
}