id: github-stale-required-checks-repair
namespace: company.engineering
variables:
repository: my-org/my-repo
branch: main
api: "https://api.github.com/repos/{{ vars.repository }}"
tasks:
- id: run
type: io.kestra.plugin.core.output.OutputValues
description: The completed pull request run GitHub sent to the webhook.
values:
sha: "{{ trigger.body.workflow_run.head_sha }}"
url: "{{ trigger.body.workflow_run.html_url }}"
- id: pulls
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/commits/{{ outputs.run['values'].sha }}/pulls"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: protection
type: io.kestra.plugin.core.http.Request
description: Required checks set in classic branch protection. A 404 means the
branch has none.
uri: "{{ render(vars.api) }}/branches/{{ vars.branch
}}/protection/required_status_checks"
options:
allowedResponseCodes: [ 200, 404 ]
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: rulesets
type: io.kestra.plugin.core.http.Request
description: Rules from every active ruleset that applies to the branch.
uri: "{{ render(vars.api) }}/rules/branches/{{ vars.branch }}"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: check_runs
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/commits/{{ outputs.run['values'].sha
}}/check-runs?per_page=100"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: statuses
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/commits/{{ outputs.run['values'].sha }}/status"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: facts
type: io.kestra.plugin.core.output.OutputValues
values:
pr: "{{ fromJson(outputs.pulls.body) | jq('[.[] | select(.state == \"open\" and
.base.ref == \"' ~ vars.branch ~ '\")][0].number // 0') | first }}"
required: >-
{{ {'protection': outputs.protection.code == 200 ?
fromJson(outputs.protection.body).checks : [], 'rules':
fromJson(outputs.rulesets.body)} | jq('[.protection[] | {context,
source: "branch protection"}] + [.rules[] | select(.type ==
"required_status_checks") | .ruleset_id as $id |
.parameters.required_status_checks[] | {context, source: "ruleset",
ruleset_id: $id}]') | first | toJson }}
reported: >-
{{ {'runs': fromJson(outputs.check_runs.body).check_runs, 'statuses':
fromJson(outputs.statuses.body).statuses} | jq('[.runs[].name] +
[.statuses[].context] | unique') | first | toJson }}
running: >-
{{ {'runs': fromJson(outputs.check_runs.body).check_runs, 'statuses':
fromJson(outputs.statuses.body).statuses} | jq('[.runs[] |
select(.status != "completed")] + [.statuses[] | select(.state ==
"pending")] | length') | first }}
apps: "{{ fromJson(outputs.check_runs.body).check_runs | jq('map({key: .name,
value: .app.id}) | from_entries') | first | toJson }}"
- id: diff
type: io.kestra.plugin.core.output.OutputValues
values:
stale: >-
{{ {'required': fromJson(outputs.facts['values'].required), 'reported':
fromJson(outputs.facts['values'].reported)} | jq('. as $f |
[$f.required[] | select(.context as $c | $f.reported | index($c) |
not)]') | first | toJson }}
stale_names: >-
{{ {'required': fromJson(outputs.facts['values'].required), 'reported':
fromJson(outputs.facts['values'].reported)} | jq('. as $f |
[$f.required[] | select(.context as $c | $f.reported | index($c) | not)
| .context] | unique | join(", ")') | first }}
stale_summary: >-
{{ {'required': fromJson(outputs.facts['values'].required), 'reported':
fromJson(outputs.facts['values'].reported)} | jq('. as $f |
[$f.required[] | select(.context as $c | $f.reported | index($c) | not)]
| group_by(.context) | map("`" + .[0].context + "` (required by " +
(map(if .source == "ruleset" then "a ruleset" else .source end) | unique
| sort_by(. == "a ruleset") | join(" and ")) + ")") | join(", ")') |
first }}
candidates: >-
{{ {'required': fromJson(outputs.facts['values'].required), 'reported':
fromJson(outputs.facts['values'].reported)} | jq('. as $f |
[$f.reported[] | select(. as $n | [$f.required[].context] | index($n) |
not)]') | first | toJson }}
- id: proposal
type: io.kestra.plugin.core.kv.Get
description: The stale checks this flow already asked about, so it asks only once.
key: "stale_required_checks_{{ vars.branch | slugify }}"
- id: route
type: io.kestra.plugin.core.flow.Switch
value: >-
{%- if outputs.facts['values'].pr == '0' -%}NOT_A_PULL_REQUEST {%- elseif
outputs.facts['values'].running != '0' -%}CHECKS_STILL_RUNNING {%- elseif
outputs.diff['values'].stale_names == '' -%}ALL_REPORTED {%- elseif
(outputs.proposal.value ?? '') == outputs.diff['values'].stale_names
-%}ALREADY_ASKED {%- else -%}STALE{%- endif -%}
cases:
STALE:
- id: remember_proposal
type: io.kestra.plugin.core.kv.Set
key: "stale_required_checks_{{ vars.branch | slugify }}"
value: "{{ outputs.diff['values'].stale_names }}"
ttl: P30D
- id: explain_on_pull_request
type: io.kestra.plugin.github.issues.Comment
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ vars.repository }}"
issueNumber: "{{ outputs.facts['values'].pr }}"
body: |
{%- set candidates = fromJson(outputs.diff['values'].candidates) -%}
This pull request waits for {{ outputs.diff['values'].stale_summary }}, but no check with that name was reported on {{ outputs.run['values'].sha | slice(0, 7) }}, and every other check has finished. A renamed or removed job usually causes this, and it blocks every pull request into `{{ vars.branch }}`.
Checks that did run and are not required: {% for c in candidates %}`{{ c }}`{% if not loop.last %}, {% endif %}{% else %}none{% endfor %}.
A fix to the required checks of `{{ vars.branch }}` is waiting for approval in Kestra, execution `{{ execution.id }}`.
- id: approve
type: io.kestra.plugin.core.flow.Pause
description: Pick the checks that replace the stale ones, or leave branch
protection as it is.
onResume:
- id: decision
type: SELECT
values:
- Update the required checks
- Leave them as they are
defaults: Update the required checks
required: true
- id: replacements
type: MULTISELECT
description: Checks to require instead. Leave empty to only remove the stale
ones.
expression: "{{ fromJson(outputs.diff['values'].candidates) }}"
required: false
- id: decide
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve.onResume.decision == 'Update the required checks'
}}"
then:
- id: if_branch_protection
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.diff['values'].stale) | jq('[.[] |
select(.source == \"branch protection\")] | length > 0') | first
}}"
then:
- id: update_branch_protection
type: io.kestra.plugin.core.http.Request
method: PATCH
uri: "{{ render(vars.api) }}/branches/{{ vars.branch
}}/protection/required_status_checks"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
contentType: application/json
body: >-
{{ {'protection': fromJson(outputs.protection.body),
'stale': fromJson(outputs.diff['values'].stale), 'picks':
outputs.approve.onResume.replacements ?? [], 'apps':
fromJson(outputs.facts['values'].apps)} | jq('. as $f |
[$f.stale[] | select(.source == "branch protection") |
.context] as $gone | {strict: $f.protection.strict, checks:
([$f.protection.checks[] | select(.context as $c | $gone |
index($c) | not)] + [$f.picks[] | {context: .} + (if
$f.apps[.] then {app_id: $f.apps[.]} else {} end)] |
unique_by(.context))}') | first | toJson }}
- id: if_rulesets
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.diff['values'].stale) | jq('[.[] |
select(.source == \"ruleset\")] | length > 0') | first }}"
then:
- id: each_ruleset
type: io.kestra.plugin.core.flow.Loop
description: Each iteration gets the ruleset id, the stale checks to drop from
it and the checks to add.
values: >-
{{ {'stale': fromJson(outputs.diff['values'].stale),
'picks': outputs.approve.onResume.replacements ?? [],
'apps': fromJson(outputs.facts['values'].apps)} | jq('. as
$f | [$f.stale[] | select(.source == "ruleset")] |
group_by(.ruleset_id) | map({id: .[0].ruleset_id, gone:
map(.context), add: [$f.picks[] | {context: .} + (if
$f.apps[.] then {integration_id: $f.apps[.]} else {}
end)]})') | first | toJson }}
tasks:
- id: get_ruleset
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/rulesets/{{ fromJson(item.value).id }}"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: update_ruleset
type: io.kestra.plugin.core.http.Request
method: PUT
uri: "{{ render(vars.api) }}/rulesets/{{ fromJson(item.value).id }}"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
contentType: application/json
body: >-
{{ {'rules': fromJson(outputs.get_ruleset.body).rules,
'change': fromJson(item.value)} | jq('. as $f | {rules:
[$f.rules[] | if .type == "required_status_checks" then
.parameters.required_status_checks =
([.parameters.required_status_checks[] | select(.context
as $c | $f.change.gone | index($c) | not)] +
$f.change.add | unique_by(.context)) else . end]}') |
first | toJson }}
- id: protection_after
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/branches/{{ vars.branch
}}/protection/required_status_checks"
options:
allowedResponseCodes: [ 200, 404 ]
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: rulesets_after
type: io.kestra.plugin.core.http.Request
uri: "{{ render(vars.api) }}/rules/branches/{{ vars.branch }}"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
- id: verify
type: io.kestra.plugin.core.output.OutputValues
description: Required checks after the update that this commit still doesn't
report.
values:
still_missing: >-
{{ {'protection': outputs.protection_after.code == 200 ?
fromJson(outputs.protection_after.body).checks : [], 'rules':
fromJson(outputs.rulesets_after.body), 'reported':
fromJson(outputs.facts['values'].reported)} | jq('. as $f |
[$f.protection[].context] + [$f.rules[] | select(.type ==
"required_status_checks") |
.parameters.required_status_checks[].context] | unique |
map(select(. as $c | $f.reported | index($c) | not)) | join(",
")') | first }}
- id: report_on_pull_request
type: io.kestra.plugin.github.issues.Comment
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ vars.repository }}"
issueNumber: "{{ outputs.facts['values'].pr }}"
body: |
{%- set picks = outputs.approve.onResume.replacements ?? [] -%}
{%- set gone = fromJson(outputs.diff['values'].stale) | jq('[.[].context] | unique') | first -%}
Updated the required checks of `{{ vars.branch }}`: removed {% for g in gone %}`{{ g }}`{% if not loop.last %}, {% endif %}{% endfor %}{% if picks | length > 0 %}, now requiring {% for p in picks %}`{{ p }}`{% if not loop.last %}, {% endif %}{% endfor %} instead{% endif %}.
{% if outputs.verify['values'].still_missing == '' -%}
Every required check is now reported on {{ outputs.run['values'].sha | slice(0, 7) }}.
{%- else -%}
Still not reported on {{ outputs.run['values'].sha | slice(0, 7) }}: `{{ outputs.verify['values'].still_missing }}`.
{%- endif %}
else:
- id: left_as_is
type: io.kestra.plugin.core.log.Log
message: "Left the required checks of {{ vars.branch }} as they are. This flow
won't ask again about {{ outputs.diff['values'].stale_names }}
for 30 days."
ALREADY_ASKED:
- id: already_asked
type: io.kestra.plugin.core.log.Log
message: "Already asked about {{ outputs.diff['values'].stale_names }}, not
asking again."
CHECKS_STILL_RUNNING:
- id: checks_still_running
type: io.kestra.plugin.core.log.Log
message: "Other checks are still running on {{ outputs.run['values'].sha }}, the
next completed run will check again."
ALL_REPORTED:
- id: all_reported
type: io.kestra.plugin.core.log.Log
message: "Every required check of {{ vars.branch }} was reported on {{
outputs.run['values'].sha }}."
NOT_A_PULL_REQUEST:
- id: not_a_pull_request
type: io.kestra.plugin.core.log.Log
message: "{{ outputs.run['values'].sha }} isn't the head of an open pull request
into {{ vars.branch }}."
triggers:
- id: on_workflow_run
type: io.kestra.plugin.core.trigger.Webhook
description: Receives GitHub's `workflow_run` events and starts only for
completed `pull_request` runs.
key: "{{ secret('GITHUB_WEBHOOK_KEY') }}"
when: "{{ trigger.body.action == 'completed' and trigger.body.workflow_run.event
== 'pull_request' }}"