add some initial tests

This commit is contained in:
Moritz Schmitz von Hülst 2020-11-12 17:05:47 +01:00
parent 808cb0be59
commit c9d97025ca
10 changed files with 5980 additions and 203 deletions

View File

@ -10,6 +10,7 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- run: npm ci
- run: npm run test
- run: npm run build

5551
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,8 @@
"description": "A GitHub Action to automatically bump and tag master, on merge, with the latest SemVer formatted version.",
"main": "lib/main.js",
"scripts": {
"build": "tsc"
"build": "tsc",
"test": "jest --testTimeout 10000"
},
"repository": {
"type": "git",
@ -29,6 +30,9 @@
"devDependencies": {
"@types/node": "^13.13.5",
"@types/semver": "^7.1.0",
"jest": "^26.6.3",
"jest-circus": "^26.6.3",
"ts-jest": "^26.4.4",
"typescript": "^3.8.3"
}
}

165
src/action.ts Normal file
View File

@ -0,0 +1,165 @@
import * as core from "@actions/core";
import { gte, inc, parse, ReleaseType, SemVer, valid } from "semver";
import { analyzeCommits } from "@semantic-release/commit-analyzer";
import { generateNotes } from "@semantic-release/release-notes-generator";
import {
getBranchFromRef,
getCommits,
getLatestPrereleaseTag,
getLatestTag,
getValidTags,
mapCustomReleaseTypes,
} from "./utils";
import { createTag } from "./github";
export async function run() {
try {
const defaultBump = core.getInput("default_bump") as ReleaseType | "false";
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 = !!core.getInput("create_annotated_tag");
const dryRun = core.getInput("dry_run");
const customReleaseTypes = core.getInput("custom_release_types");
let mappedReleaseTypes;
if (customReleaseTypes) {
mappedReleaseTypes = mapCustomReleaseTypes(customReleaseTypes);
}
const { GITHUB_REF, GITHUB_SHA } = process.env;
if (!GITHUB_REF) {
core.setFailed("Missing GITHUB_REF.");
return;
}
if (!GITHUB_SHA) {
core.setFailed("Missing 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 isPrerelease = !isReleaseBranch && isPreReleaseBranch;
const identifier = appendToPreReleaseTag ? appendToPreReleaseTag : currentBranch;
const validTags = await getValidTags();
const latestTag = getLatestTag(validTags);
const latestPrereleaseTag = getLatestPrereleaseTag(
validTags,
identifier
);
const commits = await getCommits(latestTag.commit.sha);
let newVersion: string;
if (customTag) {
newVersion = customTag;
} else {
let previousTag: SemVer | null;
if (!latestPrereleaseTag) {
previousTag = parse(latestTag.name);
} else {
previousTag = parse(
gte(latestTag.name, latestPrereleaseTag.name)
? latestTag.name
: latestPrereleaseTag.name
);
}
if (!previousTag) {
core.setFailed("Could not parse previous tag.");
return;
}
core.info(`Previous tag was ${previousTag}.`);
core.setOutput("previous_tag", previousTag.version);
const bump = await analyzeCommits(
{ releaseTypes: mappedReleaseTypes },
{ commits, logger: { log: console.info.bind(console) } }
);
if (!bump && defaultBump === "false") {
core.debug(
"No commit specifies the version bump. Skipping the tag creation."
);
return;
}
const releaseType: ReleaseType = isPrerelease
? `pre${bump || defaultBump}`
: bump || defaultBump;
const incrementedVersion = inc(
previousTag,
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(
{},
{
commits,
logger: { log: console.info.bind(console) },
options: {
repositoryUrl: `https://github.com/${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, GITHUB_SHA);
} catch (error) {
core.setFailed(error.message);
}
}

65
src/github.ts Normal file
View File

@ -0,0 +1,65 @@
import { context, GitHub } from "@actions/github";
import * as core from "@actions/core";
import { Octokit } from "@octokit/rest";
let octokitSingleton;
function getOctokitSingleton() {
if (octokitSingleton) {
return octokitSingleton;
}
const githubToken = core.getInput("github_token");
octokitSingleton = new GitHub(githubToken);
return octokitSingleton;
}
export async function listTags() {
const octokit = getOctokitSingleton();
const tags = await octokit.repos.listTags({
...context.repo,
per_page: 100,
});
return tags.data;
}
export async function compareCommits(sha: string) {
const octokit = getOctokitSingleton();
const commits = await octokit.repos.compareCommits({
...context.repo,
base: sha,
head: "HEAD",
});
return commits.data.commits;
}
export async function createTag(
newTag: string,
createAnnotatedTag: boolean,
GITHUB_SHA: string
) {
const octokit = getOctokitSingleton();
let annotatedTag:
| Octokit.Response<Octokit.GitCreateTagResponse>
| undefined = undefined;
if (createAnnotatedTag) {
core.debug(`Creating annotated tag.`);
annotatedTag = await octokit.git.createTag({
...context.repo,
tag: newTag,
message: newTag,
object: GITHUB_SHA,
type: "commit",
});
}
core.debug(`Pushing new tag to the repo.`);
await octokit.git.createRef({
...context.repo,
ref: `refs/tags/${newTag}`,
sha: annotatedTag ? annotatedTag.data.sha : GITHUB_SHA,
});
}

View File

@ -1,159 +1,3 @@
import * as core from "@actions/core";
import { inc, parse, ReleaseType, valid, gte, SemVer } from "semver";
import { analyzeCommits } from "@semantic-release/commit-analyzer";
import { generateNotes } from "@semantic-release/release-notes-generator";
import {
getValidTags,
getCommits,
getBranchFromRef,
getLatestTag,
createTag,
getLatestPrereleaseTag,
} from "./utils";
async function run() {
try {
const defaultBump = core.getInput("default_bump") as ReleaseType | "false";
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 = !!core.getInput("create_annotated_tag");
const dryRun = core.getInput("dry_run");
const { GITHUB_REF, GITHUB_SHA } = process.env;
if (!GITHUB_REF) {
core.setFailed("Missing GITHUB_REF.");
return;
}
if (!GITHUB_SHA) {
core.setFailed("Missing 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 isPrerelease = !isReleaseBranch && isPreReleaseBranch;
const identifier = appendToPreReleaseTag ? appendToPreReleaseTag : currentBranch;
const validTags = await getValidTags();
const latestTag = getLatestTag(validTags);
const latestPrereleaseTag = getLatestPrereleaseTag(
validTags,
identifier
);
const commits = await getCommits(latestTag.commit.sha);
let newVersion: string;
if (customTag) {
newVersion = customTag;
} else {
let previousTag: SemVer | null;
if (!latestPrereleaseTag) {
previousTag = parse(latestTag.name);
} else {
previousTag = parse(
gte(latestTag.name, latestPrereleaseTag.name)
? latestTag.name
: latestPrereleaseTag.name
);
}
if (!previousTag) {
core.setFailed("Could not parse previous tag.");
return;
}
core.info(`Previous tag was ${previousTag}.`);
core.setOutput("previous_tag", previousTag.version);
const bump = await analyzeCommits(
{},
{ commits, logger: { log: console.info.bind(console) } }
);
if (!bump && defaultBump === "false") {
core.debug(
"No commit specifies the version bump. Skipping the tag creation."
);
return;
}
const releaseType: ReleaseType = isPrerelease
? "prerelease"
: bump || defaultBump;
const incrementedVersion = inc(
previousTag,
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(
{},
{
commits,
logger: { log: console.info.bind(console) },
options: {
repositoryUrl: `https://github.com/${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, GITHUB_SHA);
} catch (error) {
core.setFailed(error.message);
}
}
import { run } from './action';
run();

View File

@ -1,24 +1,19 @@
import * as core from "@actions/core";
import { Octokit } from "@octokit/rest";
import { context, GitHub } from "@actions/github";
import { valid, rcompare, prerelease } from "semver";
const githubToken = core.getInput("github_token");
const octokit = new GitHub(githubToken);
import { prerelease, rcompare, valid } from "semver";
import DEFAULT_RELEASE_TYPES from "@semantic-release/commit-analyzer/lib/default-release-types.js";
import { compareCommits, listTags } from "./github";
export async function getValidTags() {
const tags = await octokit.repos.listTags({
...context.repo,
per_page: 100,
});
const tags = await listTags();
const invalidTags = tags.data
const invalidTags = tags
.map((tag) => tag.name)
.filter((name) => !valid(name));
invalidTags.forEach((name) => core.debug(`Found Invalid Tag: ${name}.`));
const validTags = tags.data
const validTags = tags
.filter((tag) => valid(tag.name))
.sort((a, b) => rcompare(a.name, b.name));
@ -28,13 +23,9 @@ export async function getValidTags() {
}
export async function getCommits(sha: string) {
const commits = await octokit.repos.compareCommits({
...context.repo,
base: sha,
head: "HEAD",
});
const commits = await compareCommits(sha);
return commits.data.commits
return commits
.filter((commit) => !!commit.commit.message)
.map((commit) => ({
message: commit.commit.message,
@ -46,33 +37,6 @@ export function getBranchFromRef(ref: string) {
return ref.replace("refs/heads/", "");
}
export async function createTag(
newTag: string,
createAnnotatedTag: boolean,
GITHUB_SHA: string
) {
let annotatedTag:
| Octokit.Response<Octokit.GitCreateTagResponse>
| undefined = undefined;
if (createAnnotatedTag) {
core.debug(`Creating annotated tag.`);
annotatedTag = await octokit.git.createTag({
...context.repo,
tag: newTag,
message: newTag,
object: GITHUB_SHA,
type: "commit",
});
}
core.debug(`Pushing new tag to the repo.`);
await octokit.git.createRef({
...context.repo,
ref: `refs/tags/${newTag}`,
sha: annotatedTag ? annotatedTag.data.sha : GITHUB_SHA,
});
}
export function getLatestTag(tags: Octokit.ReposListTagsResponseItem[]) {
return (
tags.find((tag) => !prerelease(tag.name)) || {
@ -92,3 +56,23 @@ export function getLatestPrereleaseTag(
.filter((tag) => prerelease(tag.name))
.find((tag) => tag.name.match(identifier));
}
export function mapCustomReleaseTypes(
customReleaseTypes: string
) {
return customReleaseTypes
.split(';')
.map(part => {
const custom = part.split(':');
if (custom.length !== 2) {
core.warning(`${part} is not a valid custom release definition.`);
return null;
}
const [keyword, release] = custom;
return {
type: keyword,
release
};
})
.filter(customRelease => DEFAULT_RELEASE_TYPES.includes(customRelease?.release));
}

47
tests/action.test.ts Normal file
View File

@ -0,0 +1,47 @@
import { run } from '../src/action';
import * as utils from '../src/utils';
import * as github from '../src/github';
import * as core from '@actions/core';
const mockCreateTag = jest.spyOn(github, 'createTag').mockImplementation(async () => {
});
const mockSetFailed = jest.spyOn(core, 'setFailed');
describe('main tests', () => {
const mockGetCommits = (commits) => jest.spyOn(utils, 'getCommits').mockImplementation(async (sha) => {
return commits;
});
const mockGetValidTags = (validTags) => jest.spyOn(utils, 'getValidTags').mockImplementation(async () => {
return validTags;
});
beforeEach(() => {
jest.clearAllMocks();
process.env['GITHUB_REF'] = 'refs/heads/master';
process.env['GITHUB_SHA'] = 'GITHUB_SHA';
});
it('happy path', async () => {
/*
* Given
*/
const mockValidTags = mockGetValidTags([]);
const commits = [
{ message: 'fix: this is my first fix' },
]
const mockCommits = mockGetCommits(commits);
/*
* When
*/
await run();
/*
* Then
*/
expect(mockValidTags).toHaveBeenCalled();
expect(mockCommits).toHaveBeenCalledWith('HEAD');
expect(mockCreateTag).toHaveBeenCalledWith('0.0.1', expect.any(Boolean), expect.any(String));
expect(mockSetFailed).not.toBeCalled();
})
});

7
tests/helper.ts Normal file
View File

@ -0,0 +1,7 @@
export function setInput(key, value) {
process.env[`INPUT_${key.toUpperCase()}`] = value;
}
export function setInputs(map) {
Object.keys(map).forEach(key => setInput(key, map[key]));
}

109
tests/utils.test.ts Normal file
View File

@ -0,0 +1,109 @@
import * as utils from '../src/utils';
import { getValidTags } from '../src/utils';
import * as github from '../src/github';
describe('utils', () => {
it('maps custom release types', () => {
/*
* Given
*/
const customReleasesString = 'james:preminor;bond:premajor';
/*
* When
*/
const mappedReleases = utils.mapCustomReleaseTypes(customReleasesString);
/*
* Then
*/
expect(mappedReleases)
.toEqual([
{ type: 'james', release: 'preminor' },
{ type: 'bond', release: 'premajor' }
]);
});
it('filters out invalid custom release types', () => {
/*
* Given
*/
const customReleasesString = 'james:pre-release;bond:premajor';
/*
* When
*/
const mappedReleases = utils.mapCustomReleaseTypes(customReleasesString);
/*
* Then
*/
expect(mappedReleases)
.toEqual([
{ type: 'bond', release: 'premajor' }
]);
});
it('extracts branch from ref', () => {
/*
* Given
*/
const remoteRef = 'refs/heads/master';
/*
* When
*/
const branch = utils.getBranchFromRef(remoteRef);
/*
* Then
*/
expect(branch).toEqual('master');
});
it('returns valid tags', async () => {
/*
* Given
*/
const testTags = [
{ name: 'release-1.2.3' },
{ name: '1.2.3' },
]
const mockListTags = jest.spyOn(github, 'listTags').mockImplementation(async () => testTags);
/*
* When
*/
const validTags = await getValidTags();
/*
* Then
*/
expect(mockListTags).toHaveBeenCalled();
expect(validTags).toHaveLength(1);
});
it('returns sorted tags', async () => {
/*
* Given
*/
const testTags = [
{ name: '1.2.4-prerelease.1' },
{ name: '1.2.4-prerelease.2' },
{ name: '1.2.4-prerelease.0' },
{ name: '1.2.3' },
]
const mockListTags = jest.spyOn(github, 'listTags').mockImplementation(async () => testTags);
/*
* When
*/
const validTags = await getValidTags();
/*
* Then
*/
expect(mockListTags).toHaveBeenCalled();
expect(validTags[0]).toEqual({ name: '1.2.4-prerelease.2' });
});
});