Repository navigation
Expand file tree
/
Copy pathcheck.sh
More file actions
450 lines (408 loc) · 19.1 KB
/
Copy pathcheck.sh
File metadata and controls
450 lines (408 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#!/usr/bin/env bash
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHECKS_DIR="${SCRIPT_DIR}/checks"
source "${CHECKS_DIR}/lib.sh"
set_output() {
local name="$1" value="$2"
local delimiter="ghadelimiter_${RANDOM}${RANDOM}${RANDOM}"
# Regenerate on the off chance the value contains the delimiter line
while [[ "$value" == *"$delimiter"* ]]; do
delimiter="ghadelimiter_${RANDOM}${RANDOM}${RANDOM}"
done
{
echo "${name}<<${delimiter}"
echo "${value}"
echo "${delimiter}"
} >> "${GITHUB_OUTPUT:-/dev/null}"
}
# ── Action toggles ───────────────────────────────────────────────────────────
# Booleans the action reads itself (not a check). Any value other than
# true/false is reported as a configuration error further below.
ANNOTATIONS="$(to_lower "${INPUT_ANNOTATIONS:-$DEFAULT_ANNOTATIONS}")"
COMMENT_ON_FAILURE="$(to_lower "${INPUT_COMMENT_ON_FAILURE:-$DEFAULT_COMMENT_ON_FAILURE}")"
# Value of the comment-on-failure step output: only an exact true enables it
comment_enabled() {
if [[ "$COMMENT_ON_FAILURE" == "true" ]]; then echo "true"; else echo "false"; fi
}
# ── Bypass ────────────────────────────────────────────────────────────────────
# Skip all checks when the PR author matches skip-actors, or the PR carries any
# label in skip-labels. Intended for bot PRs (e.g. Dependabot) or manually
# labelled exemptions. Emits a passing summary/outputs and exits.
inert() { printf '%s' "$1" | tr '\n' ' ' | tr -d '`'; }
emit_skip() {
local subject="$1" value="$2" input_name="$3"
local value_text skip_summary
value_text="$(inert "$value")"
skip_summary="## PR Requirements Check"$'\n\n'"Checks skipped: ${subject} \`${value_text}\` matched \`${input_name}\`."
printf '%s\n' "$skip_summary" >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
set_output "summary" "$skip_summary"
set_output "failed-checks" ""
set_output "comment-on-failure" "$(comment_enabled)"
set_output "result" "pass"
set_output "pass-count" "0"
set_output "fail-count" "0"
set_output "warn-count" "0"
set_output "total-count" "0"
set_output "skipped" "true"
set_output "skip-reason" "${subject} ${value_text} matched ${input_name}"
echo ""
echo "PR Requirements: skipped (${subject} ${value_text} matched ${input_name})"
exit 0
}
# Sets BYPASS_SUBJECT, BYPASS_VALUE and BYPASS_INPUT when the PR is bypassed
find_bypass() {
local pr_author="${INPUT_PR_AUTHOR:-}"
if [[ -n "$pr_author" ]] && csv_contains_ignore_case "$pr_author" "${INPUT_SKIP_ACTORS:-}"; then
BYPASS_SUBJECT="author" BYPASS_VALUE="$pr_author" BYPASS_INPUT="skip-actors"
return 0
fi
local pr_labels="${INPUT_LABELS:-}" skip_label
split_csv "${INPUT_SKIP_LABELS:-}"
local skip_label_list=(${SPLIT_RESULT[@]+"${SPLIT_RESULT[@]}"})
for skip_label in ${skip_label_list[@]+"${skip_label_list[@]}"}; do
if csv_contains_ignore_case "$skip_label" "$pr_labels"; then
BYPASS_SUBJECT="label" BYPASS_VALUE="$skip_label" BYPASS_INPUT="skip-labels"
return 0
fi
done
return 1
}
# Lets the action skip steps that run before this script when a bypass applies
if [[ "${1:-}" == "--detect-bypass" ]]; then
if find_bypass; then
set_output "bypassed" "true"
else
set_output "bypassed" "false"
fi
exit 0
fi
if find_bypass; then
emit_skip "$BYPASS_SUBJECT" "$BYPASS_VALUE" "$BYPASS_INPUT"
fi
# ── Check Registry ──────────────────────────────────────────────────────────
# Format: "env_toggle|default|display_name|script_name"
# To add a new check: append an entry here and create the script in checks/
REGISTRY=(
"INPUT_CHECK_TITLE|true|PR Title|title_format.sh"
"INPUT_CHECK_DESCRIPTION|true|PR Description|description.sh"
"INPUT_CHECK_ISSUE_REFERENCE|true|Issue Reference|issue_reference.sh"
"INPUT_CHECK_BRANCH_NAME|false|Branch Name|branch_name.sh"
"INPUT_CHECK_PR_SIZE|false|PR Size|pr_size.sh"
"INPUT_CHECK_LABEL|false|Label Presence|label_presence.sh"
"INPUT_CHECK_TARGET_BRANCH|false|Target Branch|target_branch.sh"
"INPUT_CHECK_RELEASE_NOTES|false|Release Notes|release_notes.sh"
)
# ── Remediation tips ──────────────────────────────────────────────────────────
# Per-check "how to fix" guidance, keyed by display name. Tips are built from the
# same configuration inputs the checks use, so guidance stays accurate as rules
# change. Config values are rendered as inert code spans (backticks/newlines
# stripped) to keep the summary safe.
code() {
# Render "$1" as an inert inline code span; fall back to "$2" when empty.
local value="$1"
value=$(printf '%s' "$value" | tr '\n' ' ' | tr -d '`')
if [[ -z "$value" ]]; then
value="$2"
fi
printf '`%s`' "$value"
}
remediation_for() {
local title_formats title_types desc_min desc_sections issue_keyword
local branch_pattern branch_ticket max_files req_labels targets
case "$1" in
"PR Title")
title_formats="${INPUT_TITLE_FORMATS:-$DEFAULT_TITLE_FORMATS}"
title_types="${INPUT_TITLE_TYPES:-$DEFAULT_TITLE_TYPES}"
echo "- **PR Title** — the title must match one of these formats: $(code "$title_formats" conventional)."
if [[ ",$title_formats," == *",conventional,"* ]]; then
echo " - Allowed conventional types: $(code "$title_types" "feat, fix, ...")."
if [[ "$(to_lower "${INPUT_TITLE_REQUIRE_SCOPE:-false}")" == "true" ]]; then
echo " - A scope is required, e.g. \`feat(api): add retry logic\`."
fi
echo " - ✅ \`feat: add retry logic\`"
echo " - ❌ \`added retry logic\`"
fi
if [[ -n "${INPUT_TITLE_MAX_LENGTH:-}" ]]; then
echo " - Keep the title at or below $(code "$INPUT_TITLE_MAX_LENGTH" -) characters."
fi ;;
"PR Description")
desc_min="${INPUT_DESCRIPTION_MIN_LENGTH:-$DEFAULT_DESCRIPTION_MIN_LENGTH}"
desc_sections="${INPUT_DESCRIPTION_REQUIRED_SECTIONS:-}"
echo "- **PR Description** — write a description of at least $(code "$desc_min" 20) characters."
if [[ -n "$desc_sections" ]]; then
echo " - Required sections: $(code "$desc_sections" -)."
fi
if [[ "$(to_lower "${INPUT_DESCRIPTION_IGNORE_COMMENTS:-false}")" == "true" ]]; then
echo " - Template comments (\`<!-- ... -->\`) do not count; replace them with your own text."
fi
if [[ "$(to_lower "${INPUT_DESCRIPTION_REQUIRE_SECTION_CONTENT:-false}")" == "true" ]]; then
echo " - Write some text under each required section heading."
fi ;;
"Issue Reference")
issue_keyword="${INPUT_ISSUE_REFERENCE_REQUIRE_KEYWORD:-false}"
if [[ "$(to_lower "$issue_keyword")" == "true" ]]; then
echo "- **Issue Reference** — reference an issue with a keyword, e.g. \`Closes #123\` or \`Fixes AB#123\`."
else
echo "- **Issue Reference** — reference an issue in the description, e.g. \`#123\`."
fi ;;
"Branch Name")
branch_pattern="${INPUT_BRANCH_PATTERN:-$DEFAULT_BRANCH_PATTERN}"
echo "- **Branch Name** — the branch name must match $(code "$branch_pattern" -), e.g. \`feature/add-login\`."
if [[ "$(to_lower "${INPUT_BRANCH_REQUIRE_TICKET:-false}")" == "true" ]]; then
branch_ticket="${INPUT_BRANCH_TICKET_PATTERN:-$DEFAULT_BRANCH_TICKET_PATTERN}"
echo " - Must include a ticket after the prefix, matching $(code "$branch_ticket" -), e.g. \`feature/123-add-login\`."
fi ;;
"PR Size")
max_files="${INPUT_MAX_FILES_CHANGED:-$DEFAULT_MAX_FILES_CHANGED}"
echo "- **PR Size** — keep changed files at or below $(code "$max_files" 50); split larger changes into smaller PRs."
if [[ -n "${INPUT_MAX_LINES_CHANGED:-}" ]]; then
echo " - Keep changed lines (additions + deletions) at or below $(code "$INPUT_MAX_LINES_CHANGED" -)."
fi ;;
"Label Presence")
req_labels="${INPUT_REQUIRED_LABELS:-}"
if [[ -n "$req_labels" ]]; then
echo "- **Label Presence** — add the required label(s): $(code "$req_labels" -)."
else
echo "- **Label Presence** — add at least one label to the PR."
fi ;;
"Target Branch")
targets="${INPUT_ALLOWED_TARGET_BRANCHES:-$DEFAULT_ALLOWED_TARGET_BRANCHES}"
echo "- **Target Branch** — retarget the PR to an allowed branch: $(code "$targets" "main, master")." ;;
"Release Notes")
echo "- **Release Notes** — add a heading matching $(code "${INPUT_RELEASE_NOTES_TAG:-$DEFAULT_RELEASE_NOTES_TAG}" -) followed directly by a bullet list, e.g. \`- Added retry logic\`."
if [[ -n "${INPUT_RELEASE_NOTES_SKIP_LABELS-$DEFAULT_RELEASE_NOTES_SKIP_LABELS}" ]]; then
echo " - If the change needs no release notes, add a label: $(code "${INPUT_RELEASE_NOTES_SKIP_LABELS-$DEFAULT_RELEASE_NOTES_SKIP_LABELS}" -)."
fi ;;
"Warn Checks")
echo "- **Warn Checks** — list only known check ids in \`warn-checks\`: ${KNOWN_IDS[*]}." ;;
"Annotations")
echo "- **Annotations** — set \`annotations\` to \`true\` or \`false\`." ;;
"Comment On Failure")
echo "- **Comment On Failure** — set \`comment-on-failure\` to \`true\` or \`false\`." ;;
*)
echo "- **$1** — see the check details above and the contributing guidelines." ;;
esac
}
# ── Runner ───────────────────────────────────────────────────────────────────
declare -a CHECK_NAMES=()
declare -a CHECK_RESULTS=()
declare -a CHECK_MESSAGES=()
declare -a CHECK_IDS=()
FAIL_COUNT=0
PASS_COUNT=0
WARN_COUNT=0
# Action-level config errors (not tied to an executed check): fail the job
# but stay out of pass/fail/total counts
CONFIG_ERROR_COUNT=0
# Check id derived from the registry toggle, e.g. INPUT_CHECK_PR_SIZE -> pr-size
check_id_for() { to_lower "${1#INPUT_CHECK_}" | tr '_' '-'; }
# Return 0 when $1 equals any of the remaining arguments.
contains() {
local needle="$1" item
shift
for item in "$@"; do
[[ "$item" == "$needle" ]] && return 0
done
return 1
}
declare -a KNOWN_IDS=()
for entry in "${REGISTRY[@]}"; do
IFS='|' read -r env_var _ _ _ <<< "$entry"
KNOWN_IDS+=("$(check_id_for "$env_var")")
done
declare -a WARN_IDS=()
split_csv "${INPUT_WARN_CHECKS:-}"
for warn_check in ${SPLIT_RESULT[@]+"${SPLIT_RESULT[@]}"}; do
WARN_IDS+=("$(to_lower "$warn_check")")
done
# result is pass, fail (the PR breaks a rule), warn (a fail listed in
# warn-checks), error (invalid check configuration) or config-error (invalid
# action-level configuration, kept out of the counts)
record_result() {
local name="$1" result="$2" message="$3" check_id="${4:-}"
CHECK_IDS+=("$check_id")
CHECK_NAMES+=("$name")
CHECK_RESULTS+=("$result")
CHECK_MESSAGES+=("$message")
case "$result" in
pass) ((PASS_COUNT++)) ;;
warn) ((WARN_COUNT++)) ;;
config-error) ((CONFIG_ERROR_COUNT++)) ;;
*) ((FAIL_COUNT++)) ;;
esac
}
run_check() {
local name="$1" check_id="$3"
local script="${CHECKS_DIR}/$2"
if [[ ! -f "$script" ]]; then
record_result "$name" "error" "check script not found: $script" "$check_id"
return
fi
local output exit_code
output=$(bash "$script" 2>&1)
exit_code=$?
# Exit 2 is a configuration error: never downgraded to a warning
if [[ "$exit_code" -eq 0 ]]; then
record_result "$name" "pass" "$output" "$check_id"
elif [[ "$exit_code" -eq "$CONFIG_ERROR_EXIT" ]]; then
record_result "$name" "error" "$output" "$check_id"
elif contains "$check_id" ${WARN_IDS[@]+"${WARN_IDS[@]}"}; then
record_result "$name" "warn" "$output" "$check_id"
else
record_result "$name" "fail" "$output" "$check_id"
fi
}
# INPUT_CHECK_PR_SIZE -> check-pr-size
input_name_of() {
printf '%s' "${1#INPUT_}" | tr '[:upper:]_' '[:lower:]-'
}
for warn_check in ${WARN_IDS[@]+"${WARN_IDS[@]}"}; do
if ! contains "$warn_check" "${KNOWN_IDS[@]}"; then
record_result "Warn Checks" "config-error" "config error: unknown check '${warn_check}' in input 'warn-checks'"
fi
done
if [[ "$ANNOTATIONS" != "true" && "$ANNOTATIONS" != "false" ]]; then
record_result "Annotations" "config-error" \
"config error: input 'annotations' must be true or false, got '${INPUT_ANNOTATIONS}'"
fi
if [[ "$COMMENT_ON_FAILURE" != "true" && "$COMMENT_ON_FAILURE" != "false" ]]; then
record_result "Comment On Failure" "config-error" \
"config error: input 'comment-on-failure' must be true or false, got '${INPUT_COMMENT_ON_FAILURE}'"
fi
for idx in "${!REGISTRY[@]}"; do
IFS='|' read -r env_var default display_name script_name <<< "${REGISTRY[$idx]}"
toggle="${!env_var:-$default}"
case "$(to_lower "$toggle")" in
true) run_check "$display_name" "$script_name" "${KNOWN_IDS[$idx]}" ;;
false) ;;
*) record_result "$display_name" "error" \
"config error: input '$(input_name_of "$env_var")' must be true or false, got '${toggle}'" \
"${KNOWN_IDS[$idx]}" ;;
esac
done
# ── Summary ──────────────────────────────────────────────────────────────────
TOTAL=$((PASS_COUNT + FAIL_COUNT + WARN_COUNT))
BLOCKING_COUNT=$((FAIL_COUNT + CONFIG_ERROR_COUNT))
RESULT_EXTRA=""
if [[ "$WARN_COUNT" -gt 0 ]]; then
RESULT_EXTRA+=", ${WARN_COUNT} with warnings"
fi
if [[ "$CONFIG_ERROR_COUNT" -gt 0 ]]; then
RESULT_EXTRA+=", ${CONFIG_ERROR_COUNT} configuration error(s)"
fi
# A function rather than an inline $( { ... } ): bash 3.2 (macOS) cannot parse
# case patterns inside command substitution.
render_summary() {
echo "## PR Requirements Check"
echo ""
echo "| Check | Status | Details |"
echo "|-------|--------|---------|"
for i in "${!CHECK_NAMES[@]}"; do
if [[ "${CHECK_RESULTS[$i]}" == "pass" ]]; then
echo "| ${CHECK_NAMES[$i]} | ✅ Pass | - |"
else
case "${CHECK_RESULTS[$i]}" in
warn) status="🟡 Warning" ;;
error|config-error) status="⚠️ Error" ;;
*) status="❌ Fail" ;;
esac
# Render PR-controlled text as an inert code span: strip backticks,
# flatten newlines, escape table pipes
detail="${CHECK_MESSAGES[$i]#fail: }"
detail="${detail#error: }"
detail=$(printf '%s' "$detail" | tr '\n' ' ' | tr -d '`' | sed 's/|/\\|/g')
if [[ -z "$detail" ]]; then
detail="-"
else
detail="\`${detail}\`"
fi
echo "| ${CHECK_NAMES[$i]} | ${status} | ${detail} |"
fi
done
echo ""
echo "**Result:** ${PASS_COUNT}/${TOTAL} checks passed${RESULT_EXTRA}"
# ── How to fix (failures only) ───────────────────────────────────────────
if [[ "$BLOCKING_COUNT" -gt 0 ]]; then
echo ""
echo "### How to fix"
echo ""
echo "The checks above must pass before this PR can merge."
echo ""
for i in "${!CHECK_NAMES[@]}"; do
case "${CHECK_RESULTS[$i]}" in
fail|config-error) remediation_for "${CHECK_NAMES[$i]}" ;;
error) echo "- **${CHECK_NAMES[$i]}** — the action configuration in the workflow file is invalid; fix the input named in the details above." ;;
esac
done
fi
}
SUMMARY_MARKDOWN="$(render_summary)"
printf '%s\n' "$SUMMARY_MARKDOWN" >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
if [[ "$BLOCKING_COUNT" -eq 0 ]]; then
RESULT="pass"
else
RESULT="fail"
fi
set_output "result" "$RESULT"
set_output "pass-count" "$PASS_COUNT"
set_output "fail-count" "$FAIL_COUNT"
set_output "warn-count" "$WARN_COUNT"
set_output "total-count" "$TOTAL"
set_output "skipped" "false"
set_output "skip-reason" ""
failed_check_ids=""
for i in "${!CHECK_NAMES[@]}"; do
if [[ "${CHECK_RESULTS[$i]}" == "fail" || "${CHECK_RESULTS[$i]}" == "error" ]] && [[ -n "${CHECK_IDS[$i]}" ]]; then
failed_check_ids+="${CHECK_IDS[$i]},"
fi
done
set_output "failed-checks" "${failed_check_ids%,}"
set_output "comment-on-failure" "$(comment_enabled)"
set_output "summary" "$SUMMARY_MARKDOWN"
# ── Annotations ──────────────────────────────────────────────────────────────
# Shown in the PR checks UI. Values are escaped per the workflow command spec
# so PR-controlled text cannot end the command early.
escape_command_data() {
local value="$1"
value="${value//'%'/%25}"
value="${value//$'\r'/%0D}"
value="${value//$'\n'/%0A}"
printf '%s' "$value"
}
escape_command_property() {
local value
value="$(escape_command_data "$1")"
value="${value//:/%3A}"
value="${value//,/%2C}"
printf '%s' "$value"
}
if [[ "$ANNOTATIONS" != "false" ]]; then
for i in "${!CHECK_NAMES[@]}"; do
case "${CHECK_RESULTS[$i]}" in
fail|error|config-error) command="error" ;;
warn) command="warning" ;;
*) continue ;;
esac
echo "::${command} title=$(escape_command_property "${CHECK_NAMES[$i]}")::$(escape_command_data "${CHECK_MESSAGES[$i]#fail: }")"
done
fi
# ── CLI output ───────────────────────────────────────────────────────────────
# Workflow commands are disabled while PR-controlled messages are printed.
stop_commands_token="check-pr-requirements-${RANDOM}${RANDOM}${RANDOM}"
echo "::stop-commands::${stop_commands_token}"
echo ""
echo "PR Requirements: ${PASS_COUNT}/${TOTAL} passed${RESULT_EXTRA}"
for i in "${!CHECK_NAMES[@]}"; do
case "${CHECK_RESULTS[$i]}" in
pass) echo " ✅ ${CHECK_NAMES[$i]}" ;;
warn) echo " 🟡 ${CHECK_NAMES[$i]}: ${CHECK_MESSAGES[$i]}" ;;
error|config-error) echo " ⚠️ ${CHECK_NAMES[$i]}: ${CHECK_MESSAGES[$i]}" ;;
*) echo " ❌ ${CHECK_NAMES[$i]}: ${CHECK_MESSAGES[$i]}" ;;
esac
done
echo "::${stop_commands_token}::"
if [[ "$BLOCKING_COUNT" -gt 0 ]]; then
exit 1
fi
exit 0