Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: package.json

- run: npm ci
- run: npm run test
- run: npm run check
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ __tests__/runner/*

# comment out in distribution branches
node_modules/
lib/
#lib/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nickkostov is this intentional? Seems that this is only meant for distribution branches.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't remember, frankly I need to revisit this sometime soon.
Don't want to make any promises.


# Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
Expand Down
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
/docs/
/*.json
/*.js
/*.cjs
/*.yml
/*.md
*.gitignore
*.prettierignore
LICENSE
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Bump version and push tag
id: tag_version
uses: mathieudutour/github-tag-action@v6.2
Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ inputs:
default: "false"

runs:
using: "node20"
using: "node24"
main: "lib/main.js"
branding:
icon: "git-merge"
Expand Down
1 change: 0 additions & 1 deletion docs/how-to-publish-new-version.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ $ git add .
$ git commit -a -m "prod dependencies"
$ git push
```

Your action is now published! :rocket:

See the [versioning documentation](https://github.com/actions/toolkit/blob/master/docs/action-versioning.md)
Expand Down
37 changes: 37 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
resolver: './jest.resolver.cjs',
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: {
module: 'commonjs',
moduleResolution: 'node',
esModuleInterop: true,
isolatedModules: true,
},
},
],
'^.+\\.js$': [
'ts-jest',
{
tsconfig: {
module: 'commonjs',
moduleResolution: 'node',
esModuleInterop: true,
allowJs: true,
isolatedModules: true,
},
},
],
},
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
transformIgnorePatterns: [],
verbose: true,
};
11 changes: 0 additions & 11 deletions jest.config.js

This file was deleted.

47 changes: 47 additions & 0 deletions jest.resolver.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const path = require('path');
const fs = require('fs');

function resolveViaExports(request) {
const name = request.startsWith('@')
? request.split('/').slice(0, 2).join('/')
: request.split('/')[0];

const pkgFile = path.join(
process.cwd(),
'node_modules',
name,
'package.json',
);
if (!fs.existsSync(pkgFile)) return null;

const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
if (!pkg.exports) return null;

const subpath = request === name ? '.' : '.' + request.slice(name.length);
const entry = pkg.exports[subpath];
if (!entry) return null;

const target =
typeof entry === 'string'
? entry
: entry.require || entry.default || entry.import;

return target ? path.join(process.cwd(), 'node_modules', name, target) : null;
}

module.exports = (request, options) => {
// Skip relative/absolute paths
if (request.startsWith('.') || request.startsWith('/')) {
return options.defaultResolver(request, options);
}

// Try default resolver first
try {
return options.defaultResolver(request, options);
} catch (e) {
// Default failed — try resolving via exports map
const resolved = resolveViaExports(request);
if (resolved) return resolved;
throw e;
}
};
162 changes: 162 additions & 0 deletions lib/action.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import * as core from '@actions/core';
import { gte, inc, parse, valid } from 'semver';
import { analyzeCommits } from '@semantic-release/commit-analyzer';
import { generateNotes } from '@semantic-release/release-notes-generator';
import { getBranchFromRef, isPr, getCommits, getLatestPrereleaseTag, getLatestTag, getValidTags, mapCustomReleaseRules, mergeWithDefaultChangelogRules, } from './utils.js';
import { createTag } from './github.js';
export default async function main() {
const defaultBump = core.getInput('default_bump');
const defaultPreReleaseBump = core.getInput('default_prerelease_bump');
const tagPrefix = core.getInput('tag_prefix');
const customTag = core.getInput('custom_tag');
const releaseBranches = core.getInput('release_branches');
const preReleaseBranches = core.getInput('pre_release_branches');
const appendToPreReleaseTag = core.getInput('append_to_pre_release_tag');
const createAnnotatedTag = /true/i.test(core.getInput('create_annotated_tag'));
const dryRun = core.getInput('dry_run');
const customReleaseRules = core.getInput('custom_release_rules');
const shouldFetchAllTags = core.getInput('fetch_all_tags');
const commitSha = core.getInput('commit_sha');
let mappedReleaseRules;
if (customReleaseRules) {
mappedReleaseRules = mapCustomReleaseRules(customReleaseRules);
}
const { GITHUB_REF, GITHUB_SHA } = process.env;
if (!GITHUB_REF) {
core.setFailed('Missing GITHUB_REF.');
return;
}
const commitRef = commitSha || GITHUB_SHA;
if (!commitRef) {
core.setFailed('Missing commit_sha or GITHUB_SHA.');
return;
}
const currentBranch = getBranchFromRef(GITHUB_REF);
const isReleaseBranch = releaseBranches
.split(',')
.some((branch) => currentBranch.match(branch));
const isPreReleaseBranch = preReleaseBranches
.split(',')
.some((branch) => currentBranch.match(branch));
const isPullRequest = isPr(GITHUB_REF);
const isPrerelease = !isReleaseBranch && !isPullRequest && isPreReleaseBranch;
// Sanitize identifier according to
// https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions
const identifier = (appendToPreReleaseTag ? appendToPreReleaseTag : currentBranch).replace(/[^a-zA-Z0-9-]/g, '-');
const prefixRegex = new RegExp(`^${tagPrefix}`);
const validTags = await getValidTags(prefixRegex, /true/i.test(shouldFetchAllTags));
const latestTag = getLatestTag(validTags, prefixRegex, tagPrefix);
const latestPrereleaseTag = getLatestPrereleaseTag(validTags, identifier, prefixRegex);
let commits;
let newVersion;
if (customTag) {
commits = await getCommits(latestTag.commit.sha, commitRef);
core.setOutput('release_type', 'custom');
newVersion = customTag;
}
else {
let previousTag;
let previousVersion;
if (!latestPrereleaseTag) {
previousTag = latestTag;
}
else {
previousTag = gte(latestTag.name.replace(prefixRegex, ''), latestPrereleaseTag.name.replace(prefixRegex, ''))
? latestTag
: latestPrereleaseTag;
}
if (!previousTag) {
core.setFailed('Could not find previous tag.');
return;
}
previousVersion = parse(previousTag.name.replace(prefixRegex, ''));
if (!previousVersion) {
core.setFailed('Could not parse previous tag.');
return;
}
core.info(`Previous tag was ${previousTag.name}, previous version was ${previousVersion.version}.`);
core.setOutput('previous_version', previousVersion.version);
core.setOutput('previous_tag', previousTag.name);
commits = await getCommits(previousTag.commit.sha, commitRef);
let bump = await analyzeCommits({
releaseRules: mappedReleaseRules
? // analyzeCommits doesn't appreciate rules with a section /shrug
mappedReleaseRules.map(({ section, ...rest }) => ({ ...rest }))
: undefined,
}, { commits, logger: { log: console.info.bind(console) } });
// Determine if we should continue with tag creation based on main vs prerelease branch
let shouldContinue = true;
if (isPrerelease) {
if (!bump && defaultPreReleaseBump === 'false') {
shouldContinue = false;
}
}
else {
if (!bump && defaultBump === 'false') {
shouldContinue = false;
}
}
// Default bump is set to false and we did not find an automatic bump
if (!shouldContinue) {
core.debug('No commit specifies the version bump. Skipping the tag creation.');
return;
}
// If we don't have an automatic bump for the prerelease, just set our bump as the default
if (isPrerelease && !bump) {
bump = defaultPreReleaseBump;
}
// If somebody uses custom release rules on a prerelease branch they might create a 'preprepatch' bump.
const preReg = /^pre/;
if (isPrerelease && preReg.test(bump)) {
bump = bump.replace(preReg, '');
}
const releaseType = isPrerelease
? `pre${bump}`
: bump || defaultBump;
core.setOutput('release_type', releaseType);
const incrementedVersion = inc(previousVersion, releaseType, identifier);
if (!incrementedVersion) {
core.setFailed('Could not increment version.');
return;
}
if (!valid(incrementedVersion)) {
core.setFailed(`${incrementedVersion} is not a valid semver.`);
return;
}
newVersion = incrementedVersion;
}
core.info(`New version is ${newVersion}.`);
core.setOutput('new_version', newVersion);
const newTag = `${tagPrefix}${newVersion}`;
core.info(`New tag after applying prefix is ${newTag}.`);
core.setOutput('new_tag', newTag);
const changelog = await generateNotes({
preset: 'conventionalcommits',
presetConfig: {
types: mergeWithDefaultChangelogRules(mappedReleaseRules),
},
}, {
commits,
logger: { log: console.info.bind(console) },
options: {
repositoryUrl: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`,
},
lastRelease: { gitTag: latestTag.name },
nextRelease: { gitTag: newTag, version: newVersion },
});
core.info(`Changelog is ${changelog}.`);
core.setOutput('changelog', changelog);
if (!isReleaseBranch && !isPreReleaseBranch) {
core.info('This branch is neither a release nor a pre-release branch. Skipping the tag creation.');
return;
}
if (validTags.map((tag) => tag.name).includes(newTag)) {
core.info('This tag already exists. Skipping the tag creation.');
return;
}
if (/true/i.test(dryRun)) {
core.info('Dry run: not performing tag action.');
return;
}
await createTag(newTag, createAnnotatedTag, commitRef);
}
18 changes: 18 additions & 0 deletions lib/defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Default sections & changelog rules mentioned in `conventional-changelog-angular` & `conventional-changelog-conventionalcommits`.
* References:
* https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-angular/writer-opts.js
* https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-conventionalcommits/writer-opts.js
*/
export const defaultChangelogRules = Object.freeze({
feat: { type: 'feat', section: 'Features' },
fix: { type: 'fix', section: 'Bug Fixes' },
perf: { type: 'perf', section: 'Performance Improvements' },
revert: { type: 'revert', section: 'Reverts' },
docs: { type: 'docs', section: 'Documentation' },
style: { type: 'style', section: 'Styles' },
refactor: { type: 'refactor', section: 'Code Refactoring' },
test: { type: 'test', section: 'Tests' },
build: { type: 'build', section: 'Build Systems' },
ci: { type: 'ci', section: 'Continuous Integration' },
});
53 changes: 53 additions & 0 deletions lib/github.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { context, getOctokit } from '@actions/github';
import * as core from '@actions/core';
let octokitSingleton;
export function getOctokitSingleton() {
if (octokitSingleton) {
return octokitSingleton;
}
const githubToken = core.getInput('github_token');
octokitSingleton = getOctokit(githubToken);
return octokitSingleton;
}
export async function listTags(shouldFetchAllTags = false, fetchedTags = [], page = 1) {
const octokit = getOctokitSingleton();
const tags = await octokit.rest.repos.listTags({
...context.repo,
per_page: 100,
page,
});
if (tags.data.length < 100 || shouldFetchAllTags === false) {
return [...fetchedTags, ...tags.data];
}
return listTags(shouldFetchAllTags, [...fetchedTags, ...tags.data], page + 1);
}
export async function compareCommits(baseRef, headRef) {
const octokit = getOctokitSingleton();
core.debug(`Comparing commits (${baseRef}...${headRef})`);
const commits = await octokit.rest.repos.compareCommits({
...context.repo,
base: baseRef,
head: headRef,
});
return commits.data.commits;
}
export async function createTag(newTag, createAnnotatedTag, GITHUB_SHA) {
const octokit = getOctokitSingleton();
let annotatedTag = undefined;
if (createAnnotatedTag) {
core.debug(`Creating annotated tag.`);
annotatedTag = await octokit.rest.git.createTag({
...context.repo,
tag: newTag,
message: newTag,
object: GITHUB_SHA,
type: 'commit',
});
}
core.debug(`Pushing new tag to the repo.`);
await octokit.rest.git.createRef({
...context.repo,
ref: `refs/tags/${newTag}`,
sha: annotatedTag ? annotatedTag.data.sha : GITHUB_SHA,
});
}
Loading