github actions | get origin branch on push - github

I want that a workflow that starts on push will print the origin (base) branch name and name of the one who did the push.
for example if my name is Tom and I merged 'test' branch to master, I will be able to get 'Tom' and 'test' as values on the workflow that starts on push (right after the pull request).
I did find something that works on pull request to get the base branch name: ${{ github.event.pull_request.head.ref }}, but when replacing 'pull_request' with push it doesn't work anymore.
Is there a way to do it?
I've been searching for hours now and can't find a proper solution, for each type of event there is a different solution.
Thank you for reading!

You can use the following properties of the github context:
github.ref_name
github.event.pusher.name (see: push event payload)
Here is an example of a complete workflow:
name: show-push-info
on:
push:
jobs:
print-info:
runs-on: ubuntu-latest
steps:
- name: Print info
run: echo "'${{ github.ref_name }}' was pushed by '${{ github.event.pusher.name }}'"

Related

Github Actions to see changed files

I am trying to use actions to post a comment on a PR if a file has changed but my action is unable to see the changes.
jobs:
check:
runs-on: self-hosted
permissions:
pull-requests: write
steps:
- uses: actions/checkout#v2
with:
fetch-depth: 2
- name: Get all changed files and echo alert
env:
GITHUB_TOKEN: *******************
run: |
git diff --name-status
or if I change it to git status it outputs a message saying no changes working tree is clean, but I know one file has changed.
I tried using v1 instead of v2 but that doesn't work either.
Does anyone have any ideas on what i am doing wrong or how I can get this working?
Checkout is just "checking out" clean repository state for a given commit or PR.
If you expect to get changes files from PR, you can do it by using external actions, for examples:
- name: Get changed files using defaults
id: changed-files
uses: tj-actions/changed-files#v32
- name: List all added files
run: |
for file in ${{ steps.changed-files.outputs. modified_files }}; do
echo "$file was modified."
done
Use Github contexts: Learn GitHub Actions Contexts
Here is the command you probably need:
git diff --name-only ${{ github.event.after }} ${{ github.event.before }}
Also, you could affect the whole action by setting paths at the beginning of an action:
name: Action #1
on:
push:
branches:
- main
paths:
- <folder>/** // action will be triggered by push to the main branch AND when there are changed files in <folder>
pull_request:
branches:
- main
paths:
- <folder>/*.js // action will be triggered only on pull-requests AND when any .js files in <folder> have been changed

Run Github Action only when a push to main comes from a branch with a certain name

I have a Github Action that deploys my app from the main branch when there is a push to it or a merge from a pull request:
'on':
push:
branches:
- main
jobs:
build_and_deploy:
What I am trying to accomplish is to only run the action if the pull request comes from a branch that does not contain the string "nodeploy/" in its name.
I tried this:
'on':
push:
branches:
- main
jobs:
build_and_deploy:
if: ${{ !startsWith(github.head_ref, 'nodeploy/') }}
but it didn't work.
I believe it doesn't work because the value of github.head_ref is always main in this case.
Are there any solutions to this?
I found a solution. As suggested in the comments, I checked the message in the head commit.
'on':
push:
branches:
- main
jobs:
build_and_deploy:
if: ${{ !contains(github.event.head_commit.message, 'nodeploy/') }}
And now it does what I wanted.
Be aware that if you change the automatically generated merge message it won't work.

Create pull request with github action

I'm trying to make it work this action, but I'm confused also whats it's missing in between, before triggering the peter-evans PR.
The scenario is pretty simple, I like on push, on any feature/* branch, to create automatically PR, but instead I'm getting weird scenario, where develop changes are applied on top of the feature/* branch. Can someone give me hints on this?
name: Pull Request Action
on:
push:
branches:
- feature/*
jobs:
create-pull-request:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout#v2
with:
fetch-depth: 0
ref: develop
- name: Create Pull Request
uses: peter-evans/create-pull-request#v3.10.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: Simple demo
title: '[Example] Simple demo'
body: >
This PR is auto-generated by
[create-pull-request](https://github.com/peter-evans/create-pull-request).
labels: feature, automated pr
branch: feature/workflow-demo
Just posting this as an alternative solution. If you don't want to use any 3rd party actions you can achieve this with actions/github-script, it will just require a bit more coding.
As this stands, the action will error if there is already an open PR for the feature branch. If this is an issue you could check of an existing PR with the github.rest.pulls.list method, filtering by both head and base so it will only return one or no PRs.
name: Pull Request Action
on:
push:
branches:
- feature/*
jobs:
create-pull-request:
runs-on: ubuntu-latest
steps:
- name: Create Pull Request
uses: actions/github-script#v6
with:
script: |
const { repo, owner } = context.repo;
const result = await github.rest.pulls.create({
title: '[Example] Simple demo',
owner,
repo,
head: '${{ github.ref_name }}',
base: 'develop',
body: [
'This PR is auto-generated by',
'[actions/github-script](https://github.com/actions/github-script).'
].join('\n')
});
github.rest.issues.addLabels({
owner,
repo,
issue_number: result.data.number,
labels: ['feature', 'automated pr']
});
I know this question is a year old now and asking about the create-pull-request action, but for those that would rather not use third-party actions, Github actions now support Github command line natively, if you use Github hosted runners. See: Using Github CLI in Workflows
This makes it super easy to create a pull request using the gh pr create command
Something like this:
steps:
- name: create pull request
run: gh pr create -B base_branch -H branch_to_merge --title 'Merge branch_to_merge into base_branch' --body 'Created by Github action'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Reading through the readme, the action by Peter Evans doesn't fit what you're trying to achieve. But you can use repo-sync's pull-request action:
name: Pull Request Action
on:
push:
branches:
- feature/*
jobs:
create-pull-request:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout#v2
- name: pull-request
uses: repo-sync/pull-request#v2
with:
destination_branch: "develop"
github_token: ${{ secrets.GITHUB_TOKEN }}
pr_label: "feature, automated pr"
pr_title: "[Example] Simple demo"
You might need to specify the base branch there:
- name: Create Pull Request
uses: peter-evans/create-pull-request#v3.10.1
with:
token: ${{ secrets.GH_TOKEN }}
commit-message: Auto Pull Request
title: Your desired title
body: Auto-created Pull Request
branch: ${{ github.ref }} # The branch where you commit
base: develop # Don't forget to specify the right base branch here
I have this and it creates the PR when it does not exist. I remember it didn't work exactly right at the beginning until I specified myself base and branch values, which are not very clear in the docs.

Getting base branch SHA on pull request in Github Action Workflow

In GitHub action on pull request, I need to run some code in the context of the "current master", and later re-run the same code in the context of the PR branch.
I can check out compare a pull request to the base it is being PR-ed against. How would I find the SHA of the base branch (e.g. current master if PR is against the master)?
jobs:
job_on_base:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
ref: "${{ github.base_ref }}"
- run: |
# Seems like I can get it here with $(git log -1 --format="%H")
echo "My current SHA is ... ?"
job_on_pr:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
ref: "${{ github.ref }}"
- run: |
echo "My current SHA is $GITHUB_SHA"
echo "The BASE SHA is ?"
If the job runs on a pull_request event the base sha is available as ${{ github.event.pull_request.base.sha }}
This turned out to be a git question, rather than Github actions. The actions/checkout#v2 creates a shallow --depth=1 clone, so to get PR's parent one can parse git cat-file -p output as described here. The first (base) parent could be accessed with
git cat-file -p <SHA> | awk 'NR > 1 {if(/^parent/){print $2; exit}}'
The better approach turned out to be using fetch-depth: 2 parameter. It allows just one job to handle both pull request and master merge cases, and can also be used with HEAD^1 to get to the parent.
steps:
- uses: actions/checkout#v2
with:
fetch-depth: 2
What worked for me was: github.event.workflow_run.head_sha.
The top-voted answer suggesting github.event.pull_request.head.sha didn't work for me.
I found this by examining all the possible data in the github.context object using the method suggested here - https://stackoverflow.com/a/70107953

Ways to get last commit author in Github Actions workflow

I am working on converting a Jenkins Pipeline into a Github Actions workflow and need a way of storing the commit author as an environment variable for later use in node.js code.
I have read the documentation and this seems to be the only way I can get it working:
name: Feature Branch PR
on:
pull_request:
types: [opened, edited, synchronize]
push:
branches:
- '**'
Then in the Env section:
env:
AUTHOR: ${{ github.event.pusher.name }}
The problem is this only works for Push triggers. So if i remove the on: push section from top of yml workflow (so it only triggers on PRs) the AUTHOR info becomes empty.
I cannot find a way to get it for commits. Does anyone know of of a way? We do not want this workflow to trigger on pushes.
I also tried
AUTHOR: $(jq '.commits.committer.name' $GITHUB_EVENT_PATH)
I think this was syntactically incorrect though.
For anyone who struggles with this in future, I managed to work it out.
In the node code (not yml) you can obtain an Actions event.json file with all info available. To get the author of a previous commit:
const ev = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'));
return ev.pull_request.user.login;
As YakovL mentioned,
env:
${{ github.event.pull_request.user.login }}
Works fine in a Github action.
To answer the question that was originally asked, you can do the following to get the author of the last commit in a GitHub action:
github.event.commits[0].author.name
For example (to prevent a loop in an action using a personal access token):
name: Version and Package Repo
on:
push:
branches: [ master, main ]
jobs:
build:
if: github.event.commits[0].author.name != 'GitHubActions'
runs-on: ubuntu-18.04
steps:
- name: Checkout repo
uses: actions/checkout#v2
with:
fetch-depth: 0
token: ${{ secrets.PAT }}
- name: Configure git
run: |
git config user.name "GitHubActions"
git config user.email "<>"
- name: Version and Package
run: npm version patch --force
env:
NODE_AUTH_TOKEN: $\{{ secrets.PAT }}
- name: Update git
run: |
git push
git push --tags
You can use this in the interpolation format too:
${github.event.commits[0].author.name}
And if you need to use different github context variables, they are documented at:
https://docs.github.com/en/actions/learn-github-actions/environment-variables
https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#push
Annoyingly, the user details are in different formats for different event types, but in addition to example above (for push), you could try github.event.head.user.login or github.event.base.user.login too