Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support posting of dive results to PR for succesful runs #69

Merged
merged 27 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from 15 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: 48 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ jobs:
env:
TEST_IMAGE: ghcr.io/joschi/dive:latest

permissions:
# 'Params: always-comment with github-token' step to push a comment to PR
pull-requests: write

steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

Expand Down Expand Up @@ -145,3 +149,47 @@ jobs:
echo "Expected step to fail"
exit 1
fi

# Verifies that the action properly handles missing GitHub token when
# always-comment is true. Expected to fail as posting comments requires
# GitHub token authentication
- name: '[Run] Negative test: always-comment w/o github-token'
id: always-comment-missing-github-token
if: always() && steps.pre-setup.outcome == 'success'
continue-on-error: true
uses: ./
with:
image: ${{ env.TEST_IMAGE }}
always-comment: true

- name: '[Verification] Negative test: always-comment w/o github-token'
# It will not be able to create comment outside PR. result in main branch:
# Not Found - https://docs.github.com/rest
if: always() && steps.pre-setup.outcome == 'success' && github.ref !=
'refs/heads/main'
shell: bash
run: |
error_message="${{ steps.always-comment-missing-github-token.outputs.error }}"
expected_message='always-comment parameter requires github-token to be set.'

if [[ ! "$error_message" =~ "$expected_message" ]]; then
echo "Expected error message to contain: $expected_message"
echo "Got: $error_message"
exit 1
fi
if [[ "${{ steps.always-comment-missing-github-token.outcome }}" != "failure" ]]; then
echo "Expected step to fail"
exit 1
fi

# Runs at the end and only when all other tests pass, as it posts the
# results as a comment on the PR
- name: 'Params: always-comment with github-token'
# It will not be able to create comment outside PR. result in main branch:
# Not Found - https://docs.github.com/rest
if: github.ref != 'refs/heads/main'
uses: ./
with:
image: ${{ env.TEST_IMAGE }}
always-comment: true
github-token: ${{ secrets.GITHUB_TOKEN }}
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ reduce your container image size as early as possible.

### Inputs

| Name                      | Type | Required | Default | Description                              |
| ------------------- | ------ | -------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| image | String | true | | Image to analyze |
| config-file | String | false | `${{ github.workspace }}/.dive.yaml` | Path to [dive config file](https://github.com/joschi/dive#ci-integration) |
| github-token | String | false | | GitHub token to post PR comment on dive failure |
| dive-image-registry | String | false | `ghcr.io/joschi/dive` | Docker registry to pull the Dive image from |
| dive-image-version | String | false | `0.13.1@sha256:f016a4bd2837` `130545e391acee7876aa5f7258` `ccdb12640ab4afaffa1c597d17` | Version of the Dive docker image to use. <br> While `latest` is supported, using a specific version with SHA is recommended for security and reproducibility |
| Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | Type | Required | Default | Description&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |
| ---------------------------------------------------------------------------------------------------------------------------------- | ------- | -------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| image | String | true | | Image to analyze |
| always-comment | Boolean | false | `false` | Post dive analysis results as PR comment regardless of whether any inefficiencies were found. By default, comments are only posted when issues are detected. Requires `github-token` |
| config-file | String | false | `${{ github.workspace }}/.dive.yaml` | Path to [dive config file](https://github.com/joschi/dive#ci-integration) |
| github-token | String | false | | GitHub token to post PR comment with dive analysis |
| dive-image-registry | String | false | `ghcr.io/joschi/dive` | Docker registry to pull the Dive image from |
| dive-image-version | String | false | `0.13.1@sha256:f016a4bd2837` `130545e391acee7876aa5f7258` `ccdb12640ab4afaffa1c597d17` | Version of the Dive docker image to use. <br> While `latest` is supported, using a specific version with SHA is recommended for security and reproducibility |


### Workflow
Expand All @@ -47,7 +48,7 @@ jobs:
- name: Build image
run: docker build -t sample:latest .
- name: Dive
uses: MaxymVlasov/dive-action@v1.2.1
uses: MaxymVlasov/dive-action@v1.3.0
with:
image: sample:latest
config-file: ${{ github.workspace }}/.dive-ci.yml
Expand Down
8 changes: 7 additions & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@ inputs:
image:
description: Image to analyze
required: true
always-comment:
description: Post dive analysis results as PR comment regardless of whether
any inefficiencies were found. By default, comments are only posted when
issues are detected. Requires `github-token`
required: false
default: 'false'
config-file:
description: Path to dive config file
required: false
default: ${{ github.workspace }}/.dive.yaml
github-token:
description: GitHub Token to post PR comment
description: GitHub token to post PR comment with dive analysis
required: false
dive-image-registry:
description: Docker registry to pull the Dive image from
Expand Down
41 changes: 28 additions & 13 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ function format(output) {
function error(message) {
core.setOutput('error', message);
core.setFailed(message);
process.exit(1);
}
function postComment(token, output) {
return __awaiter(this, void 0, void 0, function* () {
const octokit = github.getOctokit(token);
const comment = Object.assign(Object.assign({}, github.context.issue), { issue_number: github.context.issue.number, body: format(output) });
yield octokit.rest.issues.createComment(comment);
});
}
/**
* Executes a Docker image analysis using the dive tool and handles the results.
Expand All @@ -123,13 +131,19 @@ function run() {
const image = core.getInput('image');
if (!image) {
error('Missing required parameter: image');
return;
}
const configFile = core.getInput('config-file');
// Convert always-comment input to boolean value.
// All values other than 'true' are considered false.
const alwaysComment = core.getInput('always-comment').toLowerCase() === 'true';
const token = core.getInput('github-token');
if (alwaysComment && !token) {
error('"always-comment" parameter requires "github-token" to be set.');
}
const diveRepo = core.getInput('dive-image-registry');
// Validate Docker image name format
if (!/^[\w.\-_/]+$/.test(diveRepo)) {
throw new Error('Invalid dive-image-registry format');
error('Invalid dive-image-registry format');
}
const diveVersion = core.getInput('dive-image-version');
const diveImage = `${diveRepo}:${diveVersion}`;
Expand Down Expand Up @@ -169,20 +183,21 @@ function run() {
}
};
const exitCode = yield exec.exec('docker', parameters, execOptions);
if (exitCode === 0) {
// success
return;
const scanFailedErrorMsg = `Scan failed (exit code: ${exitCode})`;
if (alwaysComment) {
yield postComment(token, output);
if (exitCode === 0)
return;
error(scanFailedErrorMsg);
}
const token = core.getInput('github-token');
if (!token) {
error(`Scan failed (exit code: ${exitCode}).\nTo post scan results ` +
'as a PR comment, please provide the github-token in the action inputs.');
if (exitCode === 0)
return;
if (!token) {
error(`Scan failed (exit code: ${exitCode}).\nTo post scan results as ` +
'a PR comment, please provide the github-token in the action inputs.');
}
const octokit = github.getOctokit(token);
const comment = Object.assign(Object.assign({}, github.context.issue), { issue_number: github.context.issue.number, body: format(output) });
yield octokit.rest.issues.createComment(comment);
error(`Scan failed (exit code: ${exitCode})`);
yield postComment(token, output);
error(scanFailedErrorMsg);
}
catch (e) {
error(e instanceof Error ? e.message : String(e));
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

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": "dive-action",
"version": "1.2.1",
"version": "1.3.0",
"description": "[![Release][release-badge]][release] [![GitHub Marketplace][marketplace-badge]][marketplace] [![License][license-badge]][license]",
"main": "lib/main.js",
"scripts": {
Expand Down
55 changes: 38 additions & 17 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ function format(output: string): string {
function error(message: string): void {
core.setOutput('error', message)
core.setFailed(message)
process.exit(1)
}

async function postComment(token: string, output: string): Promise<void> {
const octokit = github.getOctokit(token)
const comment = {
...github.context.issue,
issue_number: github.context.issue.number,
body: format(output)
}
await octokit.rest.issues.createComment(comment)
}

/**
Expand All @@ -69,14 +80,22 @@ async function run(): Promise<void> {
const image = core.getInput('image')
if (!image) {
error('Missing required parameter: image')
return
}
const configFile = core.getInput('config-file')
// Convert always-comment input to boolean value.
// All values other than 'true' are considered false.
const alwaysComment =
core.getInput('always-comment').toLowerCase() === 'true'
const token = core.getInput('github-token')

if (alwaysComment && !token) {
error('"always-comment" parameter requires "github-token" to be set.')
}

const diveRepo = core.getInput('dive-image-registry')
// Validate Docker image name format
if (!/^[\w.\-_/]+$/.test(diveRepo)) {
throw new Error('Invalid dive-image-registry format')
error('Invalid dive-image-registry format')
}
const diveVersion = core.getInput('dive-image-version')
const diveImage = `${diveRepo}:${diveVersion}`
Expand Down Expand Up @@ -125,27 +144,29 @@ async function run(): Promise<void> {
}
}
const exitCode = await exec.exec('docker', parameters, execOptions)
if (exitCode === 0) {
// success
return

const scanFailedErrorMsg = `Scan failed (exit code: ${exitCode})`

if (alwaysComment) {
await postComment(token, output)

if (exitCode === 0) return

error(scanFailedErrorMsg)
}

const token = core.getInput('github-token')
if (exitCode === 0) return

if (!token) {
error(
`Scan failed (exit code: ${exitCode}).\nTo post scan results ` +
'as a PR comment, please provide the github-token in the action inputs.'
`Scan failed (exit code: ${exitCode}).\nTo post scan results as ` +
'a PR comment, please provide the github-token in the action inputs.'
)
return
}
const octokit = github.getOctokit(token)
const comment = {
...github.context.issue,
issue_number: github.context.issue.number,
body: format(output)
}
await octokit.rest.issues.createComment(comment)
error(`Scan failed (exit code: ${exitCode})`)

await postComment(token, output)

error(scanFailedErrorMsg)
} catch (e) {
error(e instanceof Error ? e.message : String(e))
}
Expand Down
Loading