-
Notifications
You must be signed in to change notification settings - Fork 541
-
Hi, I would like to strip out snippets of JS code into separate files outside of YAML for ease of legibility. However, I'm struggling to understand how best to achieve something this.
Before/Current
script: | const { data: list_comments } = await github.rest.issues.listComments({ issue_number: context.issue.number, owner: context.repo.owner, per_page: 100, repo: context.repo.repo, }); const get_comment = list_comments .sort((a, b) => b.id - a.id) .find((comment) => /^keyword/.test(comment.body)); return { body: get_comment.body, id: get_comment.id, };
After/Proposed
script: | require(process.env.GITHUB_ACTION_PATH + '/comment.js');
// File: comment.js const { data: list_comments } = await github.rest.issues.listComments({ issue_number: context.issue.number, owner: context.repo.owner, per_page: 100, repo: context.repo.repo, }); const get_comment = list_comments .sort((a, b) => b.id - a.id) .find((comment) => /^keyword/.test(comment.body)); return { body: get_comment.body, id: get_comment.id, };
With this, I get: "SyntaxError: await is only valid in async functions and the top level bodies of modules."
If I drop the await, then I get: "ReferenceError: github is not defined."
I'm sure I'm missing something obvious with module.exports = ({ github, context }) => { ... }, but I'm not sure how best to address this particular script which: makes an API call, processes the response, and returns the output in that specific order.
Really appreciate any thoughts/inputs, thanks for your time.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
I shared an example script here that got @rdhar on the right path.
The crux of the solution is that:
- The script to be referenced is
requireed in the script step that needs re-usable code as an exported function. - Async functions need to be
awaited in the calling script step.
Beta Was this translation helpful? Give feedback.
All reactions
-
Thank you for sharing, @yhakbar!
That script setup and module.exports = async... is exactly what was needed -- the only tweak was to replace the return { ... } with core.setOutput(), like so:
// Before return { body: get_comment.body, id: get_comment.id, }; // After core.setOutput("body", get_comment.body); core.setOutput("id", get_comment.id);
Similarly, I had to amend references to the output result within the action.yml workflow as well:
# Before fromJSON(steps.comment.outputs.result)['body'] fromJSON(steps.comment.outputs.result)['id'] # After steps.comment.outputs.body steps.comment.outputs.id
Beta Was this translation helpful? Give feedback.