I want to access the Pull Request number in a Github Actions workflow. I can access the GITHUB_REF environment variable that is available. Although on a Pull Request action it has the value: "refs/pull/125/merge". I need to extract just the "125".
I have found a similar post here that shows how to get the current branch using this variable. Although in this case, what I am parsing is different and I have been unable to isolate the Pull Request number.
I have tried using {GITHUB_REF##*/} which resolves to "merge"
I have also tried {GITHUB_REF#*/} which resolves to "pull/125/merge"
I only need the Pull Request number (which in my example is 125)
Although it is already answered, the easiest way I found is using the github context. The following example shows how to set it to an environment variable.
env:
PR_NUMBER: ${{ github.event.number }}
An alternative if you are trying to figure out which PR a commit is linked to on a push instead of a pull_request event is to use the gh CLI which is included in the standard GitHub Action images.
For example:
- name: Get Pull Request Number
id: pr
run: echo "::set-output name=pull_request_number::$(gh pr view --json number -q .number || echo "")"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Be sure to add pull_request: read permissions on the job as well.
Then in following steps, you can access it with the variable,
${{ steps.pr.outputs.pull_request_number }}
While the answer by #Samira worked correctly. I found out that there is a new way to do this and wanted to share it with anyone who might stumble upon this.
The solution is to add a stage at the beginning of your workflow which gets the PR number from the Github Token (event) and then set it as an environment variable for easy use throughout the rest of the workflow. Here is the code:
- name: Test
uses: actions/github-script#0.3.0
with:
github-token: ${{github.token}}
script: |
const core = require('#actions/core')
const prNumber = context.payload.number;
core.exportVariable('PULL_NUMBER', prNumber);
Now in any later stage, you can simply use $PULL_NUMBER to access the environment variable set before.
How about using awk to extract parts of GITHUB_REF instead of bash magick?
From awk manpage:
-F fs
--field-separator fs
Use fs for the input field separator (the value of the FS predefined variable).
As long you remember this, it's trivial to extract only part of variable you need. awk is available on all platforms, so step below will work everywhere:
- run: echo ::set-env name=PULL_NUMBER::$(echo "$GITHUB_REF" | awk -F / '{print $3}')
shell: bash
Just gonna drop what worked out for me
- id: find-pull-request
uses: jwalton/gh-find-current-pr#v1
with:
# Can be "open", "closed", or "all". Defaults to "open".
state: open
- name: create TODO/FIXME comment body
id: comment-body
run: |
yarn leasot '**/*.{js,ts,jsx,tsx}' --ignore 'node_modules/**/*' --exit-nicely --reporter markdown > TODO.md
body="$(sed 1,2d TODO.md)"
body="${body//'%'/'%25'}"
body="${body//$'\n'/'%0A'}"
body="${body//$'\r'/'%0D'}"
echo "::set-output name=body::$body"
- name: post TODO/FIXME comment to PR
uses: peter-evans/create-or-update-comment#v2
with:
issue-number: ${{ steps.find-pull-request.outputs.number }}
body: ${{ steps.comment-body.outputs.body }}
Here's a working snippet to get the issue number in both push and pull_request events within a GitHub Actions workflow by leveraging actions/github-script:
steps:
- uses: actions/github-script#v6
id: get_issue_number
with:
script: |
if (context.issue.number) {
// Return issue number if present
return context.issue.number;
} else {
// Otherwise return issue number from commit
return (
await github.rest.repos.listPullRequestsAssociatedWithCommit({
commit_sha: context.sha,
owner: context.repo.owner,
repo: context.repo.repo,
})
).data[0].number;
}
result-encoding: string
- name: Issue number
run: echo '${{steps.get_issue_number.outputs.result}}'
The script queries the list labels for an issue REST API endpoint via octokit/rest.js client.
Related
Let's say I have a pull request like this.
name: Workflow
on:
pull_request:
paths:
- '**/*.h'
- '**/*.c'
I protect the master branch by configuring GitHub Actions to require the status check to pass before the pull request is mergable.
Now I update a readme doc. I open a pull request against master. The pull request is unmergable because the status check never returns a success nor does it return a fail.
Suggestions?
The docs suggest creating another action with the same name, that runs when the opposite condition is met. In your case, you'd want
name: Workflow
on:
pull_request:
paths-ignore:
- '**/*.h'
- '**/*.c'
jobs:
build:
runs-on: ubuntu-latest
steps:
- run: 'echo "No build required" '
Notice the paths-ignore.
https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/troubleshooting-required-status-checks#handling-skipped-but-required-checks
The answer provided by the docs (Vicky's answer) doesn't work correctly for me. Providing multiple values for paths-ignore isn't preventing the generic/duplicate workflow from running. Since the original and the duplicate/generic workflow both run, we're still able to merge before the check finishes unfortunately.
This commit on Github shows a viable way of handling it that isn't too complicated:
https://github.com/android-password-store/Android-Password-Store/commit/0c45bffaba1192ea8a10173e709f439dbf32b089#diff-87ee5504a3e25ac558b343724c905f2f7949e8cec3d92b9c4300bb922afa164f
The relevant snippet (under "steps"):
- name: Check if relevant files have changed
uses: actions/github-script#0.9.0
id: service-changed
with:
result-encoding: string
script: |
const result = await github.pulls.listFiles({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
pull_number: context.payload.number,
per_page: 100
})
const serviceChanged = result.data.filter(f => f.filename.startsWith("app/") || f.filename.endsWith("gradle") || f.filename.startsWith(".github") || f.filename.startsWith("gradle") || f.filename.endsWith("properties")).length > 0
console.log(serviceChanged)
return serviceChanged
- name: Checkout repository
if: ${{ steps.service-changed.outputs.result == 'true' }}
uses: actions/checkout#v1
- name: Copy CI gradle.properties
if: ${{ steps.service-changed.outputs.result == 'true' }}
run: mkdir -p ~/.gradle ; cp .github/ci-gradle.properties ~/.gradle/gradle.properties
Here are some other options I've found that look less viable or much more complicated:
https://github.com/fkirc/skip-duplicate-actions Looks questionable at solving this particular problem
https://brunoscheufler.com/blog/2022-04-24-required-github-actions-jobs-in-a-monorepo Looks awfully complicated but viable
https://blog.pantsbuild.org/skipping-github-actions-jobs-without-breaking-branch-protection/ Looks complicated, and it turns into a sales pitch
I want to try to implement that whenever I make a new release in github, actions will automatically publish the corresponding release to pypi for me, but this requires me to get the latest release number.
I've tracked some of stackoverflow's related question, but embarrassingly none of them work for me. For example in #16241
My error message is:
Set output
Run echo ::set-output name=tag::${GITHUB_REF#refs/*/}
::set-output
name=tag::
Test
Run echo $RELEASE_VERSION
Write-Output: D:\a\_temp\7fa75053-482a-4be6-bec1-6b0f60cdf855.ps1:3
Line |
3 | echo
| ~~~~
| Cannot process command because of one or more missing mandatory parameters: InputObject.
Error: Process completed with exit code 1.
I'm running on a windows vm, is there something wrong with my code? Thanks.
You can get this by setting your publish workflow to run on the following event:
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
Then you'll be able to get the tag itself with the github.ref context in your job.
Here is the answer on How to get Tag Name in GitHub Actions
on:
push:
tags:
- '*'
jobs:
github-example-tags:
steps:
- name: GitHub Tag Name example
run: |
echo "Tag name from GITHUB_REF_NAME: $GITHUB_REF_NAME"
echo "Tag name from github.ref_name: ${{ github.ref_name }}"
See
https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
Is there any smart way to determine the default branch in GitHub actions?
Now I need to write something like:
on:
push:
branches:
- master
is there a way to write something like the code below?
on:
push:
branches:
- $default-branch
I tried to google but found nothing
I accidentally found a really nice way to solve this. That evalutes to the branch name, e.g. master.
${{ github.event.repository.default_branch }}
Also, found out the hard way that that always() is side-effecting: my job was getting skipped if always() was not called even though the other clause was true.
This works to run a job only when running on default branch
if: ${{ always() && format('refs/heads/{0}', ) == github.ref }}
$default-branch can be used in Workflow templates, but not in Workflows. The branch will become hard-coded in the Workflow upon initialization, and will have to be manually maintained. [1]
Blog post: https://github.blog/changelog/2020-07-22-github-actions-better-support-for-alternative-default-branch-names/
- if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
run: echo "On the default branch"
- if: github.ref != format('refs/heads/{0}', github.event.repository.default_branch)
run: echo "Not on the default branch"
This is not possible at the moment. Please check this topic on github community
You simply can reach variable at this level
The workflow is not valid. .github/workflows/so-004-variables-in-trigger.yaml (Line: 7, Col: 9): Unrecognized named-value: 'env'. Located at position 1 within expression: env.default-branch
You may consider addition filterint based on the branch name like here but at the moment you can't do what you want.
Add this step to your job:
- name: Determine default branch
run: |
DEFAULT_BRANCH=$(git remote show origin | awk '/HEAD branch/ {print $NF}')
echo "default_branch=$DEFAULT_BRANCH" >> $GITHUB_ENV
echo "default_branch_ref=refs/heads/$DEFAULT_BRANCH" >> $GITHUB_ENV
That will add a default_branch and a default_branch_ref variable to the env enivronment variables.
You can then access the default branch name with ${{ env.default_branch }} in subsequent steps.
The default_branch_ref variable is useful for directly comparing against github.ref to determine whether you are on the default branch.
This method uses the current method of setting environment variables to use in later steps [1] and JoeLinux's method for determining the default branch name [2].
Full example workflow:
name: ci
on: [push, pull_request]
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Determine default branch
run: |
DEFAULT_BRANCH=$(git remote show origin | awk '/HEAD branch/ {print $NF}')
echo "default_branch=$DEFAULT_BRANCH" >> $GITHUB_ENV
echo "default_branch_ref=refs/heads/$DEFAULT_BRANCH" >> $GITHUB_ENV
- name: debug
run: echo ${{ env.default_branch }}
- name: Deploy
if: github.ref == env.default_branch_ref
run: echo "Run!"
You can use $default-branch in a template, and then when that template is rendered into a new repo, it will be replaced with the (then) default branch name for the repo, but that is a very limited use case and still does not help you when the name of the default branch changes. The best I have come up with is to list the all the default branch names in the organization, like this:
on:
push:
branches:
- master
- main
- root
- default
- production
and then you can either trust that the repos will not have non-default branches with those names, or start the jobs and then filter them by adding an if condition like
if: github.event.push.ref == format('refs/heads/{}', github.event.repository.default_branch)
Side note
For most events
${{ github.event.repository.default_branch }}
is available and works fine, but not when running schedule events via cron. When github.event_name == "schedule" the only element in github.event is schedule (the cron string that triggered the run).
When running inside a GitHub action on at GitHub runner with gh available, this more reliably gets you the default branch name:
gh repo view --json defaultBranchRef --jq .defaultBranchRef.name
However, this does not help the OP when you want to make the default branch the target that triggers the run.
Hopefully, there will be a better way to do this in the future. Until then, you can use the GitHub API and save the result in a named step output.
e.g.
- name: Extract default branch name
shell: bash
run: |
owner="my-org"
repo="repo_x"
branch=$(curl -L -H 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
https://api.github.com/repos/${owner}/${repo} \
| jq .default_branch)
echo "##[set-output name=default_branch;]$(echo ${branch})"
id: repo_x
...
${{ steps.repo_x.outputs.default_branch }}
For (mainly) pedagogical reasons, I'm trying to run this workflow in GitHub actions:
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
produce_comment:
name: Respond to issue
runs-on: ubuntu-latest
steps:
- name: Dump job context
env:
JOB_CONTEXT: ${{ jobs.maybe-greet.steps.id }}
run: echo "$JOB_CONTEXT"
I need two different jobs, since they use different context (operating systems), but I need to get the output of a step in the first job to the second job. I am trying with several combinations of the jobs context as found here but there does not seem to be any way to do that. Apparently, jobs is just the name of a YAML variable that does not really have a context, and the context job contains just the success or failure. Any idea?
Check the "GitHub Actions: New workflow features" from April 2020, which could help in your case (to reference step outputs from previous jobs)
Job outputs
You can specify a set of outputs that you want to pass to subsequent jobs and then access those values from your needs context.
See documentation:
jobs.<jobs_id>.outputs
A map of outputs for a job.
Job outputs are available to all downstream jobs that depend on this job.
For more information on defining job dependencies, see jobs.<job_id>.needs.
Job outputs are strings, and job outputs containing expressions are evaluated on the runner at the end of each job. Outputs containing secrets are redacted on the runner and not sent to GitHub Actions.
To use job outputs in a dependent job, you can use the needs context.
For more information, see "Context and expression syntax for GitHub Actions."
To use job outputs in a dependent job, you can use the needs context.
Example
jobs:
job1:
runs-on: ubuntu-latest
# Map a step output to a job output
outputs:
output1: ${{ steps.step1.outputs.test }}
output2: ${{ steps.step2.outputs.test }}
steps:
- id: step1
run: echo "test=hello" >> $GITHUB_OUTPUT
- id: step2
run: echo "test=world" >> $GITHUB_OUTPUT
job2:
runs-on: ubuntu-latest
needs: job1
steps:
- run: echo ${{needs.job1.outputs.output1}} ${{needs.job1.outputs.output2}}
Note the use of $GITHUB_OUTPUT, instead of the older ::set-output now (Oct. 2022) deprecated.
To avoid untrusted logged data to use set-state and set-output workflow commands without the intention of the workflow author we have introduced a new set of environment files to manage state and output.
Jesse Adelman adds in the comments:
This seems to not work well for anything beyond a static string.
How, for example, would I take a multiline text output of step (say, I'm running a pytest or similar) and use that output in another job?
either write the multi-line text to a file (jschmitter's comment)
or base64-encode the output and then decode it in the next job (Nate Karasch's comment)
Update: It's now possible to set job outputs that can be used to transfer string values to downstream jobs. See this answer.
What follows is the original answer. These techniques might still be useful for some use cases.
Write the data to file and use actions/upload-artifact and actions/download-artifact. A bit awkward, but it works.
Create a repository dispatch event and send the data to a second workflow. I prefer this method personally, but the downside is that it needs a repo scoped PAT.
Here is an example of how the second way could work. It uses repository-dispatch action.
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
- name: Repository Dispatch
uses: peter-evans/repository-dispatch#v1
with:
token: ${{ secrets.REPO_ACCESS_TOKEN }}
event-type: my-event
client-payload: '{"greet": "${{ steps.maybe-greet.outputs.GREET }}"}'
This triggers a repository dispatch workflow in the same repository.
name: Repository Dispatch
on:
repository_dispatch:
types: [my-event]
jobs:
myEvent:
runs-on: ubuntu-latest
steps:
- run: echo ${{ github.event.client_payload.greet }}
In my case I wanted to pass an entire build/artifact, not just a string:
name: Build something on Ubuntu then use it on MacOS
on:
workflow_dispatch:
# Allows for manual build trigger
jobs:
buildUbuntuProject:
name: Builds the project on Ubuntu (Put your stuff here)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- uses: some/compile-action#v99
- uses: actions/upload-artifact#v2
# Upload the artifact so the MacOS runner do something with it
with:
name: CompiledProject
path: pathToCompiledProject
doSomethingOnMacOS:
name: Runs the program on MacOS or something
runs-on: macos-latest
needs: buildUbuntuProject # Needed so the job waits for the Ubuntu job to finish
steps:
- uses: actions/download-artifact#master
with:
name: CompiledProject
path: somewhereToPutItOnMacOSRunner
- run: ls somewhereToPutItOnMacOSRunner # See the artifact on the MacOS runner
It is possible to capture the entire output (and return code) of a command within a run step, which I've written up here to hopefully save someone else the headache. Fair warning, it requires a lot of shell trickery and a multiline run to ensure everything happens within a single shell instance.
In my case, I needed to invoke a script and capture the entirety of its stdout for use in a later step, as well as preserve its outcome for error checking:
# capture stdout from script
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code as well
SCRIPT_RC=$?
# FYI, this would get stdout AND stderr
SCRIPT_ALL_OUTPUT=$(./do-something.sh 2>&1)
Since Github's job outputs only seem to be able to capture a single line of text, I also had to escape any newlines for the output:
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
Additionally, I needed to ultimately return the script's exit code to correctly indicate whether it failed. The whole shebang ends up looking like this:
- name: A run step with stdout as a captured output
id: myscript
run: |
# run in subshell, capturiing stdout to var
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code too
SCRIPT_RC=$?
# print a single line output for github
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
# exit with the script status
exit $SCRIPT_RC
continue-on-error: true
- name: Add above outcome and output as an issue comment
uses: actions/github-script#v5
env:
STEP_OUTPUT: ${{ steps.myscript.outputs.stdout }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// indicates whather script succeeded or not
let comment = `Script finished with \`${{ steps.myscript.outcome }}\`\n`;
// adds stdout, unescaping newlines again to make it readable
comment += `<details><summary>Show Output</summary>
\`\`\`
${process.env.STEP_OUTPUT.replace(/\\n/g, '\n')}
\`\`\`
</details>`;
// add the whole damn thing as an issue comment
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
})
Edit: there is also an action to accomplish this with much less bootstrapping, which I only just found.
2022 October update: GitHub is deprecating set-output and recommends to use GITHUB_OUTPUT instead. The syntax for defining the outputs and referencing them in other steps, jobs.
An example from the docs:
- name: Set color
id: random-color-generator
run: echo "SELECTED_COLOR=green" >> $GITHUB_OUTPUT
- name: Get color
run: echo "The selected color is ${{ steps.random-color-generator.outputs.SELECTED_COLOR }}"
I have a workflow with an action that creates a version number when building an artefact. This version number is written to file.
How can I give that as an input to another action?
I.e: How can I use this version number as part of a commit message in another action?
Per the fabulous answer here, there's actually an inline way to accomplish this. Not intuitive at all, except that the ::set-output... syntax matches the same expected output format for GitHub Actions.
The below step loads the VERSION file into ${{ steps.getversion.outputs.version }}:
- name: Read VERSION file
id: getversion
run: echo "::set-output name=version::$(cat VERSION)"
I had the same use case as OP, so I'm pasting below my entire code, which does three things:
Pull first three-parts of the 4-part version string from the file VERSION.
Get a sequential build number using the einaregilsson/build-number#v2 action.
Concatenate these two into an always-unique 4-part version string that becomes a new GitHub release.
name: Auto-Tag Release
on:
push:
branches:
- master
jobs:
release_new_tag:
runs-on: ubuntu-latest
steps:
- name: "Checkout source code"
uses: "actions/checkout#v1"
- name: Generate build number
id: buildnumber
uses: einaregilsson/build-number#v2
with:
token: ${{secrets.github_token}}
- name: Read VERSION file
id: getversion
run: echo "::set-output name=version::$(cat VERSION)"
- uses: "marvinpinto/action-automatic-releases#latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: v${{ steps.getversion.outputs.version }}.${{ steps.buildnumber.outputs.build_number }}
prerelease: false
Fully automated release management! :-)
Note: The branch filter at top ensures that we only run this on commits to master.
It is possible to use the filesystem to communicate between actions. But if you have input on 3rd party actions, you need to give this from the outputs of another action
Ie. you need to read this file in your action and present it as output in your action.yml. Then you can use this output as input to another action in your workflow.yaml
The accepted answer is outdated as per this blog post from GitHub.
It is still possible to do this as one step from your workflow though:
- name: Read VERSION file
id: getversion
run: echo "version=$(cat VERSION)" >> $GITHUB_OUTPUT
This will set an output named version which you can access just as before using ${{ steps.getversion.outputs.version }}:
- uses: "marvinpinto/action-automatic-releases#latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: v${{ steps.getversion.outputs.version }}.${{ steps.buildnumber.outputs.build_number }}
prerelease: false