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
12 changes: 9 additions & 3 deletions actions/sticky-comment/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,20 @@ jobs:
- if: ${{ !cancelled() && github.event_name == 'pull_request' }}
uses: TrogonStack/github-actions/actions/sticky-comment@<sha> # vX.Y.Z
with:
path: ${{ steps.plan.outputs.report-path }}
path: ${{ steps.plan.outputs.comment-path }}
marker: terraform-plan
```

`!cancelled()` rather than the default, so a failed step still comments. An
empty path or a missing file skips the step instead of failing it, because the
step that writes it may have failed before it got that far.

An empty or whitespace-only file deletes every comment this token left under
the marker, and posts nothing. A hidden comment, or one another account wrote,
is left alone. `terragrunt/report` writes one to `comment-path` when every unit
is unchanged, so a pull request whose plan used to change something, and no
longer does, keeps no comment saying it still does.

### Several comments on one pull request

The marker is the identity of the comment. Give each workflow or job that
Expand All @@ -44,15 +50,15 @@ second replaces the first.

| Input | Default | Description |
| --- | --- | --- |
| `path` | required | File holding the comment body, posted as it stands. |
| `path` | required | File holding the comment body, posted as it stands. An empty or whitespace-only file deletes the earlier comment instead. |
| `marker` | required | Identity of the comment, unique within the pull request. Letters and digits, joined by single dots, dashes or underscores. |
| `token` | `github.token` | Reads and writes the comments. Needs `pull-requests: write`. |

## Outputs

| Output | Description |
| --- | --- |
| `comment-id` | ID of the comment created or updated. Empty when the step skipped. |
| `comment-id` | ID of the comment created or updated. Empty when the step skipped or deleted it. |

## Fixed behaviour

Expand Down
6 changes: 4 additions & 2 deletions actions/sticky-comment/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ inputs:
description: >-
File holding the comment body, posted as it stands. An empty path or a
missing file skips the step rather than failing it, so it can run after a
step that failed before writing one.
step that failed before writing one. An empty or whitespace-only file
deletes every comment this token posted earlier under the marker,
because there is nothing to say.
required: true
marker:
description: >-
Expand All @@ -24,7 +26,7 @@ inputs:

outputs:
comment-id:
description: ID of the comment created or updated. Empty when the step skipped.
description: ID of the comment created or updated. Empty when the step skipped or deleted it.

runs:
using: node24
Expand Down
44 changes: 36 additions & 8 deletions actions/sticky-comment/lib/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,24 @@ export async function post({ client, owner, repo, number, marker, body }) {
return { action: "created", id: created.id };
}

// An empty file says there is nothing to report, so the comment an earlier run
// left is wrong now and goes. Not hidden: a hidden comment still claims what it
// said, one click away. Every match goes, not only the first, so a duplicate
// two concurrent runs posted does not survive to say something stale.
export async function remove({ client, owner, repo, number, marker }) {
const { viewer, comments } = await listComments({ client, owner, repo, number });
const existing = comments.filter((comment) => findExisting({ comments: [comment], viewer, marker }));

if (existing.length === 0) {
return { action: "skipped", reason: "Nothing to post, and no earlier comment to take down." };
}

for (const comment of existing) {
await client.request("DELETE", `/repos/${owner}/${repo}/issues/comments/${comment.databaseId}`);
}
return { action: "deleted", ids: existing.map((comment) => comment.databaseId) };
}

export async function run({ inputs, event, env, fetch }) {
const marker = markerOf(inputs.marker);

Expand All @@ -160,21 +178,26 @@ export async function run({ inputs, event, env, fetch }) {
}

const [owner, repo] = env.GITHUB_REPOSITORY.split("/");
const serverUrl = env.GITHUB_SERVER_URL || "https://github.com";
const body = renderBody({
marker,
content: fs.readFileSync(inputs.path, "utf8"),
runUrl: `${serverUrl}/${owner}/${repo}/actions/runs/${env.GITHUB_RUN_ID}`,
sha: event?.pull_request?.head?.sha ?? env.GITHUB_SHA,
});

const client = createClient({
token: inputs.token,
apiUrl: env.GITHUB_API_URL || "https://api.github.com",
graphqlUrl: env.GITHUB_GRAPHQL_URL || "https://api.github.com/graphql",
fetch,
});

const content = fs.readFileSync(inputs.path, "utf8");
if (content.trim() === "") {
return remove({ client, owner, repo, number, marker });
}

const serverUrl = env.GITHUB_SERVER_URL || "https://github.com";
const body = renderBody({
marker,
content,
runUrl: `${serverUrl}/${owner}/${repo}/actions/runs/${env.GITHUB_RUN_ID}`,
sha: event?.pull_request?.head?.sha ?? env.GITHUB_SHA,
});

return post({ client, owner, repo, number, marker, body });
}

Expand All @@ -199,6 +222,11 @@ export async function main() {
return;
}

if (result.action === "deleted") {
info(`Nothing to post; deleted comment ${result.ids.join(", ")}.`);
return;
}

info(`Comment ${result.id} ${result.action}.`);
setOutput("comment-id", String(result.id));
} catch (thrown) {
Expand Down
6 changes: 6 additions & 0 deletions actions/terragrunt/report/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ overwrites the first.
| Output | Description |
| --- | --- |
| `report-path` | The file the report was written to. Empty when rendering failed. |
| `comment-path` | The report as a pull request comment, next to `report-path`: the same markdown, or an empty file when every unit is unchanged. Empty when rendering failed. |
| `exit-code` | The command's exit status. |

## Fixed behaviour
Expand All @@ -112,6 +113,11 @@ These are not inputs, on purpose.
- A unit that left its provider as it found it is a row in a collapsed
`Unchanged` table, not a diff. It is still listed, because a unit that
converged and a unit missing from the run are different things.
- A run in which every unit is unchanged has nothing to review, so its
`comment-path` file is empty. `sticky-comment` reads an empty file as "take
down the earlier comment". `report-path` and the job summary still hold the
whole report. A failed command, a changed unit or a run with no unit is
never quiet.
- A failed unit shows tofu's own diagnostics, falling back to Terragrunt's
error records when tofu wrote nothing. A unit that failed only because a
dependency did has a row and nothing else, and the line above the table says
Expand Down
5 changes: 5 additions & 0 deletions actions/terragrunt/report/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ inputs:
outputs:
report-path:
description: The file the report was written to, ready to post as a comment.
comment-path:
description: >-
The report as a pull request comment: the same markdown, or an empty file
when every unit is unchanged, so `sticky-comment` takes down the comment
an earlier push left instead of posting one with nothing to review.
exit-code:
description: The command's exit status. The step fails with it when it is not zero.

Expand Down
22 changes: 19 additions & 3 deletions actions/terragrunt/report/lib/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import { render, streamLine } from "./report.mjs";

export const DEFAULT_REPORT_NAME = "terragrunt-report.md";

// Next to the report and named after all of it, so two runs in one job with
// a report path each also get a comment path each, even `plan` and `plan.md`.
export function commentPathOf(reportPath) {
return `${reportPath}.comment.md`;
}

// Thrown for anything a caller can fix by editing their workflow, so main can
// report it as a GitHub error annotation rather than a stack trace.
export class InputError extends Error {}
Expand Down Expand Up @@ -86,11 +92,13 @@ export async function run({
}) {
const lines = [];
let streamError;
const commentPath = commentPathOf(reportPath);

// Gone before anything runs, so the path never holds a report from an earlier
// run in the job. A render that fails returns no path, but a later step
// reading the default path directly would otherwise post the old report.
fs.rmSync(reportPath, { force: true });
fs.rmSync(commentPath, { force: true });

// `exec 2>&1` inside the shell rather than two pipes merged here, because two
// pipes are read in whatever order they become ready, and a diagnostic would
Expand Down Expand Up @@ -154,7 +162,7 @@ export async function run({
report = render({ lines, root, title, preamble });
} catch (error) {
warning(`The run finished with status ${exitCode} but rendering its report did not: ${error.message}`);
return { exitCode: exitCode === 0 ? 1 : exitCode, reportPath: "" };
return { exitCode: exitCode === 0 ? 1 : exitCode, reportPath: "", commentPath: "" };
}

if (report.records === 0) {
Expand All @@ -165,6 +173,13 @@ export async function run({

fs.mkdirSync(path.dirname(reportPath), { recursive: true });
fs.writeFileSync(reportPath, report.markdown, "utf8");
// Empty rather than absent when there is nothing to review, so a comment
// step can tell "take down the comment an earlier push left" from "the step
// that writes this never got that far". The report itself stays whole,
// because the job summary and anything parsing the file still want every
// unit. A failed command is never quiet, whatever the log says.
const quiet = exitCode === 0 && report.unchanged;
fs.writeFileSync(commentPath, quiet ? "" : report.markdown, "utf8");

if (summary) {
if (process.env.GITHUB_STEP_SUMMARY) {
Expand All @@ -174,13 +189,14 @@ export async function run({
}
}

return { exitCode, reportPath };
return { exitCode, reportPath, commentPath };
}

export async function main() {
try {
const { exitCode, reportPath } = await run(readInputs());
const { exitCode, reportPath, commentPath } = await run(readInputs());
setOutput("report-path", reportPath);
setOutput("comment-path", commentPath);
setOutput("exit-code", String(exitCode));
if (exitCode !== 0) {
// Not `setFailed`: the command has already said what went wrong, in the
Expand Down
13 changes: 12 additions & 1 deletion actions/terragrunt/report/lib/report.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ export function verdict(body) {
if (line.startsWith("Apply complete! Resources: ")) {
line = line.slice("Apply complete! Resources: ".length);
}
// An apply that touched no resource but changed an output still changed
// something, and calling it a no-op would hide it.
if (isNoop(line) && body.includes("Changes to Outputs")) return "outputs only";
return line;
}
if (body.includes("Changes to Outputs")) return "outputs only";
Expand Down Expand Up @@ -241,6 +244,9 @@ export function render({ lines, root, title, preamble = "" }) {
let spent = 0;
let budgetHit = false;
let failed = false;
// A unit whose output named no outcome at all may have converged or may
// not; it still sits in the quiet table, but it never makes the run quiet.
let unknown = false;

for (const unit of unitsOf(records, root)) {
// The two streams are trimmed apart and joined afterwards rather than
Expand Down Expand Up @@ -271,6 +277,7 @@ export function render({ lines, root, title, preamble = "" }) {
// unit missing from the report and a unit that converged are not the same
// thing, and a reviewer cannot tell them apart.
if (isNoop(unitVerdict)) {
if (unitVerdict === "no output") unknown = true;
quiet += `| \`${unit}\` | ${unitVerdict} |\n`;
continue;
}
Expand Down Expand Up @@ -340,5 +347,9 @@ export function render({ lines, root, title, preamble = "" }) {
out += "</details>\n";
}

return { markdown: out, records: records.length };
// Nothing to review: every unit ran and left its provider as it found it.
// A failure, a change or a run with no unit at all is never unchanged.
const unchanged = !failed && !unknown && rows === "" && quiet !== "";

return { markdown: out, records: records.length, unchanged };
}
58 changes: 58 additions & 0 deletions tests/node/sticky-comment/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,64 @@ test("an empty path skips without calling GitHub", async () => {
assert.equal(github.calls.length, 0);
});

test("an empty file deletes the comment an earlier run left", async () => {
const github = fakeGitHub({ pages: [[comment({ databaseId: 5 })]] });
const result = await run({
inputs: { path: reportFile(""), marker: "plan", token: "t" },
event: EVENT,
env: ENV,
fetch: github.fetch,
});

assert.deepEqual(result, { action: "deleted", ids: [5] });
const [write, ...rest] = writes(github.calls);
assert.equal(rest.length, 0);
assert.equal(write.method, "DELETE");
assert.equal(write.url, "https://api.example.test/repos/acme/widgets/issues/comments/5");
});

test("an empty file deletes every duplicate under the marker", async () => {
const github = fakeGitHub({ pages: [[comment({ databaseId: 5 }), comment({ databaseId: 6 })]] });
const result = await run({
inputs: { path: reportFile(""), marker: "plan", token: "t" },
event: EVENT,
env: ENV,
fetch: github.fetch,
});

assert.deepEqual(result, { action: "deleted", ids: [5, 6] });
assert.deepEqual(
writes(github.calls).map((call) => [call.method, call.url.split("/").at(-1)]),
[["DELETE", "5"], ["DELETE", "6"]],
);
});

test("an empty file with no earlier comment posts nothing", async () => {
const github = fakeGitHub({ pages: [[comment({ body: "<!-- other -->\nold" })]] });
const result = await run({
inputs: { path: reportFile("\n"), marker: "plan", token: "t" },
event: EVENT,
env: ENV,
fetch: github.fetch,
});

assert.equal(result.action, "skipped");
assert.equal(writes(github.calls).length, 0);
});

test("an empty file never deletes a comment another account wrote", async () => {
const github = fakeGitHub({ pages: [[comment({ author: { login: "someone" } })]] });
const result = await run({
inputs: { path: reportFile(""), marker: "plan", token: "t" },
event: EVENT,
env: ENV,
fetch: github.fetch,
});

assert.equal(result.action, "skipped");
assert.equal(writes(github.calls).length, 0);
});

test("a refused write names the status", async () => {
const fetch = async () => new Response("Resource not accessible by integration", { status: 403 });
await assert.rejects(
Expand Down
Loading
Loading