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:
Federico Grandi
2024-03-26 14:41:25 +01:00
committed by GitHub
parent 95ee72e80d
commit cb9365b122
13 changed files with 2092 additions and 1351 deletions

8
.editorconfig Normal file
View 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
View File

@@ -0,0 +1 @@
lib/

View File

@@ -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
View File

@@ -0,0 +1,3 @@
{
"extends": "./node_modules/gts/"
}

View File

@@ -1,7 +0,0 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "none"
}

3
.prettierrc.js Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
...require('gts/.prettierrc.json')
}

2
lib/index.js generated

File diff suppressed because one or more lines are too long

2758
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,12 +5,15 @@
"description": "Add & commit files from a path directly from GitHub Actions", "description": "Add & commit files from a path directly from GitHub Actions",
"main": "lib/index.js", "main": "lib/index.js",
"scripts": { "scripts": {
"prebuild": "npm run clean",
"build": "ncc build src/main.ts --minify --out lib", "build": "ncc build src/main.ts --minify --out lib",
"watch": "ncc build src/main.ts --watch --out lib", "lint": "gts lint",
"lint": "eslint --ext .ts src",
"lint:fix": "eslint --ext .ts --fix src",
"prepare": "husky", "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": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
@@ -21,17 +24,13 @@
}, },
"devDependencies": { "devDependencies": {
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
"@types/node": "^20.11.6", "@types/node": "20.8.2",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vercel/ncc": "^0.38.1", "@vercel/ncc": "^0.38.1",
"all-contributors-cli": "^6.26.1", "all-contributors-cli": "^6.26.1",
"eslint": "^8.48.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3", "gts": "^5.2.0",
"husky": "^9.0.11", "husky": "^9.0.11",
"prettier": "^3.2.5", "typescript": "~5.2.0"
"typescript": "^5.3.3"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"

204
src/io.ts
View File

@@ -1,38 +1,38 @@
import * as core from '@actions/core' import * as core from '@actions/core';
import { getUserInfo, parseInputArray } from './util' import {getUserInfo, parseInputArray} from './util';
interface InputTypes { export interface InputTypes {
add: string add: string;
author_name: string author_name: string;
author_email: string author_email: string;
commit: string | undefined commit: string | undefined;
committer_name: string committer_name: string;
committer_email: string committer_email: string;
cwd: string cwd: string;
default_author: 'github_actor' | 'user_info' | 'github_actions' default_author: 'github_actor' | 'user_info' | 'github_actions';
fetch: string fetch: string;
message: string message: string;
new_branch: string | undefined new_branch: string | undefined;
pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd' pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd';
pull: string | undefined pull: string | undefined;
push: string push: string;
remove: string | undefined remove: string | undefined;
tag: string | undefined tag: string | undefined;
tag_push: 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 { export interface OutputTypes {
committed: 'true' | 'false' committed: 'true' | 'false';
commit_long_sha: string | undefined commit_long_sha: string | undefined;
commit_sha: string | undefined commit_sha: string | undefined;
pushed: 'true' | 'false' pushed: 'true' | 'false';
tagged: 'true' | 'false' tagged: 'true' | 'false';
tag_pushed: 'true' | 'false' tag_pushed: 'true' | 'false';
} }
export type output = keyof OutputTypes export type output = keyof OutputTypes;
export const outputs: OutputTypes = { export const outputs: OutputTypes = {
committed: 'false', committed: 'false',
@@ -40,81 +40,82 @@ export const outputs: OutputTypes = {
commit_sha: undefined, commit_sha: undefined,
pushed: 'false', pushed: 'false',
tagged: 'false', tagged: 'false',
tag_pushed: 'false' tag_pushed: 'false',
} };
// Setup default output values // 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>( export function getInput<T extends input>(
name: T, name: T,
parseAsBool?: false parseAsBool?: false
): InputTypes[T] ): InputTypes[T];
export function getInput<T extends input>( export function getInput<T extends input>(
name: T, name: T,
parseAsBool = false parseAsBool = false
): InputTypes[T] | boolean { ): InputTypes[T] | boolean {
if (parseAsBool) return core.getBooleanInput(name) if (parseAsBool) return core.getBooleanInput(name);
// @ts-expect-error return core.getInput(name) as InputTypes[T];
return core.getInput(name)
} }
export function setOutput<T extends output>(name: T, value: OutputTypes[T]) { export function setOutput<T extends output>(name: T, value: OutputTypes[T]) {
core.debug(`Setting output: ${name}=${value}`) core.debug(`Setting output: ${name}=${value}`);
outputs[name] = value outputs[name] = value;
core.setOutput(name, value) core.setOutput(name, value);
} }
export function logOutputs() { export function logOutputs() {
core.startGroup('Outputs') core.startGroup('Outputs');
for (const key in 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() { export async function checkInputs() {
function setInput(input: input, value: string | undefined) { function setInput(input: input, value: string | undefined) {
if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value) if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value);
else return delete process.env[`INPUT_${input.toUpperCase()}`] else return delete process.env[`INPUT_${input.toUpperCase()}`];
} }
function setDefault(input: input, value: string) { function setDefault(input: input, value: string) {
if (!getInput(input)) setInput(input, value) if (!getInput(input)) setInput(input, value);
return getInput(input) return getInput(input);
} }
// #region add, remove // #region add, remove
if (!getInput('add') && !getInput('remove')) if (!getInput('add') && !getInput('remove'))
throw new Error( throw new Error(
"Both 'add' and 'remove' are empty, the action has nothing to do." "Both 'add' and 'remove' are empty, the action has nothing to do."
) );
if (getInput('add')) { if (getInput('add')) {
const parsed = parseInputArray(getInput('add')) const parsed = parseInputArray(getInput('add'));
if (parsed.length == 1) if (parsed.length === 1)
core.info('Add input parsed as single string, running 1 git add command.') core.info(
'Add input parsed as single string, running 1 git add command.'
);
else if (parsed.length > 1) else if (parsed.length > 1)
core.info( core.info(
`Add input parsed as string array, running ${parsed.length} git add commands.` `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')) { if (getInput('remove')) {
const parsed = parseInputArray(getInput('remove') || '') const parsed = parseInputArray(getInput('remove') || '');
if (parsed.length == 1) if (parsed.length === 1)
core.info( core.info(
'Remove input parsed as single string, running 1 git rm command.' 'Remove input parsed as single string, running 1 git rm command.'
) );
else if (parsed.length > 1) else if (parsed.length > 1)
core.info( core.info(
`Remove input parsed as string array, running ${parsed.length} git rm commands.` `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 // #endregion
// #region default_author // #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'))) if (!default_author_valid.includes(getInput('default_author')))
throw new Error( throw new Error(
`'${getInput( `'${getInput(
@@ -122,71 +123,74 @@ export async function checkInputs() {
)}' is not a valid value for default_author. Valid values: ${default_author_valid.join( )}' is not a valid value for default_author. Valid values: ${default_author_valid.join(
', ' ', '
)}` )}`
) );
// #endregion // #endregion
// #region fetch // #region fetch
if (getInput('fetch')) { if (getInput('fetch')) {
let value: string | boolean let value: string | boolean;
try { try {
value = getInput('fetch', true) value = getInput('fetch', true);
} catch { } 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 // #endregion
// #region author_name, author_email // #region author_name, author_email
let name, email let name, email;
switch (getInput('default_author')) { switch (getInput('default_author')) {
case 'github_actor': { case 'github_actor': {
name = process.env.GITHUB_ACTOR name = process.env.GITHUB_ACTOR ?? '';
email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com` email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`;
break break;
} }
case 'user_info': { case 'user_info': {
if (!getInput('author_name') || !getInput('author_email')) { 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) 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) if (!res?.email)
core.warning( core.warning(
"Couldn't fetch author email, filling with github_actor." "Couldn't fetch author email, filling with github_actor."
) );
res?.name && (name = res?.name) res?.name && (name = res?.name);
res?.email && (email = res.email) res?.email && (email = res.email);
if (name && email) break if (name && email) break;
} }
!name && (name = process.env.GITHUB_ACTOR) !name && (name = process.env.GITHUB_ACTOR ?? '');
!email && (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`) !email &&
break (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`);
break;
} }
case 'github_actions': { case 'github_actions': {
name = 'github-actions' name = 'github-actions';
email = '41898282+github-actions[bot]@users.noreply.github.com' email = '41898282+github-actions[bot]@users.noreply.github.com';
break break;
} }
default: default:
throw new Error( throw new Error(
'This should not happen, please contact the author of this action. (checkInputs.author)' 'This should not happen, please contact the author of this action. (checkInputs.author)'
) );
} }
setDefault('author_name', name) setDefault('author_name', name);
setDefault('author_email', email) setDefault('author_email', email);
core.info( core.info(
`> Using '${getInput('author_name')} <${getInput( `> Using '${getInput('author_name')} <${getInput(
'author_email' 'author_email'
)}>' as author.` )}>' as author.`
) );
// #endregion // #endregion
// #region committer_name, committer_email // #region committer_name, committer_email
@@ -199,25 +203,25 @@ export async function checkInputs() {
getInput('committer_email') || getInput('committer_email') ||
getInput('author_email') + ' [from author info]' getInput('author_email') + ' [from author info]'
}>` }>`
) );
setDefault('committer_name', getInput('author_name')) setDefault('committer_name', getInput('author_name'));
setDefault('committer_email', getInput('author_email')) setDefault('committer_email', getInput('author_email'));
core.debug( core.debug(
`Committer: ${getInput('committer_name')} <${getInput('committer_email')}>` `Committer: ${getInput('committer_name')} <${getInput('committer_email')}>`
) );
// #endregion // #endregion
// #region message // #region message
setDefault( setDefault(
'message', 'message',
`Commit from GitHub Actions (${process.env.GITHUB_WORKFLOW})` `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 // #endregion
// #region pathspec_error_handling // #region pathspec_error_handling
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd'] const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd'];
if (!peh_valid.includes(getInput('pathspec_error_handling'))) if (!peh_valid.includes(getInput('pathspec_error_handling')))
throw new Error( throw new Error(
`"${getInput( `"${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( )}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join(
', ' ', '
)}` )}`
) );
// #endregion // #endregion
// #region pull // #region pull
if (getInput('pull') == 'NO-PULL') if (getInput('pull') === 'NO-PULL')
core.warning( 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." "`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 // #endregion
// #region push // #region push
if (getInput('push')) { if (getInput('push')) {
// It has to be either 'true', 'false', or any other string (use as arguments) // It has to be either 'true', 'false', or any other string (use as arguments)
let value: string | boolean let value: string | boolean;
try { try {
value = getInput('push', true) value = getInput('push', true);
} catch { } 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 // #endregion
@@ -254,6 +258,6 @@ export async function checkInputs() {
if (!getInput('github_token')) if (!getInput('github_token'))
core.warning( core.warning(
'No github_token has been detected, the action may fail if it needs to use the API' 'No github_token has been detected, the action may fail if it needs to use the API'
) );
// #endregion // #endregion
} }

View File

@@ -1,47 +1,47 @@
import * as core from '@actions/core' import * as core from '@actions/core';
import path from 'path' import * as path from 'path';
import simpleGit, { Response } from 'simple-git' import simpleGit, {Response} from 'simple-git';
import { checkInputs, getInput, logOutputs, setOutput } from './io' import {checkInputs, getInput, logOutputs, setOutput} from './io';
import { log, matchGitArgs, parseInputArray } from './util' import {log, matchGitArgs, parseInputArray} from './util';
const baseDir = path.join(process.cwd(), getInput('cwd') || '') const baseDir = path.join(process.cwd(), getInput('cwd') || '');
const git = simpleGit({ baseDir }) const git = simpleGit({baseDir});
const exitErrors: Error[] = [] const exitErrors: Error[] = [];
core.info(`Running in ${baseDir}`) core.info(`Running in ${baseDir}`);
;(async () => { (async () => {
await checkInputs() await checkInputs();
core.startGroup('Internal logs') core.startGroup('Internal logs');
core.info('> Staging files...') core.info('> Staging files...');
const ignoreErrors = const ignoreErrors =
getInput('pathspec_error_handling') == 'ignore' ? 'pathspec' : 'none' getInput('pathspec_error_handling') === 'ignore' ? 'pathspec' : 'none';
if (getInput('add')) { if (getInput('add')) {
core.info('> Adding files...') core.info('> Adding files...');
await add(ignoreErrors) await add(ignoreErrors);
} else core.info('> No files to add.') } else core.info('> No files to add.');
if (getInput('remove')) { if (getInput('remove')) {
core.info('> Removing files...') core.info('> Removing files...');
await remove(ignoreErrors) await remove(ignoreErrors);
} else core.info('> No files to remove.') } else core.info('> No files to remove.');
core.info('> Checking for uncommitted changes in the git working tree...') core.info('> Checking for uncommitted changes in the git working tree...');
const changedFiles = (await git.diffSummary(['--cached'])).files.length const changedFiles = (await git.diffSummary(['--cached'])).files.length;
// continue if there are any changes or if the allow-empty commit argument is included // continue if there are any changes or if the allow-empty commit argument is included
if ( if (
changedFiles > 0 || changedFiles > 0 ||
matchGitArgs(getInput('commit') || '').includes('--allow-empty') matchGitArgs(getInput('commit') || '').includes('--allow-empty')
) { ) {
core.info(`> Found ${changedFiles} changed files.`) core.info(`> Found ${changedFiles} changed files.`);
core.debug( core.debug(
`--allow-empty argument detected: ${matchGitArgs( `--allow-empty argument detected: ${matchGitArgs(
getInput('commit') || '' getInput('commit') || ''
).includes('--allow-empty')}` ).includes('--allow-empty')}`
) );
await git await git
.addConfig('user.email', getInput('author_email'), undefined, log) .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.email', getInput('author_email'), undefined, log)
.addConfig('author.name', getInput('author_name'), undefined, log) .addConfig('author.name', getInput('author_name'), undefined, log)
.addConfig('committer.email', getInput('committer_email'), 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( core.debug(
'> Current git config\n' + '> Current git config\n' +
JSON.stringify((await git.listConfig()).all, null, 2) JSON.stringify((await git.listConfig()).all, null, 2)
) );
let fetchOption: string | boolean let fetchOption: string | boolean;
try { try {
fetchOption = getInput('fetch', true) fetchOption = getInput('fetch', true);
} catch { } catch {
fetchOption = getInput('fetch') fetchOption = getInput('fetch');
} }
if (fetchOption) { if (fetchOption) {
core.info('> Fetching repo...') core.info('> Fetching repo...');
await git.fetch( await git.fetch(
matchGitArgs(fetchOption === true ? '' : fetchOption), matchGitArgs(fetchOption === true ? '' : fetchOption),
log 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) { if (targetBranch) {
core.info('> Checking-out branch...') core.info('> Checking-out branch...');
if (!fetchOption) if (!fetchOption)
core.warning( 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.' '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 await git
.checkout(targetBranch) .checkout(targetBranch)
.then(() => { .then(() => {
log(undefined, `'${targetBranch}' branch already existed.`) log(undefined, `'${targetBranch}' branch already existed.`);
}) })
.catch(() => { .catch(() => {
log(undefined, `Creating '${targetBranch}' branch.`) log(undefined, `Creating '${targetBranch}' branch.`);
return git.checkoutLocalBranch(targetBranch, log) return git.checkoutLocalBranch(targetBranch, log);
}) });
} }
const pullOption = getInput('pull') const pullOption = getInput('pull');
if (pullOption) { if (pullOption) {
core.info('> Pulling from remote...') core.info('> Pulling from remote...');
core.debug(`Current git pull arguments: ${pullOption}`) core.debug(`Current git pull arguments: ${pullOption}`);
await git await git
.fetch(undefined, log) .fetch(undefined, log)
.pull(undefined, undefined, matchGitArgs(pullOption), log) .pull(undefined, undefined, matchGitArgs(pullOption), log);
core.info('> Checking for conflicts...') core.info('> Checking for conflicts...');
const status = await git.status(undefined, log) const status = await git.status(undefined, log);
if (!status.conflicted.length) { if (!status.conflicted.length) {
core.info('> No conflicts found.') core.info('> No conflicts found.');
core.info('> Re-staging files...') core.info('> Re-staging files...');
if (getInput('add')) await add(ignoreErrors) if (getInput('add')) await add(ignoreErrors);
if (getInput('remove')) await remove(ignoreErrors) if (getInput('remove')) await remove(ignoreErrors);
} else } else
throw new Error( throw new Error(
`There are ${ `There are ${
status.conflicted.length status.conflicted.length
} conflicting files: ${status.conflicted.join(', ')}` } 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 await git
.commit(getInput('message'), matchGitArgs(getInput('commit') || '')) .commit(getInput('message'), matchGitArgs(getInput('commit') || ''))
.then(async (data) => { .then(async data => {
log(undefined, data) log(undefined, data);
setOutput('committed', 'true') setOutput('committed', 'true');
setOutput('commit_long_sha', data.commit) setOutput('commit_long_sha', data.commit);
setOutput('commit_sha', data.commit.substring(0, 7)) setOutput('commit_sha', data.commit.substring(0, 7));
}) })
.catch((err) => core.setFailed(err)) .catch(err => core.setFailed(err));
if (getInput('tag')) { if (getInput('tag')) {
core.info('> Tagging commit...') core.info('> Tagging commit...');
if (!fetchOption) if (!fetchOption)
core.warning( 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.' '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 await git
.tag(matchGitArgs(getInput('tag') || ''), (err, data?) => { .tag(matchGitArgs(getInput('tag') || ''), (err, data?) => {
if (data) setOutput('tagged', 'true') if (data) setOutput('tagged', 'true');
return log(err, data) return log(err, data);
}) })
.then((data) => { .then(data => {
setOutput('tagged', 'true') setOutput('tagged', 'true');
return log(null, data) return log(null, data);
}) })
.catch((err) => core.setFailed(err)) .catch(err => core.setFailed(err));
} else core.info('> No tag info provided.') } else core.info('> No tag info provided.');
let pushOption: string | boolean let pushOption: string | boolean;
try { try {
pushOption = getInput('push', true) pushOption = getInput('push', true);
} catch { } catch {
pushOption = getInput('push') pushOption = getInput('push');
} }
if (pushOption) { if (pushOption) {
// If the options is `true | string`... // If the options is `true | string`...
core.info('> Pushing commit to repo...') core.info('> Pushing commit to repo...');
if (pushOption === true) { if (pushOption === true) {
core.debug( core.debug(
`Running: git push origin ${ `Running: git push origin ${
getInput('new_branch') || '' getInput('new_branch') || ''
} --set-upstream` } --set-upstream`
) );
await git.push( await git.push(
'origin', 'origin',
getInput('new_branch'), getInput('new_branch'),
{ '--set-upstream': null }, {'--set-upstream': null},
(err, data?) => { (err, data?) => {
if (data) setOutput('pushed', 'true') if (data) setOutput('pushed', 'true');
return log(err, data) return log(err, data);
} }
) );
} else { } else {
core.debug(`Running: git push ${pushOption}`) core.debug(`Running: git push ${pushOption}`);
await git.push( await git.push(
undefined, undefined,
undefined, undefined,
matchGitArgs(pushOption), matchGitArgs(pushOption),
(err, data?) => { (err, data?) => {
if (data) setOutput('pushed', 'true') if (data) setOutput('pushed', 'true');
return log(err, data) return log(err, data);
} }
) );
} }
if (getInput('tag')) { if (getInput('tag')) {
core.info('> Pushing tags to repo...') core.info('> Pushing tags to repo...');
await git await git
.pushTags('origin', matchGitArgs(getInput('tag_push') || '')) .pushTags('origin', matchGitArgs(getInput('tag_push') || ''))
.then((data) => { .then(data => {
setOutput('tag_pushed', 'true') setOutput('tag_pushed', 'true');
return log(null, data) return log(null, data);
}) })
.catch((err) => core.setFailed(err)) .catch(err => core.setFailed(err));
} else core.info('> No tags to push.') } else core.info('> No tags to push.');
} else core.info('> Not pushing anything.') } else core.info('> Not pushing anything.');
core.endGroup() core.endGroup();
core.info('> Task completed.') core.info('> Task completed.');
} else { } else {
core.endGroup() core.endGroup();
core.info('> Working tree clean. Nothing to commit.') core.info('> Working tree clean. Nothing to commit.');
} }
})() })()
.then(() => { .then(() => {
// Check for exit errors // Check for exit errors
if (exitErrors.length == 1) throw exitErrors[0] if (exitErrors.length === 1) throw exitErrors[0];
else if (exitErrors.length > 1) { else if (exitErrors.length > 1) {
exitErrors.forEach((e) => core.error(e)) exitErrors.forEach(e => core.error(e));
throw 'There have been multiple runtime errors.' throw 'There have been multiple runtime errors.';
} }
}) })
.then(logOutputs) .then(logOutputs)
.catch((e) => { .catch(e => {
core.endGroup() core.endGroup();
logOutputs() logOutputs();
core.setFailed(e) core.setFailed(e);
}) });
async function add(ignoreErrors: 'all' | 'pathspec' | 'none' = 'none') { async function add(ignoreErrors: 'all' | 'pathspec' | 'none' = 'none') {
const input = getInput('add') const input = getInput('add');
if (!input) return [] if (!input) return [];
const parsed = parseInputArray(input) const parsed = parseInputArray(input);
const res: (string | void)[] = [] const res: (string | void)[] = [];
for (const args of parsed) { for (const args of parsed) {
res.push( res.push(
// Push the result of every git command (which are executed in order) to the array // 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 // If any of them fails, the whole function will return a Promise rejection
await git await git
.add(matchGitArgs(args), (err: any, data?: any) => .add(matchGitArgs(args), (err, data) =>
log(ignoreErrors == 'all' ? null : err, data) log(ignoreErrors === 'all' ? null : err, data)
) )
.catch((e: Error) => { .catch((e: Error) => {
// if I should ignore every error, return // if I should ignore every error, return
if (ignoreErrors == 'all') return if (ignoreErrors === 'all') return;
// if it's a pathspec error... // if it's a pathspec error...
if ( if (
e.message.includes('fatal: pathspec') && e.message.includes('fatal: pathspec') &&
e.message.includes('did not match any files') e.message.includes('did not match any files')
) { ) {
if (ignoreErrors == 'pathspec') return if (ignoreErrors === 'pathspec') return;
const peh = getInput('pathspec_error_handling'), const peh = getInput('pathspec_error_handling'),
err = new Error( err = new Error(
`Add command did not match any file: git add ${args}` `Add command did not match any file: git add ${args}`
) );
if (peh == 'exitImmediately') throw err if (peh === 'exitImmediately') throw err;
if (peh == 'exitAtEnd') exitErrors.push(err) if (peh === 'exitAtEnd') exitErrors.push(err);
} else throw e } else throw e;
}) })
) );
} }
return res return res;
} }
async function remove( async function remove(
ignoreErrors: 'all' | 'pathspec' | 'none' = 'none' ignoreErrors: 'all' | 'pathspec' | 'none' = 'none'
): Promise<(void | Response<void>)[]> { ): Promise<(void | Response<void>)[]> {
const input = getInput('remove') const input = getInput('remove');
if (!input) return [] if (!input) return [];
const parsed = parseInputArray(input) const parsed = parseInputArray(input);
const res: (void | Response<void>)[] = [] const res: (void | Response<void>)[] = [];
for (const args of parsed) { for (const args of parsed) {
res.push( res.push(
// Push the result of every git command (which are executed in order) to the array // 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 // If any of them fails, the whole function will return a Promise rejection
await git await git
.rm(matchGitArgs(args), (e: any, d?: any) => .rm(matchGitArgs(args), (e, d) =>
log(ignoreErrors == 'all' ? null : e, d) log(ignoreErrors === 'all' ? null : e, d)
) )
.catch((e: Error) => { .catch((e: Error) => {
// if I should ignore every error, return // if I should ignore every error, return
if (ignoreErrors == 'all') return if (ignoreErrors === 'all') return;
// if it's a pathspec error... // if it's a pathspec error...
if ( if (
e.message.includes('fatal: pathspec') && e.message.includes('fatal: pathspec') &&
e.message.includes('did not match any files') e.message.includes('did not match any files')
) { ) {
if (ignoreErrors == 'pathspec') return if (ignoreErrors === 'pathspec') return;
const peh = getInput('pathspec_error_handling'), const peh = getInput('pathspec_error_handling'),
err = new Error( err = new Error(
`Remove command did not match any file:\n git rm ${args}` `Remove command did not match any file:\n git rm ${args}`
) );
if (peh == 'exitImmediately') throw err if (peh === 'exitImmediately') throw err;
if (peh == 'exitAtEnd') exitErrors.push(err) if (peh === 'exitAtEnd') exitErrors.push(err);
} else throw e } else throw e;
}) })
) );
} }
return res return res;
} }

View File

@@ -1,38 +1,39 @@
import { parseArgsStringToArgv } from 'string-argv' import {parseArgsStringToArgv} from 'string-argv';
import * as core from '@actions/core' import * as core from '@actions/core';
import YAML from 'js-yaml' import * as YAML from 'js-yaml';
import { Toolkit } from 'actions-toolkit' import {Toolkit} from 'actions-toolkit';
import fs from 'fs' import * as fs from 'fs';
import { input, output } from './io' 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>>({ export const tools = new Toolkit<RecordOf<input>, RecordOf<output>>({
secrets: [ secrets: [
'GITHUB_EVENT_PATH', 'GITHUB_EVENT_PATH',
'GITHUB_EVENT_NAME', 'GITHUB_EVENT_NAME',
'GITHUB_REF', 'GITHUB_REF',
'GITHUB_ACTOR' 'GITHUB_ACTOR',
] ],
}) });
export async function getUserInfo(username?: string) { 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( core.debug(
`Fetched github actor from the API: ${JSON.stringify(res?.data, null, 2)}` `Fetched github actor from the API: ${JSON.stringify(res?.data, null, 2)}`
) );
return { return {
name: res?.data?.name, name: res?.data?.name,
email: res?.data?.email email: res?.data?.email,
} };
} }
export function log(err: any | Error, data?: any) { // eslint-disable-next-line @typescript-eslint/no-explicit-any
if (data) console.log(data) export function log(err: any, data?: any) {
if (err) core.error(err) if (data) console.log(data);
if (err) core.error(err);
} }
/** /**
@@ -61,11 +62,11 @@ export function log(err: any | Error, data?: any) {
* @returns An array, if there's no match it'll be empty * @returns An array, if there's no match it'll be empty
*/ */
export function matchGitArgs(string: string) { export function matchGitArgs(string: string) {
const parsed = parseArgsStringToArgv(string) const parsed = parseArgsStringToArgv(string);
core.debug(`Git args parsed: core.debug(`Git args parsed:
- Original: ${string} - Original: ${string}
- Parsed: ${JSON.stringify(parsed)}`) - Parsed: ${JSON.stringify(parsed)}`);
return 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 * If both fail, it returns an array containing the input value as its only element
*/ */
export function parseInputArray(input: string): string[] { export function parseInputArray(input: string): string[] {
core.debug(`Parsing input array: ${input}`);
try { try {
const json = JSON.parse(input) const json = JSON.parse(input);
if ( if (json && Array.isArray(json) && json.every(e => typeof e === 'string')) {
json && core.debug(`Input parsed as JSON array of length ${json.length}`);
Array.isArray(json) && return 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 { try {
const yaml = YAML.load(input) const yaml = YAML.load(input);
if ( if (yaml && Array.isArray(yaml) && yaml.every(e => typeof e === 'string')) {
yaml && core.debug(`Input parsed as YAML array of length ${yaml.length}`);
Array.isArray(yaml) && return 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') core.debug('Input parsed as single string');
return [input] return [input];
} }
export function readJSON(filePath: string) { export function readJSON(filePath: string) {
let fileContent: string let fileContent: string;
try { try {
fileContent = fs.readFileSync(filePath, { encoding: 'utf8' }) fileContent = fs.readFileSync(filePath, {encoding: 'utf8'});
} catch { } catch {
throw `Couldn't read file. File path: ${filePath}` throw `Couldn't read file. File path: ${filePath}`;
} }
try { try {
return JSON.parse(fileContent) return JSON.parse(fileContent);
} catch { } catch {
throw `Couldn't parse file to JSON. File path: ${filePath}` throw `Couldn't parse file to JSON. File path: ${filePath}`;
} }
} }

View File

@@ -1,62 +1,12 @@
{ {
"extends": "./node_modules/gts/tsconfig-google.json",
"compilerOptions": { "compilerOptions": {
/* Basic Options */ "rootDir": "./src",
// "incremental": true, /* Enable incremental compilation */ "outDir": "./lib",
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "declaration": false
"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. */
}, },
"exclude": [ "include": [
"node_modules", "src/**/*.ts",
"**/*.test.ts", "test/**/*.ts"
"scripts"
] ]
} }