Ways to get last commit author in Github Actions workflow - github

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

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

Unable to Manually Trigger GitHub Action

I recently started working on using some GitHub actions on my projects. I am able to setup them up to run automatically but am struggling with having them run manually. I know that you need the have the workflow_dispatch in the on section. I'm not sure if it's not working because I have it automatically run too. Is someone able to tell me what I am doing wrong?
Here is one of my workflow YAML files
name: Create-Doc-Nightly
on:
push:
branches: [ "nightly" ]
paths:
- 'src/**'
- 'pom.xml'
workflow_dispatch:
jobs:
doc:
name: Create Doc
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v3
name: Step 1 - Checkout Nightly Branch
with:
persist-credentials: false
fetch-depth: 0
- name: Step 2 - Setup JDK 17
uses: actions/setup-java#v3.4.1
with:
java-version: 17
distribution: 'temurin'
- name: Step 3 - Remove Doc
run: |
git remote set-url origin https://jnstockley:${{ secrets.TOKEN }}#github.com/jnstockley/BTTN.git
git config user.email "jack#jstockley.com"
git config --local user.name "Jack Stockley"
git rm -r docs
git commit -m "Removed Docs"
git push origin nightly
- name: Step 4 - Create Doc
run: mvn dokka:dokka -f pom.xml
- name: Step 5 - Move Docs
run: |
rm -rf docs
mkdir -p docs
mv target/dokka/* docs
- name: Step 6 - Publish docs
run: |
git remote set-url origin https://jnstockley:${{ secrets.TOKEN }}#github.com/jnstockley/BTTN.git
git config user.email "jack#jstockley.com"
git config --local user.name "Jack Stockley"
git add -f docs
git commit -m "Updated Docs"
git push origin nightly
Link to GitHub repo, nightly branch: https://github.com/jnstockley/BTTN/tree/nightly
The workflow must be on your default branch in order to use workflow_dispatch.
I believe in your case it's only on the branch nightly while it should also be on main.
To manually trigger a workflow, use the workflow_dispatch event. You can manually trigger a workflow run using the GitHub API, GitHub CLI, or GitHub browser interface. For more information, see Manually running a workflow
on: workflow_dispatch
Providing inputs
You can configure custom-defined input properties, default input values, and required inputs for the event directly in your workflow. When you trigger the event, you can provide the ref and any inputs. When the workflow runs, you can access the input values in the inputs context. For more information, see Contexts
This example defines inputs called logLevel, tags, and environment. You pass values for these inputs to the workflow when you run it. This workflow then prints the values to the log, using the inputs.logLevel, inputs.tags, and inputs.environment context properties.
yaml
on:
workflow_dispatch:
inputs:
logLevel:
description: 'Log level'
required: true
default: 'warning'
type: choice
options:
- info
- warning
- debug
tags:
description: 'Test scenario tags'
required: false
type: boolean
environment:
description: 'Environment to run tests against'
type: environment
required: true
jobs:
log-the-inputs:
runs-on: ubuntu-latest
steps:
- run: |
echo "Log level: $LEVEL"
echo "Tags: $TAGS"
echo "Environment: $ENVIRONMENT"
env:
LEVEL: ${{ inputs.logLevel }}
TAGS: ${{ inputs.tags }}
ENVIRONMENT: ${{ inputs.environment }}
If you run this workflow from a browser you must enter values for the required inputs manually before the workflow will run.
You might like the following documentation links
workflow_dispatch
github docs - events-that-trigger-workflows

github actions | get origin branch on push

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 }}'"

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.

GitHub action runs twice on merge

I have a build and deploy GitHub action that runs when I update my GitHub pages repository. In addition I have one that updates the recipes using I store.
Most of the time it runs fine but occasionally I update from my phone (with Working Copy) and do a merge, then each action runs twice, all of them triggered by the same push. The recipe update action succeeds both times.
Yet when that happens one of the build and deploy actions fails with something like “! [remote rejected] master -> gh-pages (cannot lock ref 'refs/heads/gh-pages': is at 37c581108d857f9d9c8fe584103d78e4473d280b but expected ceaf2249cc2f7864f0269e64d372fc40ce0b06e0)”
It doesn’t break anything but I’m not sure why it happens and I’d like to fix it.
Build and deploy
on:
push:
branches:
- main
schedule:
- cron: '0 */2 * * *'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout#v2
with:
persist-credentials: false
- name: Setup Python Environment
uses: actions/setup-python#v2
with:
python-version: 3.8
- name: Install Requirements
run: pip install -r requirements.txt
- name: Execute Python script
run: |
python3 -m papexp
env:
EMAIL: ${{ secrets.EMAIL }}
PASSWORD: ${{ secrets.PASSWORD }}
- name: setup git config
run: |
git config --local user.name ${{ secrets.USERNAME_GITHUB }}
git config --local user.email ${{ secrets.EMAIL }}
git pull --ff-only origin main
git add images/recipes/*
git add .
git commit -am "Update recipes" || echo "Nothing to update"
- name: Push changes
uses: ad-m/github-push-action#master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
I don't think the action is running twice because of a single push, and I don't think it's related to whether you update from your mobile or not.
Your action runs when you push to main, but it also runs every 2 hours. So sometimes you're going to get conflicts, when the action triggered by a push runs at the same time as a scheduled action.
If you need the action to run in both situations (triggered and scheduled), and if the occasional collisions aren't causing you problems, I'd just put up with it TBH. Trying to implement some kind of locking mechanism to avoid collisions is probably more effort than it's worth.