/
main.ts
531 lines (471 loc) · 15.6 KB
/
main.ts
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import * as core from '@actions/core'
import path from 'path'
import simpleGit, { CommitSummary, Response } from 'simple-git'
import YAML from 'js-yaml'
import {
getInput,
getUserInfo,
input,
log,
matchGitArgs,
outputs,
readJSON,
setOutput
} from './util'
const baseDir = path.join(process.cwd(), getInput('cwd') || '')
const git = simpleGit({ baseDir })
const exitErrors: Error[] = []
core.info(`Running in ${baseDir}`)
;(async () => {
await checkInputs()
core.startGroup('Internal logs')
core.info('> Staging files...')
const peh = getInput('pathspec_error_handling')
if (getInput('add')) {
core.info('> Adding files...')
await add(peh == 'ignore' ? 'pathspec' : 'none')
} else core.info('> No files to add.')
if (getInput('remove')) {
core.info('> Removing files...')
await remove(peh == 'ignore' ? 'pathspec' : 'none')
} else core.info('> No files to remove.')
core.info('> Checking for uncommitted changes in the git working tree...')
const changedFiles = (await git.diffSummary(['--cached'])).files.length
if (changedFiles > 0) {
core.info(`> Found ${changedFiles} changed files.`)
await git
.addConfig('user.email', getInput('author_email'), undefined, log)
.addConfig('user.name', getInput('author_name'), undefined, log)
.addConfig('author.email', getInput('author_email'), undefined, log)
.addConfig('author.name', getInput('author_name'), undefined, log)
.addConfig('committer.email', getInput('committer_email'), undefined, log)
.addConfig('committer.name', getInput('committer_name'), undefined, log)
core.debug(
'> Current git config\n' +
JSON.stringify((await git.listConfig()).all, null, 2)
)
await git.fetch(['--tags', '--force'], log)
core.info('> Switching/creating branch...')
/** This should store whether the branch already existed, of if a new one was created */
let branchType!: 'existing' | 'new'
await git
.checkout(getInput('branch'))
.then(() => (branchType = 'existing'))
.catch(() => {
if (getInput('branch_mode') == 'create') {
log(
undefined,
`'${getInput('branch')}' branch not found, trying to create one.`
)
branchType = 'new'
return git.checkoutLocalBranch(getInput('branch'), log)
} else throw `'${getInput('branch')}' branch not found.`
})
/*
The current default value is set here: it will not pull when it has
created a new branch, it will use --rebase when the branch already existed
*/
const pull =
getInput('pull') ||
getInput('pull_strategy') ||
(branchType == 'new' ? 'NO-PULL' : '--no-rebase')
if (pull == 'NO-PULL') core.info('> Not pulling from repo.')
else {
core.info('> Pulling from remote...')
core.debug(`Current git pull arguments: ${pull}`)
await git
.fetch(undefined, log)
.pull(undefined, undefined, matchGitArgs(pull), log)
}
core.info('> Re-staging files...')
if (getInput('add')) await add('all')
if (getInput('remove')) await remove('all')
core.info('> Creating commit...')
await git.commit(
getInput('message'),
matchGitArgs(getInput('commit') || ''),
(err, data?: CommitSummary) => {
if (data) {
setOutput('committed', 'true')
setOutput('commit_sha', data.commit)
}
return log(err, data)
}
)
if (getInput('tag')) {
core.info('> Tagging commit...')
await git
.tag(matchGitArgs(getInput('tag') || ''), (err, data?) => {
if (data) setOutput('tagged', 'true')
return log(err, data)
})
.then((data) => {
setOutput('tagged', 'true')
return log(null, data)
})
.catch((err) => core.setFailed(err))
} else core.info('> No tag info provided.')
let pushOption: string | boolean
try {
pushOption = getInput('push', true)
} catch {
pushOption = getInput('push')
}
if (pushOption) {
// If the options is `true | string`...
core.info('> Pushing commit to repo...')
if (pushOption === true) {
core.debug(
`Running: git push origin ${getInput('branch')} --set-upstream`
)
await git.push(
'origin',
getInput('branch'),
{ '--set-upstream': null },
(err, data?) => {
if (data) setOutput('pushed', 'true')
return log(err, data)
}
)
} else {
core.debug(`Running: git push ${pushOption}`)
await git.push(
undefined,
undefined,
matchGitArgs(pushOption),
(err, data?) => {
if (data) setOutput('pushed', 'true')
return log(err, data)
}
)
}
if (getInput('tag')) {
core.info('> Pushing tags to repo...')
await git
.pushTags('origin', undefined, (e, d?) => log(undefined, e || d))
.catch(() => {
core.info(
'> Tag push failed: deleting remote tag and re-pushing...'
)
return git
.push(
undefined,
undefined,
{
'--delete': null,
origin: null,
[matchGitArgs(getInput('tag') || '').filter(
(w) => !w.startsWith('-')
)[0]]: null
},
log
)
.pushTags('origin', undefined, log)
})
} else core.info('> No tags to push.')
} else core.info('> Not pushing anything.')
core.endGroup()
core.info('> Task completed.')
} else {
core.endGroup()
core.info('> Working tree clean. Nothing to commit.')
}
})()
.then(() => {
// Check for exit errors
if (exitErrors.length == 1) throw exitErrors[0]
else if (exitErrors.length > 1) {
exitErrors.forEach((e) => core.error(e))
throw 'There have been multiple runtime errors.'
}
})
.then(logOutputs)
.catch((e) => {
core.endGroup()
logOutputs()
core.setFailed(e)
})
async function checkInputs() {
function setInput(input: input, value: string | undefined) {
if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value)
else return delete process.env[`INPUT_${input.toUpperCase()}`]
}
function setDefault(input: input, value: string) {
if (!getInput(input)) setInput(input, value)
return getInput(input)
}
const eventPath = process.env.GITHUB_EVENT_PATH,
event = eventPath && readJSON(eventPath)
const isPR = process.env.GITHUB_EVENT_NAME?.includes('pull_request'),
defaultBranch = isPR
? (event?.pull_request?.head?.ref as string)
: process.env.GITHUB_REF?.substring(11)
// #region add, remove
if (!getInput('add') && !getInput('remove'))
throw new Error(
"Both 'add' and 'remove' are empty, the action has nothing to do."
)
if (getInput('add')) {
const parsed = parseInputArray(getInput('add'))
if (parsed.length == 1)
core.info('Add input parsed as single string, running 1 git add command.')
else if (parsed.length > 1)
core.info(
`Add input parsed as string array, running ${parsed.length} git add commands.`
)
else core.setFailed('Add input: array length < 1')
}
if (getInput('remove')) {
const parsed = parseInputArray(getInput('remove') || '')
if (parsed.length == 1)
core.info(
'Remove input parsed as single string, running 1 git rm command.'
)
else if (parsed.length > 1)
core.info(
`Remove input parsed as string array, running ${parsed.length} git rm commands.`
)
else core.setFailed('Remove input: array length < 1')
}
// #endregion
// #region default_author
const default_author_valid = ['github_actor', 'user_info', 'github_actions']
if (!default_author_valid.includes(getInput('default_author')))
throw new Error(
`'${getInput(
'default_author'
)}' is not a valid value for default_author. Valid values: ${default_author_valid.join(
', '
)}`
)
// #endregion
// #region author_name, author_email
let name, email
switch (getInput('default_author')) {
case 'github_actor': {
name = process.env.GITHUB_ACTOR
email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`
break
}
case 'user_info': {
if (!getInput('author_name') || !getInput('author_email')) {
const res = await getUserInfo(process.env.GITHUB_ACTOR)
if (!res?.name)
core.warning("Couldn't fetch author name, filling with github_actor.")
if (!res?.email)
core.warning(
"Couldn't fetch author email, filling with github_actor."
)
res?.name && (name = res?.name)
res?.email && (email = res.email)
if (name && email) break
}
!name && (name = process.env.GITHUB_ACTOR)
!email && (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`)
break
}
case 'github_actions': {
name = 'github-actions'
email = '41898282+github-actions[bot]@users.noreply.github.com'
break
}
default:
throw new Error(
'This should not happen, please contact the author of this action. (checkInputs.author)'
)
}
setDefault('author_name', name)
setDefault('author_email', email)
core.info(
`> Using '${getInput('author_name')} <${getInput(
'author_email'
)}>' as author.`
)
// #endregion
// #region committer_name, committer_email
if (getInput('committer_name') || getInput('committer_email'))
core.info(
`> Using custom committer info: ${
getInput('committer_name') ||
getInput('author_name') + ' [from author info]'
} <${
getInput('committer_email') ||
getInput('author_email') + ' [from author info]'
}>`
)
setDefault('committer_name', getInput('author_name'))
setDefault('committer_email', getInput('author_email'))
core.debug(
`Committer: ${getInput('committer_name')} <${getInput('committer_email')}>`
)
// #endregion
// #region message
setDefault(
'message',
`Commit from GitHub Actions (${process.env.GITHUB_WORKFLOW})`
)
core.info(`> Using "${getInput('message')}" as commit message.`)
// #endregion
// #region branch
const branch = setDefault('branch', defaultBranch || '')
if (isPR)
core.info(`> Running for a PR, the action will use '${branch}' as ref.`)
// #endregion
// #region branch_mode
const branch_mode_valid = ['throw', 'create']
if (!branch_mode_valid.includes(getInput('branch_mode')))
throw new Error(
`"${getInput(
'branch_mode'
)}" is not a valid value for the 'branch_mode' input. Valid values are: ${branch_mode_valid.join(
', '
)}`
)
// #endregion
// #region pathspec_error_handling
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd']
if (!peh_valid.includes(getInput('pathspec_error_handling')))
throw new Error(
`"${getInput(
'pathspec_error_handling'
)}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join(
', '
)}`
)
// #endregion
// #region pull, pull_strategy [deprecated]
if (getInput('pull') && getInput('pull_strategy'))
throw new Error(
"You can't use both pull and pull_strategy as action inputs. Please remove pull_strategy, which is deprecated."
)
if ([getInput('pull'), getInput('pull_strategy')].includes('NO-PULL'))
core.debug("NO-PULL found: won't pull from remote.")
// #endregion
// #region push
if (getInput('push')) {
// It has to be either 'true', 'false', or any other string (use as arguments)
let value: string | boolean
try {
value = getInput('push', true)
} catch {
value = getInput('push')
}
core.debug(`Current push option: '${value}' (parsed as ${typeof value})`)
}
// #endregion
// #region github_token
if (!getInput('github_token'))
core.warning(
'No github_token has been detected, the action may fail if it needs to use the API'
)
// #endregion
}
async function add(
ignoreErrors: 'all' | 'pathspec' | 'none' = 'none'
): Promise<(void | Response<void>)[]> {
const input = getInput('add')
if (!input) return []
const parsed = parseInputArray(input)
const res: (void | Response<void>)[] = []
for (const args of parsed) {
res.push(
// Push the result of every git command (which are executed in order) to the array
// If any of them fails, the whole function will return a Promise rejection
await git
.add(matchGitArgs(args), (err: any, data?: any) =>
log(ignoreErrors == 'all' ? null : err, data)
)
.catch((e: Error) => {
// if I should ignore every error, return
if (ignoreErrors == 'all') return
// if it's a pathspec error...
if (
e.message.includes('fatal: pathspec') &&
e.message.includes('did not match any files')
) {
if (ignoreErrors == 'pathspec') return
const peh = getInput('pathspec_error_handling'),
err = new Error(
`Add command did not match any file: git add ${args}`
)
if (peh == 'exitImmediately') throw err
if (peh == 'exitAtEnd') exitErrors.push(err)
} else throw e
})
)
}
return res
}
async function remove(
ignoreErrors: 'all' | 'pathspec' | 'none' = 'none'
): Promise<(void | Response<void>)[]> {
const input = getInput('remove')
if (!input) return []
const parsed = parseInputArray(input)
const res: (void | Response<void>)[] = []
for (const args of parsed) {
res.push(
// Push the result of every git command (which are executed in order) to the array
// If any of them fails, the whole function will return a Promise rejection
await git
.rm(matchGitArgs(args), (e: any, d?: any) =>
log(ignoreErrors == 'all' ? null : e, d)
)
.catch((e: Error) => {
// if I should ignore every error, return
if (ignoreErrors == 'all') return
// if it's a pathspec error...
if (
e.message.includes('fatal: pathspec') &&
e.message.includes('did not match any files')
) {
if (ignoreErrors == 'pathspec') return
const peh = getInput('pathspec_error_handling'),
err = new Error(
`Remove command did not match any file:\n git rm ${args}`
)
if (peh == 'exitImmediately') throw err
if (peh == 'exitAtEnd') exitErrors.push(err)
} else throw e
})
)
}
return res
}
/**
* Tries to parse a JSON array, then a YAML array.
* If both fail, it returns an array containing the input value as its only element
*/
function parseInputArray(input: string): string[] {
try {
const json = JSON.parse(input)
if (
json &&
Array.isArray(json) &&
json.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as JSON array of length ${json.length}`)
return json
}
} catch {}
try {
const yaml = YAML.load(input)
if (
yaml &&
Array.isArray(yaml) &&
yaml.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as YAML array of length ${yaml.length}`)
return yaml
}
} catch {}
core.debug('Input parsed as single string')
return [input]
}
function logOutputs() {
core.startGroup('Outputs')
for (const key in outputs) {
core.info(`${key}: ${outputs[key]}`)
}
core.endGroup()
}