Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial implementation #1

Merged
merged 14 commits into from
Sep 17, 2024
186 changes: 186 additions & 0 deletions .github/workflows/integration-tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
---
name: Integration Tests
on:
pull_request:
paths:
- "action.yaml"
- ".github/workflows/integration-tests.yaml"

jobs:
test-default-name:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: ${{ github.job }}
- name: Test job ID
run: |
[[ "${job_id}" =~ ^[0-9]+$ ]] || exit 1
env:
job_id: ${{ steps.job.outputs.id }}

test-custom-name:
name: Custom Name
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: Custom Name
- name: Test job ID
run: |
[[ "${job_id}" =~ ^[0-9]+$ ]] || exit 1
env:
job_id: ${{ steps.job.outputs.id }}
omus marked this conversation as resolved.
Show resolved Hide resolved

test-empty-name:
name: ""
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: test-empty-name
omus marked this conversation as resolved.
Show resolved Hide resolved

test-null-name:
name: null
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: ${{ github.job }}

test-false-name:
name: false
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: false

test-matrix:
name: Matrix
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
strategy:
fail-fast: false
matrix:
build:
- name: App One
repo: user/app1
- name: App Two
repo: user/app2
version:
- "1.0"
- "2.0"
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: Matrix (${{ matrix.build.name }}, ${{ matrix.build.repo }}, ${{ matrix.version }})
- name: Test job name is distinct
run: |
jobs="$(gh api -X GET "/repos/{owner}/{repo}/actions/runs/${run_id:?}/attempts/${run_attempt:?}/jobs")"
if [[ $(jq --arg name "$job_name" '.jobs | map(select(.name == $name)) | length' <<<"${jobs}") -ne 1 ]]; then
jq '.jobs[].name' <<<"${jobs}"
exit 1
fi
env:
GH_TOKEN: ${{ github.token }}
run_id: ${{ github.run_id }}
run_attempt: ${{ github.run_attempt }}
job_name: ${{ steps.job.outputs.name }}

test-matrix-expr:
name: Matrix Expression - ${{ github.event_name }} - ${{ matrix.dne }} - ${{ matrix.index }} - ${{ strategy.job-index }}
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
strategy:
fail-fast: false
matrix:
index:
- 1
- 2
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
- name: Test job name
run: '[[ "${output}" == "${expected}" ]] || exit 1'
env:
output: ${{ steps.job.outputs.name }}
expected: Matrix Expression - ${{ github.event_name }} - - ${{ matrix.index }} - ${{ strategy.job-index }}
- name: Test job name is distinct
run: |
jobs="$(gh api -X GET "/repos/{owner}/{repo}/actions/runs/${run_id:?}/attempts/${run_attempt:?}/jobs")"
if [[ $(jq --arg name "$job_name" '.jobs | map(select(.name == $name)) | length' <<<"${jobs}") -ne 1 ]]; then
jq '.jobs[].name' <<<"${jobs}"
exit 1
fi
env:
GH_TOKEN: ${{ github.token }}
run_id: ${{ github.run_id }}
run_attempt: ${{ github.run_attempt }}
job_name: ${{ steps.job.outputs.name }}

test-ambiguous:
# Using `github.job` with any other expressions present results in it being empty
name: ${{ github.job }}
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
fail-fast: false
matrix:
index:
- 1
- 2
steps:
- uses: actions/checkout@v4
- uses: ./
id: job
continue-on-error: true
- name: Action failed
if: ${{ steps.job.outcome != 'failure' }}
run: exit 1
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Beacon Biosignals

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
60 changes: 58 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,58 @@
# job-context
Provides additional context for the currently running job
# Job Context

Provides additional context for the currently running job. GitHub Actions provides a [`job` context](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/accessing-contextual-information-about-workflow-runs#job-context) but is missing some pieces including the job name and the job ID (the numeric value as used by the GitHub API).

## Requirements

The `job-context` action requires that the job in which this action is used has a job name that is unique within the workflow file. By default job names are unique so this is only a problem if you specify a custom `jobs.<job_key>.name`. If the job name is not unique within the workflow this action will fail and report the ambiguous job name.

Additionally, this job currently does not support job names which utilize GHA expressions using the contexts: `needs`, `vars`, or `inputs`.

## Examples

```yaml
# CI.yaml
jobs:
demo:
name: Demo
# These permissions are needed to:
# - Use `job-context`: https://github.com/beacon-biosignals/job-context#permissions
permissions:
context: read
runs-on: ubuntu-latest
strategy:
matrix:
version:
- "1.0"
- "2.0"
steps:
- uses: beacon-biosignals/job-context@v1
id: job
- run: |
echo "job-name=${{ steps.job.outputs.name }} # e.g. Demo (1.0)
echo "job-id=${{ steps.job.outputs.id }} # e.g. 28842064821
```

## Inputs

The `job-context` action supports the following inputs:

| Name | Description | Required | Example |
|:-----------------|:------------|:---------|:--------|
| `path` | The path to the cloned repo containing the workflow. Should only be needed by other GHAs using this action. | No | <pre><code>${{ github.action_path }}/repo</code></pre> |

## Outputs

| Name | Description | Example |
|:-------|:------------|:--------|
| `name` | The rendered job name. | <pre><code>Demo (1.0)</code></pre> |
| `id` | The numeric job ID as used by the GitHub API. Not be be confused with the workflow job key `github.job`. | <pre><code>28842064821</code></pre> |

## Permissions

The follow [job permissions](https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs) are required to run this action:

```yaml
permissions:
context: read
```
107 changes: 107 additions & 0 deletions action.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
---
name: Job Context
description:
inputs:
path:
description: >-
The path to the cloned repo containing the workflow. Should only be needed by other
GHAs using this action.
type: string
default: ""
required: false
outputs:
name:
description: The rendered job name.
value: ${{ steps.render.outputs.name }}
id:
description: >-
The numeric job ID as used by the GitHub API. Not be be confused with the workflow
job key `github.job`.
value: ${{ steps.job-api.outputs.id }}
runs:
using: composite
steps:
# In order to determine the job name we'll extract the non-rendered job name from the
# workflow and then evaulate any expressions contained within.
- uses: actions/checkout@v4
with:
ref: ${{ github.workflow_sha }}
path: ${{ inputs.path || format('{0}/repo', github.action_path) }}
- id: workflow
shell: bash
run: |
# Workflow job name template
[[ "$RUNNER_DEBUG" -eq 1 ]] && set -x
set -euo pipefail

# e.g. octocat/hello-world/.github/workflows/my-workflow.yml@refs/heads/my_branch -> .github/workflows/my-workflow.yml
workflow_path="$(echo "${workflow_ref%@*}" | cut -d/ -f3-)"
job_name_template="$(job_key="${job_key}" yq '.jobs[env(job_key)] | select(has("name")).name | select(. != null)' "${repo_path}/${workflow_path:?}")"
echo "name-template=${job_name_template}" | tee -a "$GITHUB_OUTPUT"
env:
repo_path: ${{ inputs.path || format('{0}/repo', github.action_path) }}
workflow_ref: ${{ github.workflow_ref }}
job_key: ${{ github.job }} # User supplied job key cannot be allowed as we cannot properly render `matrix` expressions later
- id: render
shell: bash
run: |
# Render job name
[[ "$RUNNER_DEBUG" -eq 1 ]] && set -x
set -euo pipefail

# Determine if job name contains GitHub expressions. As GitHub expressions must be
# closed we can just check for the opening sequence.
if grep -qE '\$\{\{' <<<"${job_name_template}"; then
# Convert GHA expressions into jq Bash expressions. Converts `null` results into `""` to match GHA behavior.
# e.g. `{{ matrix.demo.version }}` -> `$(jq -r '.demo.version | select(type != "null")' <<<"${matrix_json:?}")`
job_name_expr="$(perl -pe 's/\$\{\{\s*([a-z]+)\.([a-z0-9._-]+)\s*}}/\$(jq -r --arg p "\2" '\''getpath(\$p | split(".")) | select(type != "null")'\'' <<<"\${\1_json:?}")/g' <<<"${job_name_template}")"
job_name="$(eval "echo \"${job_name_expr}\"")"
else
job_name="${job_name_template}"
if [ -z "${job_name}" ]; then
job_name="${job_key:?}"
fi

# GitHub adds job matrix values to job names which do not contain expressions.
matrix_values="$(jq -r '[.. | select(type != "object")] | join(", ")' <<<"${matrix_json}")"
if [[ -n "${matrix_values}" ]]; then
job_name="${job_name:?} (${matrix_values})"
fi
fi
echo "name=${job_name:?}" | tee -a "$GITHUB_OUTPUT"
env:
job_name_template: ${{ steps.workflow.outputs.name-template }}
job_key: ${{ github.job }}

# `jobs.<job_id>.name` can use the contexts: [github, needs, strategy, matrix, vars, inputs]. No functions are allowed.
# https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/contexts#context-availability
github_json: ${{ toJSON(github) }}
# needs_json: ${{ toJSON(needs) }}
strategy_json: ${{ toJSON(strategy) }}
matrix_json: ${{ toJSON(matrix) }}
# vars_json: ${{ toJSON(vars) }}
# inputs_json: ${{ toJSON(inputs) }}

# With the rendered job name we can use the GitHub API to fetch the job ID from the API
# as long as the job name is distinct within the workflow.
- id: job-api
shell: bash
run: |
# Fetch job ID
[[ "$RUNNER_DEBUG" -eq 1 ]] && set -x
set -euo pipefail

jobs="$(gh api -X GET "/repos/{owner}/{repo}/actions/runs/${run_id:?}/attempts/${run_attempt:?}/jobs")"
job_ids="$(jq -c --arg name "$job_name" '[.jobs[] | select(.name == $name) | .id]' <<<"${jobs}")"

if [[ $(jq length <<<"${job_ids}") -eq 1 ]]; then
echo "id=$(jq 'first' <<<"${job_ids}")" | tee -a "$GITHUB_OUTPUT"
else
echo "ERROR: Unable to determine job ID. The job name \"${job_name:?}\" is not unique within the workflow." >&2
exit 1
fi
env:
GH_TOKEN: ${{ github.token }}
run_id: ${{ github.run_id }}
run_attempt: ${{ github.run_attempt }}
job_name: ${{ steps.render.outputs.name }}
Loading