Skip to content
Merged
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
48 changes: 41 additions & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,55 @@
name: Release
on:
push:
tags: ['v*.*.*']
workflow_dispatch:
concurrency:
group: release
jobs:
create-release:
runs-on: ubuntu-latest
# NOTE(krishan711): the release environment only allows main and holds the deploy key, which is the only thing allowed past the tag ruleset
environment: release
permissions:
contents: write
steps:
- name: Check out the repo
uses: actions/checkout@v7
- name: Create Release
with:
ssh-key: ${{ secrets.RELEASE_DEPLOY_KEY }}
- name: Push the version tag
id: version
run: |
version="v$(jq -r .version package.json)"
if [[ ! "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
echo "::error::package.json version $version is not semver"
exit 1
fi
existingSha="$(git ls-remote origin "refs/tags/$version" | cut -f1)"
if [[ -n "$existingSha" && "$existingSha" != "$GITHUB_SHA" ]]; then
echo "::error::$version already exists on $existingSha, bump the version in package.json"
exit 1
fi
if [[ -z "$existingSha" ]]; then
git tag "$version"
git push origin "refs/tags/$version"
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: Create the release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release create ${{ github.ref_name }} --title "Release ${{ github.ref_name }}" --generate-notes
GH_TOKEN: ${{ github.token }}
VERSION: ${{ steps.version.outputs.version }}
run: |
if gh release view "$VERSION" >/dev/null 2>&1; then
echo "$VERSION is already released"
elif [[ "$VERSION" == *-* ]]; then
gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes --prerelease
else
gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes
fi
- name: Move the major version tag
if: ${{ !contains(steps.version.outputs.version, '-') }}
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
majorTag="${GITHUB_REF_NAME%%.*}"
majorTag="${VERSION%%.*}"
git tag --force "$majorTag"
git push --force origin "$majorTag"
git push --force origin "refs/tags/$majorTag"
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# GitHub Action - Run Docker Checks

Check notice on line 1 in README.md

View workflow job for this annotation

GitHub Actions / example-annotations

README.md#L1

An example notice

Run a project's checks (lint, type-check, tests, ...) in parallel docker containers and report each one as its own GitHub check, with its result, its log and any annotations.

Expand Down Expand Up @@ -43,7 +43,7 @@
| Field | Required | Description |
| --- | --- | --- |
| `name` | yes | Short unique name, used for the container and the log group. |
| `command` | yes | Run with `sh -c` in the image, in the image's working directory. Quote it if it contains `: `. |
| `command` | yes | Run with `sh -c` in the image, ignoring the image's `ENTRYPOINT`, in the image's working directory. Quote it if it contains `: `. |
| `check-name` | no | Report this check as its own GitHub check with this name. |
| `annotations-file` | no | JSON file the command writes inside the container, in the [create-annotations](https://github.com/kibalabs/github-action-create-annotations) format, attached to the check. Needs `check-name`. Relative paths start from the image's working directory. |
| `stdout-file` | no | Save the command's standard output to this file in the workspace, e.g. to compare generated files afterwards. |
Expand All @@ -69,10 +69,10 @@

When [Skip If Passed](https://github.com/kibalabs/github-action-skip-if-passed) decides a job can be skipped, it sets `CHECKS_ALREADY_PASSED=true` and this action does nothing. Its checks set `external_id` to the workflow run's id, so Skip If Passed copies them onto the skipped commit.

If the job is cancelled or times out, a post step marks any checks that didn't finish as cancelled.
If the job is cancelled or times out, a post step marks any checks that didn't finish as cancelled and force-removes their containers.

## Development

Build with `make build`, which bundles `src/` into `runnable/index.js`. GitHub runs that file directly, so commit it with every source change. Run the tests with `make test`.

To release, push a `vX.Y.Z` tag. The release workflow publishes the release and moves the `vX` tag to it, so `@v1` always points at the latest 1.x release.
To release, bump `version` in `package.json` in a PR, then run the Release workflow on `main` (Actions → Release → Run workflow). It tags `vX.Y.Z`, publishes the release and moves the `vX` tag to it, so `@v1` always points at the latest 1.x release. Versions with a pre-release suffix (e.g. `1.1.0-rc1`) are published as pre-releases and don't move `vX`. Only the release workflow can push version tags.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kibalabs/github-action-run-docker-checks",
"version": "1.0.0",
"version": "1.0.1",
"description": "GitHub Action to run checks in parallel docker containers and report each as its own GitHub check",
"license": "MIT",
"private": true,
Expand Down
2 changes: 1 addition & 1 deletion runnable/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export const getImageWorkingDirectory = async (image: string): Promise<string> =
};

export const startContainer = async (containerName: string, image: string, command: string): Promise<void> => {
await runDockerOrThrow(['run', '--detach', '--name', containerName, image, 'sh', '-c', command]);
await runDockerOrThrow(['run', '--detach', '--name', containerName, '--entrypoint', 'sh', image, '-c', command]);
};

export const waitForContainer = async (containerName: string): Promise<number> => {
Expand Down
19 changes: 12 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { ChecksPermissionError, completeCheck, createInProgressCheck, ICheckTarg
import { IAnnotation, ICheckDefinition, ICheckResult, SKIP_ENVIRONMENT_VARIABLE } from './model';

const CHECK_RUN_IDS_STATE = 'checkRunIds';
const CONTAINER_NAMES_STATE = 'containerNames';

const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));

Expand Down Expand Up @@ -42,8 +43,7 @@ const readAnnotations = async (containerName: string, definition: ICheckDefiniti
}
};

const runCheck = async (definition: ICheckDefinition, image: string, workingDirectory: string, pathPrefix: string, tempDirectory: string): Promise<ICheckResult> => {
const containerName = `${definition.name.replace(/[^a-zA-Z0-9_.-]/g, '-')}-${randomUUID().slice(0, 8)}`;
const runCheck = async (containerName: string, definition: ICheckDefinition, image: string, workingDirectory: string, pathPrefix: string, tempDirectory: string): Promise<ICheckResult> => {
const logPath = path.join(tempDirectory, `${containerName}.log`);
const startTime = Date.now();
let exitCode: number | null = null;
Expand Down Expand Up @@ -83,6 +83,8 @@ const createChecks = async (octokit: Octokit, target: ICheckTarget, definitions:
}
try {
checkRunIds.set(definition.name, await createInProgressCheck(octokit, target, definition.checkName));
// NOTE(krishan711): saved after every creation so the post step can cancel the created checks even if a later creation fails
saveState(CHECK_RUN_IDS_STATE, JSON.stringify([...checkRunIds.values()]));
} catch (error) {
if (!(error instanceof ChecksPermissionError)) {
throw error;
Expand Down Expand Up @@ -115,10 +117,11 @@ const runChecks = async (): Promise<void> => {
const workingDirectory = await getImageWorkingDirectory(image);
const tempDirectory = await fs.mkdtemp(path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'docker-checks-'));
const checkRunIds = await createChecks(octokit, target, definitions);
saveState(CHECK_RUN_IDS_STATE, JSON.stringify([...checkRunIds.values()]));
const containerNames = definitions.map((definition: ICheckDefinition): string => `${definition.name.replace(/[^a-zA-Z0-9_.-]/g, '-')}-${randomUUID().slice(0, 8)}`);
saveState(CONTAINER_NAMES_STATE, JSON.stringify(containerNames));
logInfo(`Running ${definitions.length} checks in ${image}: ${definitions.map((definition: ICheckDefinition): string => definition.name).join(', ')}`);
const results = await Promise.all(definitions.map(async (definition: ICheckDefinition): Promise<ICheckResult> => {
const result = await runCheck(definition, image, workingDirectory, pathPrefix, tempDirectory);
const results = await Promise.all(definitions.map(async (definition: ICheckDefinition, index: number): Promise<ICheckResult> => {
const result = await runCheck(containerNames[index], definition, image, workingDirectory, pathPrefix, tempDirectory);
logInfo(`${result.isSuccess ? 'Passed' : 'Failed'}: ${definition.name} in ${result.durationSeconds}s`);
const checkRunId = checkRunIds.get(definition.name);
if (checkRunId) {
Expand All @@ -139,8 +142,10 @@ const runChecks = async (): Promise<void> => {
}
};

// NOTE(krishan711): runs after the job even when it is cancelled or times out, so the checks this action created don't stay in progress forever
// NOTE(krishan711): runs after the job even when cancelled or timed out, cleaning up checks and their containers
const cancelUnfinishedChecks = async (): Promise<void> => {
const containerNames = JSON.parse(getState(CONTAINER_NAMES_STATE) || '[]') as string[];
await Promise.all(containerNames.map((containerName: string): Promise<void> => removeContainer(containerName)));
const checkRunIds = JSON.parse(getState(CHECK_RUN_IDS_STATE) || '[]') as number[];
if (checkRunIds.length === 0) {
return;
Expand All @@ -162,7 +167,7 @@ const run = async (): Promise<void> => {
await (isPost ? cancelUnfinishedChecks() : runChecks());
} catch (error) {
if (isPost) {
warning(`Could not cancel unfinished checks: ${getErrorMessage(error)}`);
warning(`Could not clean up unfinished checks or containers: ${getErrorMessage(error)}`);
} else {
setFailed(getErrorMessage(error));
}
Expand Down
Loading