Skip to content

Commit

Permalink
fix: hide-previous-comment now can handel matrix strategy runs when…
Browse files Browse the repository at this point in the history
… given a unique `comment-header` (#78)

* Updated filtering logic

* chore: added some print statements

* fix: Updated the bundled version via yarn run v1.22.22
$ ncc build index.js --out dist --license licenses.txt
ncc: Version 0.33.4
ncc: Compiling file index.js into CJS
 36kB  dist/licenses.txt
900kB  dist/index.js
936kB  [744ms] - ncc 0.33.4
Done in 1.00s.

* chore(docs): Updates readme to inform users of  to leverage custom  when using the action in a matrix

---------

Co-authored-by: Jarrett Gaither <jarrett.gaither@liatrio.com>
  • Loading branch information
jburns24 and jarrettgaither authored Dec 12, 2024
1 parent cc42bc1 commit 95ca081
Show file tree
Hide file tree
Showing 3 changed files with 287 additions and 204 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ Implementing this Action is _super_ simple and the comments are consise and easy
**Optional** Defaults to `false`

- Will hide/minimize all previous comments generated by this action.
- When using this feature within a matrix, ensure you set `comment-header` to a unique value per matrix job (e.g., `comment-header: Plan Summary for ${{ matrix.module }}`). This ensures the action can properly identify and manage comments from each matrix job independently.

### `log-changed-resources`

Expand Down
249 changes: 145 additions & 104 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12818,22 +12818,24 @@ const core = __nccwpck_require__(2186);
const github = __nccwpck_require__(5438);
const fs = __nccwpck_require__(7147);

const expandDetailsComment = core.getBooleanInput('expand-comment');
const includePlanSummary = core.getBooleanInput('include-plan-job-summary');
const myToken = core.getInput('github-token');
const expandDetailsComment = core.getBooleanInput("expand-comment");
const includePlanSummary = core.getBooleanInput("include-plan-job-summary");
const myToken = core.getInput("github-token");
const octokit = github.getOctokit(myToken);
const context = github.context;
const inputFilenames = core.getMultilineInput('json-file');
const commentHeader = core.getMultilineInput('comment-header');
const commentFooter = core.getMultilineInput('comment-footer');
const quietMode = core.getBooleanInput('quiet');
const includeLinkToWorkflow = core.getBooleanInput('include-workflow-link');
const hidePreviousComments = core.getBooleanInput('hide-previous-comments');
const logChangedResources = core.getBooleanInput('log-changed-resources');

const workflowLink = includeLinkToWorkflow ? `
[Workflow: ${context.workflow}](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId })
` : "";
const inputFilenames = core.getMultilineInput("json-file");
const commentHeader = core.getMultilineInput("comment-header");
const commentFooter = core.getMultilineInput("comment-footer");
const quietMode = core.getBooleanInput("quiet");
const includeLinkToWorkflow = core.getBooleanInput("include-workflow-link");
const hidePreviousComments = core.getBooleanInput("hide-previous-comments");
const logChangedResources = core.getBooleanInput("log-changed-resources");

const workflowLink = includeLinkToWorkflow
? `
[Workflow: ${context.workflow}](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})
`
: "";

var hasNoChanges = false;

Expand Down Expand Up @@ -12863,17 +12865,17 @@ const commentsQuery = /* GraphQL */ `
`;

const output = () => {
let body = '';
let body = "";
// for each file
for (const file of inputFilenames) {
const resource_changes = JSON.parse(fs.readFileSync(file)).resource_changes;
try {
let changed_resources = resource_changes.filter((resource) => {
return resource.change.actions != ["no-op"];
})
});

if (logChangedResources) {
console.log("changed_resources", changed_resources)
console.log("changed_resources", changed_resources);
}
if (Array.isArray(resource_changes) && resource_changes.length > 0) {
const resources_to_create = [],
Expand Down Expand Up @@ -12922,26 +12924,36 @@ ${details("delete", resources_to_delete, "-")}
${details("update", resources_to_update, "!")}
${details("replace", resources_to_replace, "+")}
</details>
${commentFooter.map(a => a == '' ? '\n' : a).join('\n')}
${commentFooter.map((a) => (a == "" ? "\n" : a)).join("\n")}
${workflowLink}
`
if (resources_to_create + resources_to_delete + resources_to_update + resources_to_replace == []) {
`;
if (
resources_to_create +
resources_to_delete +
resources_to_update +
resources_to_replace ==
[]
) {
hasNoChanges = true;
}
} else {
hasNoChanges = true;
console.log("No changes found in the plan. setting hasNoChanges to true.")
console.log(
"No changes found in the plan. setting hasNoChanges to true.",
);
body += `
<p>There were no changes done to the infrastructure.</p>
`
core.info(`"The content of ${file} did not result in a valid array or the array is empty... Skipping."`)
`;
core.info(
`"The content of ${file} did not result in a valid array or the array is empty... Skipping."`,
);
}
} catch (error) {
core.error(`${file} is not a valid JSON file. error: ${error}`);
}
}
return body;
}
};

const details = (action, resources, operator) => {
let str = "";
Expand All @@ -12954,108 +12966,137 @@ const details = (action, resources, operator) => {
for (const el of resources) {
// In the replace block, we show delete (-) and then create (+)
if (action === "replace") {
str += `- ${el}\n`
str += `- ${el}\n`;
}
str += `${operator} ${el}\n`
str += `${operator} ${el}\n`;
}

str += "```\n"
str += "```\n";
}

return str;
}
};

const queryComments = (variables) => {
return octokit.graphql(commentsQuery, variables);
return octokit.graphql(commentsQuery, variables);
};

const minimizeComment = (variables) => {
return octokit.graphql(minimizeCommentQuery, variables);
return octokit.graphql(minimizeCommentQuery, variables);
};

const hideComments = () => {
core.info(`Hiding previous comments.`);

queryComments({
owner: context.repo.owner,
name: context.repo.repo,
number: context.issue.number
})
.then(response => {
core.info(`Successfully retrieved comments for PR #${context.issue.number}.`);
const comments = response.repository.pullRequest.comments.nodes;
core.info(`Hiding previous comments.`);

core.info(`Found ${comments.length} comments in the PR.`);
queryComments({
owner: context.repo.owner,
name: context.repo.repo,
number: context.issue.number,
})
.then((response) => {
core.info(
`Successfully retrieved comments for PR #${context.issue.number}.`,
);
const comments = response.repository.pullRequest.comments.nodes;

core.info(`Found ${comments.length} comments in the PR.`);

core.info(`Comment header used for matching is: ${commentHeader}`);

filteredComments = comments.filter(
(comment) =>
comment.body.includes("Terraform Plan:") ||
comment.body.includes(
"There were no changes done to the infrastructure.",
),
);

core.info(
`Filtered down to ${filteredComments.length} comments created by this action.`,
);

filteredComments = filteredComments.filter((comment) =>
comment.body.includes(commentHeader),
);

core.info(
`Filtered down to ${filteredComments.length} comments that need to be minimized.`,
);

const minimizePromises = filteredComments
.filter((comment) => !comment.isMinimized)
.map((comment) => {
return minimizeComment({ id: comment.id }).catch((error) =>
core.error(
`Failed to minimize comment ${comment.id}: ${error.message}`,
),
);
});

const filteredComments = comments.filter(comment =>
comment.body.includes('Terraform Plan:') ||
comment.body.includes('There were no changes done to the infrastructure.')
return Promise.all(minimizePromises)
.then(() => core.info("All minimize operations completed."))
.catch((error) =>
core.error(`Error during minimize operations: ${error.message}`),
);

core.info(`Filtered down to ${filteredComments.length} comments that need to be minimized.`);

const minimizePromises = filteredComments
.filter(comment => !comment.isMinimized)
.map(comment => {
return minimizeComment({ id: comment.id })
.catch(error => core.error(`Failed to minimize comment ${comment.id}: ${error.message}`));
});

return Promise.all(minimizePromises)
.then(() => core.info('All minimize operations completed.'))
.catch(error => core.error(`Error during minimize operations: ${error.message}`));
})
.catch(error => core.error(`Failed to retrieve comments: ${error.message}`));
})
.catch((error) =>
core.error(`Failed to retrieve comments: ${error.message}`),
);
};


try {
let rawOutput = output();
let createComment = true;

console.log("hidePreviousComments", hidePreviousComments)
console.log("hidePreviousComments && context.eventName === pull_request", hidePreviousComments && context.eventName === 'pull_request')
if (hidePreviousComments && context.eventName === 'pull_request') {
hideComments();
}

console.log("includePlanSummary", includePlanSummary)
if (includePlanSummary) {
core.info("Adding plan output to job summary")
core.summary.addHeading('Terraform Plan Results').addRaw(rawOutput).write()
}

console.log("quietMode", quietMode)
console.log("hasNoChanges", hasNoChanges)
console.log("quietMode && hasNoChanges", quietMode && hasNoChanges)
if (quietMode && hasNoChanges) {
core.info("quiet mode is enabled and there are no changes to the infrastructure.")
core.info("Skipping comment creation.")
createComment = false
}

if (context.eventName === 'pull_request') {
core.info(`Found PR # ${context.issue.number} from workflow context - proceeding to comment.`)
} else {
core.info("Action doesn't seem to be running in a PR workflow context.")
core.info("Skipping comment creation.")
createComment = false
}

if (createComment) {
core.info("Adding comment to PR");
core.info(`Comment: ${rawOutput}`);
octokit.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: rawOutput
});
core.info("Comment added successfully.");
}
let rawOutput = output();
let createComment = true;

console.log("hidePreviousComments", hidePreviousComments);
console.log(
"hidePreviousComments && context.eventName === pull_request",
hidePreviousComments && context.eventName === "pull_request",
);
if (hidePreviousComments && context.eventName === "pull_request") {
hideComments();
}

console.log("includePlanSummary", includePlanSummary);
if (includePlanSummary) {
core.info("Adding plan output to job summary");
core.summary.addHeading("Terraform Plan Results").addRaw(rawOutput).write();
}

console.log("quietMode", quietMode);
console.log("hasNoChanges", hasNoChanges);
console.log("quietMode && hasNoChanges", quietMode && hasNoChanges);
if (quietMode && hasNoChanges) {
core.info(
"quiet mode is enabled and there are no changes to the infrastructure.",
);
core.info("Skipping comment creation.");
createComment = false;
}

if (context.eventName === "pull_request") {
core.info(
`Found PR # ${context.issue.number} from workflow context - proceeding to comment.`,
);
} else {
core.info("Action doesn't seem to be running in a PR workflow context.");
core.info("Skipping comment creation.");
createComment = false;
}

if (createComment) {
core.info("Adding comment to PR");
core.info(`Comment: ${rawOutput}`);
octokit.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: rawOutput,
});
core.info("Comment added successfully.");
}
} catch (error) {
core.setFailed(error.message);
core.setFailed(error.message);
}

})();
Expand Down
Loading

0 comments on commit 95ca081

Please sign in to comment.