Merge pull request #96

added prettier
This commit is contained in:
Phil 2021-05-20 22:55:13 +02:00 committed by GitHub
commit 8d8758c76a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 108 additions and 79 deletions

10
.prettierrc Normal file
View File

@ -0,0 +1,10 @@
{
"printWidth": 120,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"quoteProps": "as-needed",
"trailingComma": "all",
"endOfLine": "lf",
"arrowParens": "always"
}

162
index.js
View File

@ -1,134 +1,146 @@
const { Toolkit } = require('actions-toolkit') const { Toolkit } = require('actions-toolkit');
const { execSync } = require('child_process') const { execSync } = require('child_process');
// Change working directory if user defined PACKAGEJSON_DIR // Change working directory if user defined PACKAGEJSON_DIR
if (process.env.PACKAGEJSON_DIR) { if (process.env.PACKAGEJSON_DIR) {
process.env.GITHUB_WORKSPACE = `${process.env.GITHUB_WORKSPACE}/${process.env.PACKAGEJSON_DIR}` process.env.GITHUB_WORKSPACE = `${process.env.GITHUB_WORKSPACE}/${process.env.PACKAGEJSON_DIR}`;
process.chdir(process.env.GITHUB_WORKSPACE) process.chdir(process.env.GITHUB_WORKSPACE);
} }
// Run your GitHub Action! // Run your GitHub Action!
Toolkit.run(async tools => { Toolkit.run(async (tools) => {
const pkg = tools.getPackageJSON() const pkg = tools.getPackageJSON();
const event = tools.context.payload const event = tools.context.payload;
if (!event.commits) { if (!event.commits) {
console.log('Couldn\'t find any commits in this event, incrementing patch version...') console.log("Couldn't find any commits in this event, incrementing patch version...");
} }
const messages = event.commits ? event.commits.map(commit => commit.message + '\n' + commit.body) : [] const messages = event.commits ? event.commits.map((commit) => commit.message + '\n' + commit.body) : [];
const commitMessage = process.env['INPUT_COMMIT-MESSAGE'] || 'ci: version bump to {{version}}' const commitMessage = process.env['INPUT_COMMIT-MESSAGE'] || 'ci: version bump to {{version}}';
console.log('messages:', messages) console.log('messages:', messages);
const commitMessageRegex = new RegExp(commitMessage.replace(/{{version}}/g, 'v\\d+\\.\\d+\\.\\d+'), 'ig'); const commitMessageRegex = new RegExp(commitMessage.replace(/{{version}}/g, 'v\\d+\\.\\d+\\.\\d+'), 'ig');
const isVersionBump = messages.find(message => commitMessageRegex.test(message)) !== undefined const isVersionBump = messages.find((message) => commitMessageRegex.test(message)) !== undefined;
if (isVersionBump) { if (isVersionBump) {
tools.exit.success('No action necessary!') tools.exit.success('No action necessary!');
return return;
} }
const majorWords = process.env['INPUT_MAJOR-WORDING'].split(',') const majorWords = process.env['INPUT_MAJOR-WORDING'].split(',');
const minorWords = process.env['INPUT_MINOR-WORDING'].split(',') const minorWords = process.env['INPUT_MINOR-WORDING'].split(',');
const preReleaseWords = process.env['INPUT_RC-WORDING'].split(',') const preReleaseWords = process.env['INPUT_RC-WORDING'].split(',');
// if patch words aren't specified, any commit message qualifies as a patch // if patch words aren't specified, any commit message qualifies as a patch
const patchWords = process.env['INPUT_PATCH-WORDING'] ? process.env['INPUT_PATCH-WORDING'].split(',') : null const patchWords = process.env['INPUT_PATCH-WORDING'] ? process.env['INPUT_PATCH-WORDING'].split(',') : null;
let version = process.env.INPUT_DEFAULT || 'patch' let version = process.env.INPUT_DEFAULT || 'patch';
let foundWord = null let foundWord = null;
let preid = process.env.INPUT_PREID; let preid = process.env.INPUT_PREID;
if (messages.some( if (
message => /^([a-zA-Z]+)(\(.+\))?(\!)\:/.test(message) || majorWords.some(word => message.includes(word)))) { messages.some(
version = 'major' (message) => /^([a-zA-Z]+)(\(.+\))?(\!)\:/.test(message) || majorWords.some((word) => message.includes(word)),
} else if (messages.some(message => minorWords.some(word => message.includes(word)))) { )
version = 'minor' ) {
} else if (messages.some(message => preReleaseWords.some(word => { version = 'major';
} else if (messages.some((message) => minorWords.some((word) => message.includes(word)))) {
version = 'minor';
} else if (
messages.some((message) =>
preReleaseWords.some((word) => {
if (message.includes(word)) { if (message.includes(word)) {
foundWord = word foundWord = word;
return true return true;
} else { } else {
return false return false;
} }
} }),
))) { )
preid = foundWord.split('-')[1] ) {
version = 'prerelease' preid = foundWord.split('-')[1];
version = 'prerelease';
} else if (Array.isArray(patchWords) && patchWords.length) { } else if (Array.isArray(patchWords) && patchWords.length) {
if (!messages.some(message => patchWords.some(word => message.includes(word)))) { if (!messages.some((message) => patchWords.some((word) => message.includes(word)))) {
version = null version = null;
} }
} }
if (version === 'prerelease' && preid) { if (version === 'prerelease' && preid) {
version = `${version} --preid=${preid}` version = `${version} --preid=${preid}`;
} }
if (version === null) { if (version === null) {
tools.exit.success('No version keywords found, skipping bump.') tools.exit.success('No version keywords found, skipping bump.');
return return;
} }
try { try {
const current = pkg.version.toString() const current = pkg.version.toString();
// set git user // set git user
await tools.runInWorkspace('git', await tools.runInWorkspace('git', [
['config', 'user.name', `"${process.env.GITHUB_USER || 'Automated Version Bump'}"`]) 'config',
await tools.runInWorkspace('git', 'user.name',
['config', 'user.email', `"${process.env.GITHUB_EMAIL || 'gh-action-bump-version@users.noreply.github.com'}"`]) `"${process.env.GITHUB_USER || 'Automated Version Bump'}"`,
]);
await tools.runInWorkspace('git', [
'config',
'user.email',
`"${process.env.GITHUB_EMAIL || 'gh-action-bump-version@users.noreply.github.com'}"`,
]);
let currentBranch = /refs\/[a-zA-Z]+\/(.*)/.exec(process.env.GITHUB_REF)[1] let currentBranch = /refs\/[a-zA-Z]+\/(.*)/.exec(process.env.GITHUB_REF)[1];
let isPullRequest = false let isPullRequest = false;
if (process.env.GITHUB_HEAD_REF) { if (process.env.GITHUB_HEAD_REF) {
// Comes from a pull request // Comes from a pull request
currentBranch = process.env.GITHUB_HEAD_REF currentBranch = process.env.GITHUB_HEAD_REF;
isPullRequest = true isPullRequest = true;
} }
if (process.env['INPUT_TARGET-BRANCH']) { if (process.env['INPUT_TARGET-BRANCH']) {
// We want to override the branch that we are pulling / pushing to // We want to override the branch that we are pulling / pushing to
currentBranch = process.env['INPUT_TARGET-BRANCH'] currentBranch = process.env['INPUT_TARGET-BRANCH'];
} }
console.log('currentBranch:', currentBranch) console.log('currentBranch:', currentBranch);
// do it in the current checked out github branch (DETACHED HEAD) // do it in the current checked out github branch (DETACHED HEAD)
// important for further usage of the package.json version // important for further usage of the package.json version
await tools.runInWorkspace('npm', await tools.runInWorkspace('npm', ['version', '--allow-same-version=true', '--git-tag-version=false', current]);
['version', '--allow-same-version=true', '--git-tag-version=false', current]) console.log('current:', current, '/', 'version:', version);
console.log('current:', current, '/', 'version:', version) let newVersion = execSync(`npm version --git-tag-version=false ${version}`).toString().trim();
let newVersion = execSync(`npm version --git-tag-version=false ${version}`).toString().trim() await tools.runInWorkspace('git', ['commit', '-a', '-m', commitMessage.replace(/{{version}}/g, newVersion)]);
await tools.runInWorkspace('git', ['commit', '-a', '-m', commitMessage.replace(/{{version}}/g, newVersion)])
// now go to the actual branch to perform the same versioning // now go to the actual branch to perform the same versioning
if (isPullRequest) { if (isPullRequest) {
// First fetch to get updated local version of branch // First fetch to get updated local version of branch
await tools.runInWorkspace('git', ['fetch']) await tools.runInWorkspace('git', ['fetch']);
} }
await tools.runInWorkspace('git', ['checkout', currentBranch]) await tools.runInWorkspace('git', ['checkout', currentBranch]);
await tools.runInWorkspace('npm', await tools.runInWorkspace('npm', ['version', '--allow-same-version=true', '--git-tag-version=false', current]);
['version', '--allow-same-version=true', '--git-tag-version=false', current]) console.log('current:', current, '/', 'version:', version);
console.log('current:', current, '/', 'version:', version) newVersion = execSync(`npm version --git-tag-version=false ${version}`).toString().trim();
newVersion = execSync(`npm version --git-tag-version=false ${version}`).toString().trim() newVersion = `${process.env['INPUT_TAG-PREFIX']}${newVersion}`;
newVersion = `${process.env['INPUT_TAG-PREFIX']}${newVersion}` console.log('new version:', newVersion);
console.log('new version:', newVersion) console.log(`::set-output name=newTag::${newVersion}`);
console.log(`::set-output name=newTag::${newVersion}`)
try { try {
// to support "actions/checkout@v1" // to support "actions/checkout@v1"
await tools.runInWorkspace('git', ['commit', '-a', '-m', commitMessage.replace(/{{version}}/g, newVersion)]) await tools.runInWorkspace('git', ['commit', '-a', '-m', commitMessage.replace(/{{version}}/g, newVersion)]);
} catch (e) { } catch (e) {
console.warn('git commit failed because you are using "actions/checkout@v2"; ' + console.warn(
'but that doesnt matter because you dont need that git commit, thats only for "actions/checkout@v1"') 'git commit failed because you are using "actions/checkout@v2"; ' +
'but that doesnt matter because you dont need that git commit, thats only for "actions/checkout@v1"',
);
} }
const remoteRepo = `https://${process.env.GITHUB_ACTOR}:${process.env.GITHUB_TOKEN}@github.com/${process.env.GITHUB_REPOSITORY}.git` const remoteRepo = `https://${process.env.GITHUB_ACTOR}:${process.env.GITHUB_TOKEN}@github.com/${process.env.GITHUB_REPOSITORY}.git`;
if (process.env['INPUT_SKIP-TAG'] !== 'true') { if (process.env['INPUT_SKIP-TAG'] !== 'true') {
await tools.runInWorkspace('git', ['tag', newVersion]) await tools.runInWorkspace('git', ['tag', newVersion]);
await tools.runInWorkspace('git', ['push', remoteRepo, '--follow-tags']) await tools.runInWorkspace('git', ['push', remoteRepo, '--follow-tags']);
await tools.runInWorkspace('git', ['push', remoteRepo, '--tags']) await tools.runInWorkspace('git', ['push', remoteRepo, '--tags']);
} else { } else {
await tools.runInWorkspace('git', ['push', remoteRepo]) await tools.runInWorkspace('git', ['push', remoteRepo]);
} }
} catch (e) { } catch (e) {
tools.log.fatal(e) tools.log.fatal(e);
tools.exit.failure('Failed to bump version') tools.exit.failure('Failed to bump version');
} }
tools.exit.success('Version bumped!') tools.exit.success('Version bumped!');
}) });

6
package-lock.json generated
View File

@ -5793,6 +5793,12 @@
"integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=",
"dev": true "dev": true
}, },
"prettier": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.3.0.tgz",
"integrity": "sha512-kXtO4s0Lz/DW/IJ9QdWhAf7/NmPWQXkFr/r/WkR3vyI+0v8amTDxiaQSLzs8NBlytfLWX/7uQUMIW677yLKl4w==",
"dev": true
},
"pretty-format": { "pretty-format": {
"version": "25.2.6", "version": "25.2.6",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-25.2.6.tgz", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-25.2.6.tgz",

View File

@ -24,6 +24,7 @@
}, },
"devDependencies": { "devDependencies": {
"jest": "^25.2.7", "jest": "^25.2.7",
"standard": "^14.3.3" "standard": "^14.3.3",
"prettier": "^2.3.0"
} }
} }