chore: switch to GTS for linting (#636)
* fix: switch over to gts * fix: add debug message for input arrays * fix: fix input array parsing
This commit is contained in:
8
.editorconfig
Normal file
8
.editorconfig
Normal file
@@ -0,0 +1,8 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
insert_final_newline = true
|
||||
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@@ -0,0 +1 @@
|
||||
lib/
|
||||
36
.eslintrc.js
36
.eslintrc.js
@@ -1,36 +0,0 @@
|
||||
module.exports = {
|
||||
env: {
|
||||
commonjs: true,
|
||||
es6: true,
|
||||
node: true
|
||||
},
|
||||
extends: ['eslint:recommended', 'plugin:prettier/recommended'],
|
||||
globals: {},
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 6,
|
||||
sourceType: 'module'
|
||||
},
|
||||
plugins: ['@typescript-eslint'],
|
||||
ignorePatterns: ['lib/*'],
|
||||
rules: {
|
||||
'prettier/prettier': 'warn',
|
||||
'no-cond-assign': [2, 'except-parens'],
|
||||
'no-unused-vars': 0,
|
||||
'no-redeclare': 0,
|
||||
'@typescript-eslint/no-unused-vars': 1,
|
||||
'no-empty': [
|
||||
'error',
|
||||
{
|
||||
allowEmptyCatch: true
|
||||
}
|
||||
],
|
||||
'prefer-const': [
|
||||
'warn',
|
||||
{
|
||||
destructuring: 'all'
|
||||
}
|
||||
],
|
||||
'spaced-comment': 'warn'
|
||||
}
|
||||
}
|
||||
3
.eslintrc.json
Normal file
3
.eslintrc.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./node_modules/gts/"
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
3
.prettierrc.js
Normal file
3
.prettierrc.js
Normal file
@@ -0,0 +1,3 @@
|
||||
module.exports = {
|
||||
...require('gts/.prettierrc.json')
|
||||
}
|
||||
2
lib/index.js
generated
2
lib/index.js
generated
File diff suppressed because one or more lines are too long
2752
package-lock.json
generated
2752
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
21
package.json
21
package.json
@@ -5,12 +5,15 @@
|
||||
"description": "Add & commit files from a path directly from GitHub Actions",
|
||||
"main": "lib/index.js",
|
||||
"scripts": {
|
||||
"prebuild": "npm run clean",
|
||||
"build": "ncc build src/main.ts --minify --out lib",
|
||||
"watch": "ncc build src/main.ts --watch --out lib",
|
||||
"lint": "eslint --ext .ts src",
|
||||
"lint:fix": "eslint --ext .ts --fix src",
|
||||
"lint": "gts lint",
|
||||
"prepare": "husky",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"clean": "gts clean",
|
||||
"fix": "gts fix",
|
||||
"pretest": "npm run compile",
|
||||
"posttest": "npm run lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
@@ -21,17 +24,13 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.11.6",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@types/node": "20.8.2",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"all-contributors-cli": "^6.26.1",
|
||||
"eslint": "^8.48.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"gts": "^5.2.0",
|
||||
"husky": "^9.0.11",
|
||||
"prettier": "^3.2.5",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "~5.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
||||
204
src/io.ts
204
src/io.ts
@@ -1,38 +1,38 @@
|
||||
import * as core from '@actions/core'
|
||||
import { getUserInfo, parseInputArray } from './util'
|
||||
import * as core from '@actions/core';
|
||||
import {getUserInfo, parseInputArray} from './util';
|
||||
|
||||
interface InputTypes {
|
||||
add: string
|
||||
author_name: string
|
||||
author_email: string
|
||||
commit: string | undefined
|
||||
committer_name: string
|
||||
committer_email: string
|
||||
cwd: string
|
||||
default_author: 'github_actor' | 'user_info' | 'github_actions'
|
||||
fetch: string
|
||||
message: string
|
||||
new_branch: string | undefined
|
||||
pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd'
|
||||
pull: string | undefined
|
||||
push: string
|
||||
remove: string | undefined
|
||||
tag: string | undefined
|
||||
tag_push: string | undefined
|
||||
export interface InputTypes {
|
||||
add: string;
|
||||
author_name: string;
|
||||
author_email: string;
|
||||
commit: string | undefined;
|
||||
committer_name: string;
|
||||
committer_email: string;
|
||||
cwd: string;
|
||||
default_author: 'github_actor' | 'user_info' | 'github_actions';
|
||||
fetch: string;
|
||||
message: string;
|
||||
new_branch: string | undefined;
|
||||
pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd';
|
||||
pull: string | undefined;
|
||||
push: string;
|
||||
remove: string | undefined;
|
||||
tag: string | undefined;
|
||||
tag_push: string | undefined;
|
||||
|
||||
github_token: string | undefined
|
||||
github_token: string | undefined;
|
||||
}
|
||||
export type input = keyof InputTypes
|
||||
export type input = keyof InputTypes;
|
||||
|
||||
interface OutputTypes {
|
||||
committed: 'true' | 'false'
|
||||
commit_long_sha: string | undefined
|
||||
commit_sha: string | undefined
|
||||
pushed: 'true' | 'false'
|
||||
tagged: 'true' | 'false'
|
||||
tag_pushed: 'true' | 'false'
|
||||
export interface OutputTypes {
|
||||
committed: 'true' | 'false';
|
||||
commit_long_sha: string | undefined;
|
||||
commit_sha: string | undefined;
|
||||
pushed: 'true' | 'false';
|
||||
tagged: 'true' | 'false';
|
||||
tag_pushed: 'true' | 'false';
|
||||
}
|
||||
export type output = keyof OutputTypes
|
||||
export type output = keyof OutputTypes;
|
||||
|
||||
export const outputs: OutputTypes = {
|
||||
committed: 'false',
|
||||
@@ -40,81 +40,82 @@ export const outputs: OutputTypes = {
|
||||
commit_sha: undefined,
|
||||
pushed: 'false',
|
||||
tagged: 'false',
|
||||
tag_pushed: 'false'
|
||||
}
|
||||
tag_pushed: 'false',
|
||||
};
|
||||
// Setup default output values
|
||||
Object.entries(outputs).forEach(([name, value]) => core.setOutput(name, value))
|
||||
Object.entries(outputs).forEach(([name, value]) => core.setOutput(name, value));
|
||||
|
||||
export function getInput<T extends input>(name: T, parseAsBool: true): boolean
|
||||
export function getInput<T extends input>(name: T, parseAsBool: true): boolean;
|
||||
export function getInput<T extends input>(
|
||||
name: T,
|
||||
parseAsBool?: false
|
||||
): InputTypes[T]
|
||||
): InputTypes[T];
|
||||
export function getInput<T extends input>(
|
||||
name: T,
|
||||
parseAsBool = false
|
||||
): InputTypes[T] | boolean {
|
||||
if (parseAsBool) return core.getBooleanInput(name)
|
||||
// @ts-expect-error
|
||||
return core.getInput(name)
|
||||
if (parseAsBool) return core.getBooleanInput(name);
|
||||
return core.getInput(name) as InputTypes[T];
|
||||
}
|
||||
|
||||
export function setOutput<T extends output>(name: T, value: OutputTypes[T]) {
|
||||
core.debug(`Setting output: ${name}=${value}`)
|
||||
outputs[name] = value
|
||||
core.setOutput(name, value)
|
||||
core.debug(`Setting output: ${name}=${value}`);
|
||||
outputs[name] = value;
|
||||
core.setOutput(name, value);
|
||||
}
|
||||
|
||||
export function logOutputs() {
|
||||
core.startGroup('Outputs')
|
||||
core.startGroup('Outputs');
|
||||
for (const key in outputs) {
|
||||
core.info(`${key}: ${outputs[key]}`)
|
||||
core.info(`${key}: ${outputs[key as keyof OutputTypes]}`);
|
||||
}
|
||||
core.endGroup()
|
||||
core.endGroup();
|
||||
}
|
||||
|
||||
export 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()}`]
|
||||
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)
|
||||
if (!getInput(input)) setInput(input, value);
|
||||
return getInput(input);
|
||||
}
|
||||
|
||||
// #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.')
|
||||
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')
|
||||
);
|
||||
else core.setFailed('Add input: array length < 1');
|
||||
}
|
||||
if (getInput('remove')) {
|
||||
const parsed = parseInputArray(getInput('remove') || '')
|
||||
if (parsed.length == 1)
|
||||
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')
|
||||
);
|
||||
else core.setFailed('Remove input: array length < 1');
|
||||
}
|
||||
// #endregion
|
||||
|
||||
// #region default_author
|
||||
const default_author_valid = ['github_actor', 'user_info', 'github_actions']
|
||||
const default_author_valid = ['github_actor', 'user_info', 'github_actions'];
|
||||
if (!default_author_valid.includes(getInput('default_author')))
|
||||
throw new Error(
|
||||
`'${getInput(
|
||||
@@ -122,71 +123,74 @@ export async function checkInputs() {
|
||||
)}' is not a valid value for default_author. Valid values: ${default_author_valid.join(
|
||||
', '
|
||||
)}`
|
||||
)
|
||||
);
|
||||
// #endregion
|
||||
|
||||
// #region fetch
|
||||
if (getInput('fetch')) {
|
||||
let value: string | boolean
|
||||
let value: string | boolean;
|
||||
|
||||
try {
|
||||
value = getInput('fetch', true)
|
||||
value = getInput('fetch', true);
|
||||
} catch {
|
||||
value = getInput('fetch')
|
||||
value = getInput('fetch');
|
||||
}
|
||||
|
||||
core.debug(`Current fetch option: '${value}' (parsed as ${typeof value})`)
|
||||
core.debug(`Current fetch option: '${value}' (parsed as ${typeof value})`);
|
||||
}
|
||||
// #endregion
|
||||
|
||||
// #region author_name, author_email
|
||||
let name, 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
|
||||
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)
|
||||
const res = await getUserInfo(process.env.GITHUB_ACTOR);
|
||||
if (!res?.name)
|
||||
core.warning("Couldn't fetch author name, filling with github_actor.")
|
||||
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
|
||||
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
|
||||
!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
|
||||
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)
|
||||
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
|
||||
@@ -199,25 +203,25 @@ export async function checkInputs() {
|
||||
getInput('committer_email') ||
|
||||
getInput('author_email') + ' [from author info]'
|
||||
}>`
|
||||
)
|
||||
);
|
||||
|
||||
setDefault('committer_name', getInput('author_name'))
|
||||
setDefault('committer_email', getInput('author_email'))
|
||||
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.`)
|
||||
);
|
||||
core.info(`> Using "${getInput('message')}" as commit message.`);
|
||||
// #endregion
|
||||
|
||||
// #region pathspec_error_handling
|
||||
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd']
|
||||
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd'];
|
||||
if (!peh_valid.includes(getInput('pathspec_error_handling')))
|
||||
throw new Error(
|
||||
`"${getInput(
|
||||
@@ -225,28 +229,28 @@ export async function checkInputs() {
|
||||
)}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join(
|
||||
', '
|
||||
)}`
|
||||
)
|
||||
);
|
||||
// #endregion
|
||||
|
||||
// #region pull
|
||||
if (getInput('pull') == 'NO-PULL')
|
||||
if (getInput('pull') === 'NO-PULL')
|
||||
core.warning(
|
||||
"`NO-PULL` is a legacy option for the `pull` input. If you don't want the action to pull the repo, simply remove this input."
|
||||
)
|
||||
);
|
||||
// #endregion
|
||||
|
||||
// #region push
|
||||
if (getInput('push')) {
|
||||
// It has to be either 'true', 'false', or any other string (use as arguments)
|
||||
let value: string | boolean
|
||||
let value: string | boolean;
|
||||
|
||||
try {
|
||||
value = getInput('push', true)
|
||||
value = getInput('push', true);
|
||||
} catch {
|
||||
value = getInput('push')
|
||||
value = getInput('push');
|
||||
}
|
||||
|
||||
core.debug(`Current push option: '${value}' (parsed as ${typeof value})`)
|
||||
core.debug(`Current push option: '${value}' (parsed as ${typeof value})`);
|
||||
}
|
||||
// #endregion
|
||||
|
||||
@@ -254,6 +258,6 @@ export async function checkInputs() {
|
||||
if (!getInput('github_token'))
|
||||
core.warning(
|
||||
'No github_token has been detected, the action may fail if it needs to use the API'
|
||||
)
|
||||
);
|
||||
// #endregion
|
||||
}
|
||||
|
||||
254
src/main.ts
254
src/main.ts
@@ -1,47 +1,47 @@
|
||||
import * as core from '@actions/core'
|
||||
import path from 'path'
|
||||
import simpleGit, { Response } from 'simple-git'
|
||||
import { checkInputs, getInput, logOutputs, setOutput } from './io'
|
||||
import { log, matchGitArgs, parseInputArray } from './util'
|
||||
import * as core from '@actions/core';
|
||||
import * as path from 'path';
|
||||
import simpleGit, {Response} from 'simple-git';
|
||||
import {checkInputs, getInput, logOutputs, setOutput} from './io';
|
||||
import {log, matchGitArgs, parseInputArray} from './util';
|
||||
|
||||
const baseDir = path.join(process.cwd(), getInput('cwd') || '')
|
||||
const git = simpleGit({ baseDir })
|
||||
const baseDir = path.join(process.cwd(), getInput('cwd') || '');
|
||||
const git = simpleGit({baseDir});
|
||||
|
||||
const exitErrors: Error[] = []
|
||||
const exitErrors: Error[] = [];
|
||||
|
||||
core.info(`Running in ${baseDir}`)
|
||||
;(async () => {
|
||||
await checkInputs()
|
||||
core.info(`Running in ${baseDir}`);
|
||||
(async () => {
|
||||
await checkInputs();
|
||||
|
||||
core.startGroup('Internal logs')
|
||||
core.info('> Staging files...')
|
||||
core.startGroup('Internal logs');
|
||||
core.info('> Staging files...');
|
||||
|
||||
const ignoreErrors =
|
||||
getInput('pathspec_error_handling') == 'ignore' ? 'pathspec' : 'none'
|
||||
getInput('pathspec_error_handling') === 'ignore' ? 'pathspec' : 'none';
|
||||
|
||||
if (getInput('add')) {
|
||||
core.info('> Adding files...')
|
||||
await add(ignoreErrors)
|
||||
} else core.info('> No files to add.')
|
||||
core.info('> Adding files...');
|
||||
await add(ignoreErrors);
|
||||
} else core.info('> No files to add.');
|
||||
|
||||
if (getInput('remove')) {
|
||||
core.info('> Removing files...')
|
||||
await remove(ignoreErrors)
|
||||
} else core.info('> No files to remove.')
|
||||
core.info('> Removing files...');
|
||||
await remove(ignoreErrors);
|
||||
} 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
|
||||
core.info('> Checking for uncommitted changes in the git working tree...');
|
||||
const changedFiles = (await git.diffSummary(['--cached'])).files.length;
|
||||
// continue if there are any changes or if the allow-empty commit argument is included
|
||||
if (
|
||||
changedFiles > 0 ||
|
||||
matchGitArgs(getInput('commit') || '').includes('--allow-empty')
|
||||
) {
|
||||
core.info(`> Found ${changedFiles} changed files.`)
|
||||
core.info(`> Found ${changedFiles} changed files.`);
|
||||
core.debug(
|
||||
`--allow-empty argument detected: ${matchGitArgs(
|
||||
getInput('commit') || ''
|
||||
).includes('--allow-empty')}`
|
||||
)
|
||||
);
|
||||
|
||||
await git
|
||||
.addConfig('user.email', getInput('author_email'), undefined, log)
|
||||
@@ -49,252 +49,252 @@ core.info(`Running in ${baseDir}`)
|
||||
.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)
|
||||
.addConfig('committer.name', getInput('committer_name'), undefined, log);
|
||||
core.debug(
|
||||
'> Current git config\n' +
|
||||
JSON.stringify((await git.listConfig()).all, null, 2)
|
||||
)
|
||||
);
|
||||
|
||||
let fetchOption: string | boolean
|
||||
let fetchOption: string | boolean;
|
||||
try {
|
||||
fetchOption = getInput('fetch', true)
|
||||
fetchOption = getInput('fetch', true);
|
||||
} catch {
|
||||
fetchOption = getInput('fetch')
|
||||
fetchOption = getInput('fetch');
|
||||
}
|
||||
if (fetchOption) {
|
||||
core.info('> Fetching repo...')
|
||||
core.info('> Fetching repo...');
|
||||
await git.fetch(
|
||||
matchGitArgs(fetchOption === true ? '' : fetchOption),
|
||||
log
|
||||
)
|
||||
} else core.info('> Not fetching repo.')
|
||||
);
|
||||
} else core.info('> Not fetching repo.');
|
||||
|
||||
const targetBranch = getInput('new_branch')
|
||||
const targetBranch = getInput('new_branch');
|
||||
if (targetBranch) {
|
||||
core.info('> Checking-out branch...')
|
||||
core.info('> Checking-out branch...');
|
||||
|
||||
if (!fetchOption)
|
||||
core.warning(
|
||||
'Creating a new branch without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.'
|
||||
)
|
||||
);
|
||||
|
||||
await git
|
||||
.checkout(targetBranch)
|
||||
.then(() => {
|
||||
log(undefined, `'${targetBranch}' branch already existed.`)
|
||||
log(undefined, `'${targetBranch}' branch already existed.`);
|
||||
})
|
||||
.catch(() => {
|
||||
log(undefined, `Creating '${targetBranch}' branch.`)
|
||||
return git.checkoutLocalBranch(targetBranch, log)
|
||||
})
|
||||
log(undefined, `Creating '${targetBranch}' branch.`);
|
||||
return git.checkoutLocalBranch(targetBranch, log);
|
||||
});
|
||||
}
|
||||
|
||||
const pullOption = getInput('pull')
|
||||
const pullOption = getInput('pull');
|
||||
if (pullOption) {
|
||||
core.info('> Pulling from remote...')
|
||||
core.debug(`Current git pull arguments: ${pullOption}`)
|
||||
core.info('> Pulling from remote...');
|
||||
core.debug(`Current git pull arguments: ${pullOption}`);
|
||||
await git
|
||||
.fetch(undefined, log)
|
||||
.pull(undefined, undefined, matchGitArgs(pullOption), log)
|
||||
.pull(undefined, undefined, matchGitArgs(pullOption), log);
|
||||
|
||||
core.info('> Checking for conflicts...')
|
||||
const status = await git.status(undefined, log)
|
||||
core.info('> Checking for conflicts...');
|
||||
const status = await git.status(undefined, log);
|
||||
|
||||
if (!status.conflicted.length) {
|
||||
core.info('> No conflicts found.')
|
||||
core.info('> Re-staging files...')
|
||||
if (getInput('add')) await add(ignoreErrors)
|
||||
if (getInput('remove')) await remove(ignoreErrors)
|
||||
core.info('> No conflicts found.');
|
||||
core.info('> Re-staging files...');
|
||||
if (getInput('add')) await add(ignoreErrors);
|
||||
if (getInput('remove')) await remove(ignoreErrors);
|
||||
} else
|
||||
throw new Error(
|
||||
`There are ${
|
||||
status.conflicted.length
|
||||
} conflicting files: ${status.conflicted.join(', ')}`
|
||||
)
|
||||
} else core.info('> Not pulling from repo.')
|
||||
);
|
||||
} else core.info('> Not pulling from repo.');
|
||||
|
||||
core.info('> Creating commit...')
|
||||
core.info('> Creating commit...');
|
||||
await git
|
||||
.commit(getInput('message'), matchGitArgs(getInput('commit') || ''))
|
||||
.then(async (data) => {
|
||||
log(undefined, data)
|
||||
setOutput('committed', 'true')
|
||||
setOutput('commit_long_sha', data.commit)
|
||||
setOutput('commit_sha', data.commit.substring(0, 7))
|
||||
.then(async data => {
|
||||
log(undefined, data);
|
||||
setOutput('committed', 'true');
|
||||
setOutput('commit_long_sha', data.commit);
|
||||
setOutput('commit_sha', data.commit.substring(0, 7));
|
||||
})
|
||||
.catch((err) => core.setFailed(err))
|
||||
.catch(err => core.setFailed(err));
|
||||
|
||||
if (getInput('tag')) {
|
||||
core.info('> Tagging commit...')
|
||||
core.info('> Tagging commit...');
|
||||
|
||||
if (!fetchOption)
|
||||
core.warning(
|
||||
'Creating a tag without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.'
|
||||
)
|
||||
);
|
||||
|
||||
await git
|
||||
.tag(matchGitArgs(getInput('tag') || ''), (err, data?) => {
|
||||
if (data) setOutput('tagged', 'true')
|
||||
return log(err, data)
|
||||
if (data) setOutput('tagged', 'true');
|
||||
return log(err, data);
|
||||
})
|
||||
.then((data) => {
|
||||
setOutput('tagged', 'true')
|
||||
return log(null, data)
|
||||
.then(data => {
|
||||
setOutput('tagged', 'true');
|
||||
return log(null, data);
|
||||
})
|
||||
.catch((err) => core.setFailed(err))
|
||||
} else core.info('> No tag info provided.')
|
||||
.catch(err => core.setFailed(err));
|
||||
} else core.info('> No tag info provided.');
|
||||
|
||||
let pushOption: string | boolean
|
||||
let pushOption: string | boolean;
|
||||
try {
|
||||
pushOption = getInput('push', true)
|
||||
pushOption = getInput('push', true);
|
||||
} catch {
|
||||
pushOption = getInput('push')
|
||||
pushOption = getInput('push');
|
||||
}
|
||||
if (pushOption) {
|
||||
// If the options is `true | string`...
|
||||
core.info('> Pushing commit to repo...')
|
||||
core.info('> Pushing commit to repo...');
|
||||
|
||||
if (pushOption === true) {
|
||||
core.debug(
|
||||
`Running: git push origin ${
|
||||
getInput('new_branch') || ''
|
||||
} --set-upstream`
|
||||
)
|
||||
);
|
||||
await git.push(
|
||||
'origin',
|
||||
getInput('new_branch'),
|
||||
{ '--set-upstream': null },
|
||||
{'--set-upstream': null},
|
||||
(err, data?) => {
|
||||
if (data) setOutput('pushed', 'true')
|
||||
return log(err, data)
|
||||
if (data) setOutput('pushed', 'true');
|
||||
return log(err, data);
|
||||
}
|
||||
)
|
||||
);
|
||||
} else {
|
||||
core.debug(`Running: git push ${pushOption}`)
|
||||
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 (data) setOutput('pushed', 'true');
|
||||
return log(err, data);
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (getInput('tag')) {
|
||||
core.info('> Pushing tags to repo...')
|
||||
core.info('> Pushing tags to repo...');
|
||||
|
||||
await git
|
||||
.pushTags('origin', matchGitArgs(getInput('tag_push') || ''))
|
||||
.then((data) => {
|
||||
setOutput('tag_pushed', 'true')
|
||||
return log(null, data)
|
||||
.then(data => {
|
||||
setOutput('tag_pushed', 'true');
|
||||
return log(null, data);
|
||||
})
|
||||
.catch((err) => core.setFailed(err))
|
||||
} else core.info('> No tags to push.')
|
||||
} else core.info('> Not pushing anything.')
|
||||
.catch(err => core.setFailed(err));
|
||||
} else core.info('> No tags to push.');
|
||||
} else core.info('> Not pushing anything.');
|
||||
|
||||
core.endGroup()
|
||||
core.info('> Task completed.')
|
||||
core.endGroup();
|
||||
core.info('> Task completed.');
|
||||
} else {
|
||||
core.endGroup()
|
||||
core.info('> Working tree clean. Nothing to commit.')
|
||||
core.endGroup();
|
||||
core.info('> Working tree clean. Nothing to commit.');
|
||||
}
|
||||
})()
|
||||
.then(() => {
|
||||
// Check for exit errors
|
||||
if (exitErrors.length == 1) throw exitErrors[0]
|
||||
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.'
|
||||
exitErrors.forEach(e => core.error(e));
|
||||
throw 'There have been multiple runtime errors.';
|
||||
}
|
||||
})
|
||||
.then(logOutputs)
|
||||
.catch((e) => {
|
||||
core.endGroup()
|
||||
logOutputs()
|
||||
core.setFailed(e)
|
||||
})
|
||||
.catch(e => {
|
||||
core.endGroup();
|
||||
logOutputs();
|
||||
core.setFailed(e);
|
||||
});
|
||||
|
||||
async function add(ignoreErrors: 'all' | 'pathspec' | 'none' = 'none') {
|
||||
const input = getInput('add')
|
||||
if (!input) return []
|
||||
const input = getInput('add');
|
||||
if (!input) return [];
|
||||
|
||||
const parsed = parseInputArray(input)
|
||||
const res: (string | void)[] = []
|
||||
const parsed = parseInputArray(input);
|
||||
const res: (string | 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)
|
||||
.add(matchGitArgs(args), (err, data) =>
|
||||
log(ignoreErrors === 'all' ? null : err, data)
|
||||
)
|
||||
.catch((e: Error) => {
|
||||
// if I should ignore every error, return
|
||||
if (ignoreErrors == 'all') 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
|
||||
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
|
||||
);
|
||||
if (peh === 'exitImmediately') throw err;
|
||||
if (peh === 'exitAtEnd') exitErrors.push(err);
|
||||
} else throw e;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return res
|
||||
return res;
|
||||
}
|
||||
|
||||
async function remove(
|
||||
ignoreErrors: 'all' | 'pathspec' | 'none' = 'none'
|
||||
): Promise<(void | Response<void>)[]> {
|
||||
const input = getInput('remove')
|
||||
if (!input) return []
|
||||
const input = getInput('remove');
|
||||
if (!input) return [];
|
||||
|
||||
const parsed = parseInputArray(input)
|
||||
const res: (void | Response<void>)[] = []
|
||||
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)
|
||||
.rm(matchGitArgs(args), (e, d) =>
|
||||
log(ignoreErrors === 'all' ? null : e, d)
|
||||
)
|
||||
.catch((e: Error) => {
|
||||
// if I should ignore every error, return
|
||||
if (ignoreErrors == 'all') 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
|
||||
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
|
||||
);
|
||||
if (peh === 'exitImmediately') throw err;
|
||||
if (peh === 'exitAtEnd') exitErrors.push(err);
|
||||
} else throw e;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return res
|
||||
return res;
|
||||
}
|
||||
|
||||
88
src/util.ts
88
src/util.ts
@@ -1,42 +1,43 @@
|
||||
import { parseArgsStringToArgv } from 'string-argv'
|
||||
import * as core from '@actions/core'
|
||||
import YAML from 'js-yaml'
|
||||
import { Toolkit } from 'actions-toolkit'
|
||||
import fs from 'fs'
|
||||
import { input, output } from './io'
|
||||
import {parseArgsStringToArgv} from 'string-argv';
|
||||
import * as core from '@actions/core';
|
||||
import * as YAML from 'js-yaml';
|
||||
import {Toolkit} from 'actions-toolkit';
|
||||
import * as fs from 'fs';
|
||||
import {input, output} from './io';
|
||||
|
||||
type RecordOf<T extends string> = Record<T, string | undefined>
|
||||
type RecordOf<T extends string> = Record<T, string | undefined>;
|
||||
export const tools = new Toolkit<RecordOf<input>, RecordOf<output>>({
|
||||
secrets: [
|
||||
'GITHUB_EVENT_PATH',
|
||||
'GITHUB_EVENT_NAME',
|
||||
'GITHUB_REF',
|
||||
'GITHUB_ACTOR'
|
||||
]
|
||||
})
|
||||
'GITHUB_ACTOR',
|
||||
],
|
||||
});
|
||||
|
||||
export async function getUserInfo(username?: string) {
|
||||
if (!username) return undefined
|
||||
if (!username) return undefined;
|
||||
|
||||
const res = await tools.github.users.getByUsername({ username })
|
||||
const res = await tools.github.users.getByUsername({username});
|
||||
|
||||
core.debug(
|
||||
`Fetched github actor from the API: ${JSON.stringify(res?.data, null, 2)}`
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
name: res?.data?.name,
|
||||
email: res?.data?.email
|
||||
}
|
||||
email: res?.data?.email,
|
||||
};
|
||||
}
|
||||
|
||||
export function log(err: any | Error, data?: any) {
|
||||
if (data) console.log(data)
|
||||
if (err) core.error(err)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function log(err: any, data?: any) {
|
||||
if (data) console.log(data);
|
||||
if (err) core.error(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches the given string to an array of arguments.
|
||||
* Matches the given string to an array of arguments.
|
||||
* The parsing is made by `string-argv`: if your way of using argument is not supported, the issue is theirs!
|
||||
* {@link https://www.npm.im/string-argv}
|
||||
* @example
|
||||
@@ -61,11 +62,11 @@ export function log(err: any | Error, data?: any) {
|
||||
* @returns An array, if there's no match it'll be empty
|
||||
*/
|
||||
export function matchGitArgs(string: string) {
|
||||
const parsed = parseArgsStringToArgv(string)
|
||||
const parsed = parseArgsStringToArgv(string);
|
||||
core.debug(`Git args parsed:
|
||||
- Original: ${string}
|
||||
- Parsed: ${JSON.stringify(parsed)}`)
|
||||
return parsed
|
||||
- Parsed: ${JSON.stringify(parsed)}`);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,45 +74,38 @@ export function matchGitArgs(string: string) {
|
||||
* If both fail, it returns an array containing the input value as its only element
|
||||
*/
|
||||
export function parseInputArray(input: string): string[] {
|
||||
core.debug(`Parsing input array: ${input}`);
|
||||
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
|
||||
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 {}
|
||||
} catch {} // eslint-disable-line no-empty
|
||||
|
||||
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
|
||||
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 {}
|
||||
} catch {} // eslint-disable-line no-empty
|
||||
|
||||
core.debug('Input parsed as single string')
|
||||
return [input]
|
||||
core.debug('Input parsed as single string');
|
||||
return [input];
|
||||
}
|
||||
|
||||
export function readJSON(filePath: string) {
|
||||
let fileContent: string
|
||||
let fileContent: string;
|
||||
try {
|
||||
fileContent = fs.readFileSync(filePath, { encoding: 'utf8' })
|
||||
fileContent = fs.readFileSync(filePath, {encoding: 'utf8'});
|
||||
} catch {
|
||||
throw `Couldn't read file. File path: ${filePath}`
|
||||
throw `Couldn't read file. File path: ${filePath}`;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(fileContent)
|
||||
return JSON.parse(fileContent);
|
||||
} catch {
|
||||
throw `Couldn't parse file to JSON. File path: ${filePath}`
|
||||
throw `Couldn't parse file to JSON. File path: ${filePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +1,12 @@
|
||||
{
|
||||
"extends": "./node_modules/gts/tsconfig-google.json",
|
||||
"compilerOptions": {
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
"outDir": "./build", /* Redirect output structure to the directory. */
|
||||
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
"rootDir": "./src",
|
||||
"outDir": "./lib",
|
||||
"declaration": false
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"**/*.test.ts",
|
||||
"scripts"
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"test/**/*.ts"
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user