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 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
72 changes: 72 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,71 @@ 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 }}

- name: '[Verification] Params: always-comment with github-token'
if: github.ref != 'refs/heads/main'
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get the PR number
pr_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
echo "PR number: $pr_number"

# Check if the comment exists and get the latest comment ID
comment_id=$(gh api "repos/${{ github.repository }}/issues/${pr_number}/comments" --jq \
'sort_by(.created_at) | reverse | .[0] | select(.body | contains("Dive Summary")) | .id')
echo "Comment ID: $comment_id"

if [ -z "$comment_id" ]; then
echo "Expected comment not found in PR"
exit 1
fi

# Delete the comment after verification
gh api -X DELETE "repos/${{ github.repository }}/issues/comments/${comment_id}"
echo "Comment deleted"
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
25 changes: 18 additions & 7 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,13 @@ function run() {
error('Missing required parameter: image');
}
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 ghToken = core.getInput('github-token');
if (alwaysComment && !ghToken) {
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)) {
Expand Down Expand Up @@ -186,20 +193,24 @@ 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(ghToken, diveOutput);
if (exitCode === 0)
return;
error(scanFailedErrorMsg);
}
const ghToken = core.getInput('github-token');
if (exitCode === 0)
return;
if (!ghToken) {
error(`Scan failed (exit code: ${exitCode}).\nTo post scan results ` +
'as a PR comment, please provide the github-token in the action inputs.');
error(`Scan failed (exit code: ${exitCode}).\nTo post scan results as ` +
'a PR comment, please provide the github-token in the action inputs.');
}
yield postComment(ghToken, diveOutput, [
'> [!WARNING]',
'> The container image has inefficient files.'
]);
error(`Scan failed (exit code: ${exitCode})`);
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
30 changes: 23 additions & 7 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ async function run(): Promise<void> {
error('Missing required parameter: image')
}
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 ghToken = core.getInput('github-token')

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

const diveRepo = core.getInput('dive-image-registry')
// Validate Docker image name format
Expand Down Expand Up @@ -161,24 +170,31 @@ 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(ghToken, diveOutput)

if (exitCode === 0) return

error(scanFailedErrorMsg)
}

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

if (!ghToken) {
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.'
)
}
await postComment(ghToken, diveOutput, [
'> [!WARNING]',
'> The container image has inefficient files.'
])

error(`Scan failed (exit code: ${exitCode})`)
error(scanFailedErrorMsg)
} catch (e) {
error(e instanceof Error ? e.message : String(e))
}
Expand Down
Loading