I'm attempting to create an Action that automatically adds a merged PR to a project so the PR can be reviewed for documentation needs. The key here is that the PR should be added to the project after it's been merged into main. From what I can tell, Github Actions don't work directly with merged PRs for the pull_request webhook.
Has anybody managed to do this or have any tips? My initial thought is to do something like:
name: Add-Merged-PRs
# Run this workflow every time a PR is merged into the main branch
on: push
branches:
- main
jobs:
# Take the PR that was merged and add it to a specified project.
You can use the pull_request event and narrow it down to "has been closed" and "was merged" using the types and branches properties of pull_request, then check in the github.event.pull_request context that the merged property is true.
All together, for a project named "Test" and a column "Merged PRs", using the GitHub CLI to make API calls, a workflow might look like this:
name: Add merged PRs to project
# When a PR into main is closed or merged
on:
pull_request:
types:
- closed
branches:
- main
jobs:
addpr:
name: Add PR to project
# PR must must be merged, not closed
if: github.event.pull_request.merged
runs-on: ubuntu-20.04
steps:
- name: Add PR to project board
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
projectid=$(gh api "repos/${{ github.repository }}/projects" \
-H "Accept: application/vnd.github.inertia-preview+json" \
| jq '.[] | select(.name == "Test").id')
columnid=$(gh api "projects/$projectid/columns" \
-H "Accept: application/vnd.github.inertia-preview+json" \
| jq '.[] | select(.name == "Merged PRs").id')
gh api "projects/columns/$columnid/cards" \
-H "Accept: application/vnd.github.inertia-preview+json" \
-F "content_type=PullRequest" \
-F "content_id=${{ github.event.pull_request.id }}"
For reference and to see how "closed with unmerged commits" and "properly merged" are told apart, see the docs for the pull_request payload object.
Related
I am trying to trigger a workflow every time a commit is pushed to the repo. This little workflow adds a label to a jira ticket every time a commit is pushed. Whenever i would commit this workflow file and add a commit message, it would trigger the workflow but when i try it with other files in the repo it does absolutely nothing and I don't have a clue why. When i would also make changes to other workflow files it would also trigger this specific workflow.
I'm new to github actions so any help would be appreciated. Below is my full workflow. I have also tried with just "on: push:".
name: Update Jira with branch name
on:
push:
branches:
- '*'
jobs:
update_jira:
runs-on: ubuntu-latest
steps:
- name: Get branch name
run: echo "Branch name:${GITHUB_REF#refs/heads/}"
- name: Login
uses: atlassian/gajira-login#master
env:
JIRA_BASE_URL: x
JIRA_USER_EMAIL: y
JIRA_API_TOKEN: z
- name: Find in commit messages
uses: atlassian/gajira-find-issue-key#v3
with:
from: commits
- name: Update Jira with branch name
run: |
JIRA_URL=x
JIRA_USERNAME=y
JIRA_TOKEN=z
curl -X PUT -H "Authorization: Basic $(echo -n "$JIRA_USERNAME:$JIRA_TOKEN" | base64)" -H "Content-Type: application/json" -d "{\"fields\":{\"labels\":[\"${GITHUB_REF#refs/heads/}\"]}}" "$JIRA_URL/rest/api/latest/issue/$(cat /home/runner/jira/config.yml | grep "issue:" | awk '{print $2}')"
# Get the response code
response_code=$(curl -X PUT -H "Authorization: Basic $(echo -n "$JIRA_USERNAME:$JIRA_TOKEN" | base64)" -H "Content-Type: application/json" -d "{\"fields\":{\"labels\":[\"${GITHUB_REF#refs/heads/}\"]}}" "$JIRA_URL/rest/api/latest/issue/$(cat /home/runner/jira/config.yml | grep "issue:" | awk '{print $2}')" -s -o /dev/null -w "%{http_code}")
# Print the response code
echo "Response code: $response_code"
The workflow only runs with this 'on: push' setup if the workflow is stored on that branch. Check if the workflow exists on those other branches as well, and add it if missing.
So, I'm working with Github Actions on end-to-end testing. The setup I'm looking at is having one job retrieve a list of urls to be tested, and my second job creates a matrix with that list and tests them all. My problem here is that when I actually run my testing script, it has to be done from the command line, because I'm using Playwright. Therefore I can't use my matrix object directly; I have to output it to a JSON file. The problem is that toJSON creates invalid pretty-printed JSON when I output it to my file, which breaks my script. Here's my code:
name: <name>
on:
push:
workflow_dispatch:
jobs:
fetch_strategic_urls:
runs-on: ubuntu-latest
outputs:
urls: ${{ steps.req-urls.outputs.urls }}
steps:
- name: Request Urls
id: req-urls
run: |
export RESPONSE=$(
curl -X GET -H "Accept: application/json" <api-endpoint>)
echo "::set-output name=urls::$RESPONSE"
run_tests:
runs-on: ubuntu-latest
strategy:
matrix:
url: ${{needs.fetch_strategic_urls.outputs.urls}}
needs: fetch_strategic_urls
steps:
- ...
- ...
- run: |
ls
echo '${{ toJSON(matrix.url) }}' >> props.json
cat props.json
npm test
working-directory: E2E.Tests
No matter which configuration of echo ${{matrix.url}} >> props.json I've tried (cat <<'EOF' > props.json ${{matrix.url}}, adding and removing quotes), it always produced JSON files that have no quotes, i.e.: { url: string } instead of {"url": "string"}, which is invalid. This is obviously pretty breaking behavior. I've seen a lot of people online recommending jq, but I don't see how I would use it in this case, since I doubt jq can parse a GitHub-type JSON object, which is necessary for me to use when sharding my jobs. Any help is greatly appreciated!
It's not easy to put a JSON doc directly in the command line. You can use env vars.
- shell: bash
env:
JSON_DOC: ${{ toJSON(some.var) }}
run: |
printf '%s\n' "$JSON_DOC" > foo.json
cat foo.json
...
Github actions documenation has a solution here:
name: Context testing
on: push
jobs:
dump_contexts_to_log:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
id: github_context_step
run: echo '${{ toJSON(github) }}'
From https://docs.github.com/en/actions/learn-github-actions/contexts#example-printing-context-information-to-the-log
I'm trying to trigger a workflow event in Github.
for some reason, I'm able to GET information about my organization repository workflow but can not use '/dispatches'
Work is based on: https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event
Here is the curl code:
curl -X POST \
-H "Accept:application/vnd.github.v3+json" \
-H 'Authorization:token ${{ github.token }}' \
'https://api.github.com/repos/[owner/org]/[repo]/actions/workflows/9999999/dispatches' \
-d '{"event_type":"semantic-release"}'
Getting error:
422 Unprocessable Entity
"message": "Invalid request.\n\nFor 'links/0/schema', nil is not an object.",
"documentation_url": "https://docs.github.com/rest/reference/repos#create-a-repository-dispatch-event"
Am I missing some basic information for this to work and trigger an event?
Instead of trying to call the GitHub API directly, try and use the GitHub CLI gh (that you can install first to test locally).
You can also use GitHub CLI in workflows.
GitHub CLI is preinstalled on all GitHub-hosted runners.
For each step that uses GitHub CLI, you must set an environment variable called GITHUB_TOKEN to a token with the required scopes
It has a gh workflow run, which does create a workflow_dispatch event for a given workflow.
Authenticates first (gh auth login, if you are doing a local test):
# authenticate against github.com by reading the token from a file
$ gh auth login --with-token < mytoken.txt
Examples:
# Run the workflow file 'triage.yml' at the remote's default branch
$ gh workflow run triage.yml
# Run the workflow file 'triage.yml' at a specified ref
$ gh workflow run triage.yml --ref my-branch
# Run the workflow file 'triage.yml' with command line inputs
$ gh workflow run triage.yml -f name=scully -f greeting=hello
# Run the workflow file 'triage.yml' with JSON via standard input
$ echo '{"name":"scully", "greeting":"hello"}' | gh workflow run triage.yml --json
In your case (GitHub Action):
jobs:
push:
runs-on: ubuntu-latest
steps:
- run: gh workflow run triage.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
As explained by hanayama in the comments:
Found out the secrets. GITHUB_TOKEN doesn't work, even with permissions edited for the entire workflow.
Using a personal access token worked.
I'm trying to find out if it's possible to add a deploy key with GitHub actions. I have already generates key with ssh-keygen and tried to add it manually which works. But I would like to add my generated key with GitHub actions as well.
In other words I want to do this "GitHub -> repo -> settings -> deploy keys -> add deploy key (the generated key during workflow)" but I want to do it with GitHub actions if it's possible.
This is the workflow that i have created so far:
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ main ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
if: github.event.repository.name != 'testar-deploy-key'
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout#v2
- name: Create deploy key
run: |
# Deploy key
ssh-keygen -m PEM -t rsa -b 4096 -C "mail#mail.com" -o -f id_rsa
#Here i want in someway to add my generated key to the current github repository.
git config --local user.email "action#github.com"
git config --local user.name "GitHub Action"
git add .
git commit -m "Generate SSH"
# Push changes
- name: Push changes
uses: ad-m/github-push-action#master
with:
branch: main
github_token: ${{ secrets.GITHUB_TOKEN }}
My objective is to get to the point where I can type /run-black as a comment on a pull request in GitHub, and then GitHubActions will run black . on the pull request's branch and add a commit.
The use case is that sometimes casual contributors make a small pull request to my library (e.g. fixing a typo), and I'd like to be able to just write a comment like /run-black to have the black formatter run on their files before I merge.
Use the action Slash Command Dispatch. Add a repo scoped PAT with the name PAT to your secrets and create two workflows with the following definitions.
name: Slash Command Dispatch
on:
issue_comment:
types: [created]
jobs:
slashCommandDispatch:
runs-on: ubuntu-latest
steps:
- name: Slash Command Dispatch
uses: peter-evans/slash-command-dispatch#v2
with:
token: ${{ secrets.PAT }}
issue-type: pull-request
commands: |
run-black
on:
repository_dispatch:
types: [run-black-command]
jobs:
runBlack:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
repository: ${{github.event.client_payload.pull_request.head.repo.full_name}}
ref: ${{github.event.client_payload.pull_request.head.ref}}
token: ${{ secrets.PAT }}
- name: Slash Command Dispatch
run: black .
- run: |
git config --local user.email "41898282+github-actions[bot]#users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "Run black" -a
git push