Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/script-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}

skip-ci:
name: Skip CI Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4

- run: Invoke-Pester -CI
working-directory: skip-ci
shell: pwsh
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

danger:
name: Danger JS Tests
runs-on: ubuntu-latest
Expand Down
23 changes: 23 additions & 0 deletions .github/workflows/workflow-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,29 @@ jobs:

Write-Host "✅ No-changes scenario validation passed!"

# A push is never a pull request update, so the action must tell the jobs to run.
skip-ci-push:
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4

- name: Run skip-ci action
id: skip-ci
uses: ./skip-ci

- name: Validate output
shell: pwsh
env:
SKIP: ${{ steps.skip-ci.outputs.skip }}
run: |
if ($env:SKIP -ne 'false') {
Write-Error "Expected skip=false on push, got '$env:SKIP'"
exit 1
}

cli-integration:
runs-on: ${{ matrix.host }}-latest
strategy:
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Features

- Skip CI - Add an action that tells whether a push to a pull request only changes files that need no CI, such as Markdown, since a head whose run passed. Jobs gated on its `skip` output don't run for a CHANGELOG fix-up. ([#187](https://github.com/getsentry/github-workflows/pull/187))

## 3.5.0

### Features
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ Validates non-maintainer PRs against contribution guidelines and enforces draft

**[📖 View full documentation →](validate-pr/README.md)**

### Skip CI

Tells whether a push to a pull request only changes files that need no CI, such as Markdown, so expensive jobs can be skipped.

**[📖 View full documentation →](skip-ci/README.md)**

## Legacy Reusable Workflows (v2)

> ⚠️ **Deprecated**: Reusable workflows have been converted to composite actions in v3. Please migrate to the composite actions above.
Expand Down
83 changes: 83 additions & 0 deletions skip-ci/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Skip CI

Tells whether a push to a pull request only changes files that need no CI, such as Markdown, since a head whose CI passed. Jobs gated on its `skip` output then don't run for a CHANGELOG fix-up or a docs edit, while everything else runs as usual.

A workflow's `paths-ignore` can't do this: GitHub matches it against the whole pull request, so a pull request that changes code runs the full workflow on every later push, even one that only touches `CHANGELOG.md`.

## Usage

Add a job that runs the action, and gate the expensive jobs on its output:

```yaml
jobs:
changes:
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
outputs:
skip: ${{ steps.skip-ci.outputs.skip }}
steps:
- id: skip-ci
uses: getsentry/github-workflows/skip-ci@<sha>
with:
paths: |
**/*.md
!package/**

build:
needs: [changes]
if: ${{ needs.changes.outputs.skip != 'true' }}
runs-on: ubuntu-latest
steps:
- run: echo "build and test"
```

Pin to a specific commit SHA. Jobs that depend on a skipped job through `needs` skip with it, so gating the jobs everything else starts from is enough. Every job that waits on another one's artifacts must be gated too, or it waits for artifacts that never come.

The job needs `actions: read` to find earlier runs and `contents: read` to compare commits. Without them the API calls fail, the action logs a warning, and CI runs. The action runs `gh` and `pwsh`, which GitHub-hosted runners have. On a runner without `gh`, it logs a warning and gives `false`, so CI runs; on a runner without `pwsh`, the step fails, and the jobs that need it don't run.

## Inputs

| Input | Required | Description |
|-------|----------|-------------|
| `paths` | No | Patterns, one per line, of files whose changes alone need no CI. Default: `**/*.md`. |
| `api-token` | No | Token for the repo. Default: `${{ github.token }}`. |

## Outputs

| Output | Description |
|--------|-------------|
| `skip` | `true` when the jobs gated on this check can be skipped, `false` otherwise. |

## When it skips

`skip` is `true` only when all of these hold:

- The workflow runs for a `pull_request` event with the `synchronize` action, i.e. a push to an open pull request. Any other event, including `push`, `workflow_dispatch`, `merge_group` and `pull_request_target`, gives `false`.
- The same workflow has a successful run for the previous head, on the same branch of the same repository, that lists this pull request. A run lists every open pull request with that head, so when two pull requests share a branch, such as one into `main` and one into a release branch, a run that passed for one counts for the other. Runs for pull requests from forks list none, so for those the branch and fork must match. A run that skipped its jobs through this action counts, because it was itself checked against a head that passed.
- The new head is strictly ahead of the previous head. A force-push that dropped or rewrote commits gives `false`.
- Between 1 and 299 files changed between the two heads (the compare API lists at most 300), and every changed file matches `paths`. For a renamed file, both its new and its old name must match.

A successful run is all the action checks: it doesn't know whether the gated jobs ran in it. If those jobs have conditions of their own, such as skipping drafts, a run where they didn't run still lets the next push skip.

A skipped run also doesn't test the pull request against a base branch that moved since the passing run. Require branches to be up to date before merging, or use a merge queue, if that matters.

When any API call fails, the action logs a warning and gives `false`. It never fails the job.

When it skips, the action writes the reason to the job summary.

## Patterns

- `**` matches any characters, including `/`. A leading `**/` also matches files at the root, so `**/*.md` matches `CHANGELOG.md` and `docs/setup.md`.
- `*` matches any characters except `/`, so `*.md` matches only Markdown files at the root.
- `?` matches one character except `/`.
- A pattern starting with `!` takes matching files back out. The last pattern that matches a file decides, so `!package/**` after `**/*.md` keeps Markdown files under `package/` needing CI.
- A leading `/` is ignored, so `!/package/**` and `!package/**` are the same.
- Blank lines and lines starting with `#` are ignored. Matching is case-sensitive.

These are not GitHub's `paths` filter patterns: `?`, `+` and `[...]` mean something else there.

## Required status checks

A job skipped by its `if:` reports one check under its unexpanded name, such as `Build ${{ matrix.target }}`, instead of one per matrix entry. A required check that names a matrix entry then never reports, and the pull request can't be merged. If you require checks, require one job that always runs and checks the results of the others, not the gated jobs themselves.
38 changes: 38 additions & 0 deletions skip-ci/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: 'Skip CI'
description: 'Tells whether a push to a pull request only changes files that need no CI, such as Markdown, since a head that passed'
author: 'Sentry'

inputs:
paths:
description: 'Patterns, one per line, of files whose changes alone need no CI. A pattern starting with ! takes files back out; the last matching pattern wins.'
required: false
default: '**/*.md'
api-token:
description: 'Token for the repo. Needs `actions: read` and `contents: read`.'
required: false
default: ${{ github.token }}

outputs:
skip:
description: "'true' when the jobs that depend on this check can be skipped; 'false' otherwise."
value: ${{ steps.check.outputs.skip }}

runs:
using: 'composite'
steps:
- name: Check changes
id: check
shell: pwsh
env:
GH_TOKEN: ${{ inputs.api-token }}
PATHS: ${{ inputs.paths }}
EVENT_NAME: ${{ github.event_name }}
EVENT_ACTION: ${{ github.event.action }}
BEFORE: ${{ github.event.before }}
HEAD: ${{ github.event.pull_request.head.sha }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
PR_NUMBER: ${{ github.event.pull_request.number }}
HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
REPOSITORY: ${{ github.repository }}
WORKFLOW_REF: ${{ github.workflow_ref }}
run: ${{ github.action_path }}/scripts/skip-ci.ps1
84 changes: 84 additions & 0 deletions skip-ci/scripts/match-paths.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Returns $true when every file matches the patterns.
# A pattern starting with '!' takes matching files back out; the last pattern that matches a file decides.
# '**' matches any characters including '/', and a leading '**/' also matches files at the root;
# '*' matches any characters except '/'; '?' matches one character except '/'. Matching is case-sensitive.
# A leading '/' is ignored, since file names are relative to the repository root.
param(
[Parameter(Mandatory = $true)][AllowEmptyCollection()][string[]] $Files,
[Parameter(Mandatory = $true)][AllowEmptyCollection()][AllowEmptyString()][string[]] $Patterns
)

Set-StrictMode -Version latest

function ConvertTo-Regex([string] $glob)
{
$regex = ''
$i = 0
while ($i -lt $glob.Length)
{
if ($glob.Substring($i).StartsWith('**/'))
{
$regex += '(?:.*/)?'
$i += 3
}
elseif ($glob.Substring($i).StartsWith('**'))
{
$regex += '.*'
$i += 2
}
elseif ($glob[$i] -eq '*')
{
$regex += '[^/]*'
$i++
}
elseif ($glob[$i] -eq '?')
{
$regex += '[^/]'
$i++
}
else
{
$regex += [regex]::Escape([string]$glob[$i])
$i++
}
}
"^$regex$"
}

$rules = @(foreach ($pattern in $Patterns)
{
$pattern = $pattern.Trim()
if ($pattern -eq '' -or $pattern.StartsWith('#'))
{
continue
}
$exclude = $pattern.StartsWith('!')
if ($exclude)
{
$pattern = $pattern.Substring(1)
}
$pattern = $pattern.TrimStart('/')
[pscustomobject]@{ Regex = ConvertTo-Regex $pattern; Exclude = $exclude }
Comment thread
bitsandfoxes marked this conversation as resolved.
Resolved
})

if ($Files.Count -eq 0 -or $rules.Count -eq 0)
{
return $false
}

foreach ($file in $Files)
{
$matched = $false
foreach ($rule in $rules)
{
if ($file -cmatch $rule.Regex)
{
$matched = -not $rule.Exclude
}
}
if (-not $matched)
{
return $false
}
}
return $true
96 changes: 96 additions & 0 deletions skip-ci/scripts/skip-ci.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Decides whether a push to a pull request only changes files that don't need CI.
# Writes `skip=true` to GITHUB_OUTPUT only when all of these hold:
# - the event is `pull_request` with action `synchronize`;
# - the same workflow has a successful run for the previous head that lists this pull request;
# - the new head is strictly ahead of the previous head (no force-push dropped commits);
# - between 1 and 299 files changed, and every file (and the old name of a renamed file) matches `PATHS`.
# Any error leaves `skip=false`, so CI runs. The script always exits 0.

Set-StrictMode -Version latest
$ErrorActionPreference = 'Stop'

function Invoke-GhApi([string] $path)
{
$json = gh api $path
if ($LASTEXITCODE -ne 0)
{
throw "gh api $path failed with exit code $LASTEXITCODE"
}
$json | ConvertFrom-Json
}

function Get-SkipReason
{
if ($env:EVENT_NAME -ne 'pull_request' -or $env:EVENT_ACTION -ne 'synchronize' -or -not $env:BEFORE)
{
Write-Host 'Not a push to an open pull request; CI runs.'
return $null
}

# WORKFLOW_REF looks like 'owner/repo/.github/workflows/ci.yml@refs/pull/1/merge'.
# The runs API takes the file name; the full path returns 404.
$workflow = Split-Path -Leaf ($env:WORKFLOW_REF -replace '@.*$', '')

$runs = Invoke-GhApi "repos/$env:REPOSITORY/actions/workflows/$workflow/runs?head_sha=$env:BEFORE&event=pull_request&status=success"
# A run lists every open pull request with its head, not only the one it ran for; runs for forks list none.
$passed = @($runs.workflow_runs | Where-Object {
$_.head_branch -eq $env:HEAD_REF -and $_.head_repository.full_name -eq $env:HEAD_REPOSITORY -and
(@($_.pull_requests).Count -eq 0 -or @($_.pull_requests | Where-Object { "$($_.number)" -eq $env:PR_NUMBER }).Count -gt 0)
})
if ($passed.Count -eq 0)
{
Write-Host "$workflow has no successful run for the previous head $env:BEFORE; CI runs."
return $null
}

# The compare API lists at most 300 files.
$compare = Invoke-GhApi "repos/$env:REPOSITORY/compare/$env:BEFORE...$env:HEAD"
$files = @($compare.files)
if ($compare.status -ne 'ahead' -or $files.Count -eq 0 -or $files.Count -ge 300)
{
Write-Host "Comparing $env:BEFORE...$env:HEAD gives status '$($compare.status)' with $($files.Count) files; CI runs."
return $null
}

$names = @(foreach ($file in $files)
{
$file.filename
if ($file.PSObject.Properties['previous_filename'])
{
$file.previous_filename
}
})
$patterns = @($env:PATHS -split "`n")
if (-not (& "$PSScriptRoot/match-paths.ps1" -Files $names -Patterns $patterns))
{
Write-Host "Some files changed since $env:BEFORE don't match ``paths``; CI runs."
return $null
}

"Only files matching ``paths`` changed since $env:BEFORE, which passed $workflow."
}

$skip = $false
try
{
$reason = Get-SkipReason
if ($reason)
{
$skip = $true
Write-Host $reason
if ($env:GITHUB_STEP_SUMMARY)
{
"$reason Skipping the jobs that depend on it." | Out-File $env:GITHUB_STEP_SUMMARY -Append
}
}
}
catch
{
Write-Host "::warning::Couldn't check the changes, so CI runs: $_"
}

if ($env:GITHUB_OUTPUT)
{
"skip=$($skip.ToString().ToLower())" | Out-File $env:GITHUB_OUTPUT -Append
}
exit 0
Loading
Loading