diff --git a/.github/actions/setup-gentoo/action.yml b/.github/actions/setup-gentoo/action.yml index 4d3810629b..cb37fc16be 100644 --- a/.github/actions/setup-gentoo/action.yml +++ b/.github/actions/setup-gentoo/action.yml @@ -22,7 +22,7 @@ runs: run: | cat >> /etc/portage/make.conf << EOF MAKEOPTS="\${MAKEOPTS} -j$(nproc)" - PORTAGE_ELOG_CLASSES="qa warn error" + PORTAGE_ELOG_CLASSES="log warn error qa" PORTAGE_ELOG_SYSTEM="save" FETCHCOMMAND="\${FETCHCOMMAND} --no-verbose" RESUMECOMMAND="\${RESUMECOMMAND} --no-verbose" diff --git a/.github/workflows/emerge-on-pr.yml b/.github/workflows/emerge-on-pr.yml index c0ddd6fb94..2741ff8ecd 100644 --- a/.github/workflows/emerge-on-pr.yml +++ b/.github/workflows/emerge-on-pr.yml @@ -72,6 +72,7 @@ jobs: ref: ${{ github.event.pull_request.head.sha }} - name: setup portage config + id: setup uses: ./.github/actions/setup-gentoo - name: setup cpu flags @@ -85,22 +86,97 @@ jobs: fi - name: emerge --onlydeps packages + id: deps + shell: bash env: ATOM: ${{ matrix.target.package }} run: | - FEATURES="getbinpkg" emerge --onlydeps --jobs 2 --quiet --verbose --autounmask=y --autounmask-write=y --autounmask-continue=y "$ATOM" + FEATURES="getbinpkg" emerge --onlydeps --jobs 2 --quiet --verbose --autounmask=y --autounmask-write=y --autounmask-continue=y "$ATOM" 2>&1 | tee /var/tmp/deps.log rm -rf /var/log/portage/elog/* - name: emerge packages + id: emerge + shell: bash env: ATOM: ${{ matrix.target.package }} - run: emerge --verbose --autounmask=y --autounmask-write=y --autounmask-continue=y "$ATOM" + run: emerge --verbose --autounmask=y --autounmask-write=y --autounmask-continue=y "$ATOM" 2>&1 | tee /var/tmp/emerge.log + # Portage cleans the build directory of every package that merged, so what is left failed + - name: save failed build logs + if: ${{ failure() }} + env: + LOG: build-log-${{ strategy.job-index }}.log + run: | + for log in /var/tmp/portage/*/*/temp/build.log; do + [ -f "$log" ] || continue + pkg=${log#/var/tmp/portage/} + echo ">>> ${pkg%/temp/build.log}" + sed 's/\x1b\[[0-9;]*m//g' "$log" + done > "$LOG" + [ -s "$LOG" ] || rm -f "$LOG" + + - name: upload failed build logs + id: build-logs + if: ${{ failure() }} + uses: actions/upload-artifact@v7 + with: + path: build-log-${{ strategy.job-index }}.log + archive: false + if-no-files-found: ignore + + - name: save portage elog + if: ${{ !cancelled() }} + env: + ATOM: ${{ matrix.target.package }} + PROFILE: ${{ matrix.target.profile }} + SETUP: ${{ steps.setup.outcome }} + DEPS: ${{ steps.deps.outcome }} + OUTCOME: ${{ steps.emerge.outcome }} + BUILD_LOGS: ${{ steps.build-logs.outputs.artifact-url }} + run: | + mkdir -p elog-report + echo "$ATOM" > elog-report/atom + echo "$PROFILE" > elog-report/profile + echo "$BUILD_LOGS" > elog-report/build-logs + echo "$SETUP" > elog-report/setup + echo "$DEPS" > elog-report/deps + echo "$OUTCOME" > elog-report/outcome + log= + [ "$DEPS" != failure ] || log=/var/tmp/deps.log + [ "$OUTCOME" != failure ] || log=/var/tmp/emerge.log + # news and config file notices differ between images and say nothing about the failure + [ -z "$log" ] || grep -vE '^ \* (IMPORTANT: |Use eselect news|See the CONFIGURATION FILES|sections of the emerge man page)' "$log" \ + | cat -s | tail -n 40 > elog-report/output + # the onlydeps elog is left over when that step fails + [ "$OUTCOME" != skipped ] || exit 0 + for file in /var/log/portage/elog/*; do + [ -f "$file" ] || continue + # category:pf:date.log -> category/pf + pkg=${file##*/} + pkg=${pkg%:*} + echo ">>> ${pkg/://}" + cat "$file" + done | awk ' + # pkg_pretend writes a second file for the package, and an unsaved INFO section + # between two sections of the same class repeats their header + /^>>> / { if ($0 == pkg) next; pkg = $0; section = "" } + /^(LOG|WARN|ERROR|QA): [a-z]+$/ { if ($0 == section) next; section = $0 } + { print } + ' > elog-report/elog + + - name: upload portage elog + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: elog-${{ strategy.job-index }} + path: elog-report/ + + # warn and log elog, such as CONFIG_CHECK without kernel sources, only go to the PR comment - name: check portage elog run: | - if ls /var/log/portage/elog/* 1> /dev/null 2>&1; then - echo "Found Portage elog messages:" - cat /var/log/portage/elog/* + cat elog-report/elog + if grep -qE '^(QA|ERROR): [a-z]+$' elog-report/elog; then + echo "Found QA or error elog messages." exit 1 fi - echo "No elog messages found." + echo "No QA or error elog messages found." diff --git a/.github/workflows/pkgcheck-comment.yml b/.github/workflows/pkgcheck-comment.yml index 511858c90a..1b87465dc2 100644 --- a/.github/workflows/pkgcheck-comment.yml +++ b/.github/workflows/pkgcheck-comment.yml @@ -2,8 +2,15 @@ name: pkgcheck-comment on: workflow_run: # pr-rules also reruns on a description edit, which pkgcheck does not - workflows: [pkgcheck, pr-rules] - types: [completed] + workflows: [pkgcheck, pr-rules, emerge-on-pr] + types: [requested, completed] + +# A run's requested and completed events share a group, so they are handled +# in that order. Each section has its own group: a group keeps only one +# pending run, and a newer one would cancel it. +concurrency: + group: ${{ github.workflow }}-${{ github.event.workflow_run.name }}-${{ github.event.workflow_run.head_sha }} + cancel-in-progress: false permissions: contents: read @@ -12,21 +19,39 @@ permissions: jobs: comment: - if: github.event.workflow_run.event == 'pull_request' + if: >- + github.event.workflow_run.event == 'pull_request' && + !(github.event.action == 'requested' && github.event.workflow_run.name == 'pr-rules') runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_URL: ${{ github.event.workflow_run.html_url }} steps: - name: checkout uses: actions/checkout@v7 + - name: show the run in progress + if: github.event.action == 'requested' + env: + WORKFLOW: ${{ github.event.workflow_run.name }} + run: | + case $WORKFLOW in + pkgcheck) scripts/comment-status.sh pkgcheck ":hourglass: scanning \`${HEAD_SHA:0:9}\`, see the [run](${RUN_URL})" ;; + emerge-on-pr) scripts/comment-status.sh elog ":hourglass: emerging \`${HEAD_SHA:0:9}\`, see the [run](${RUN_URL})" ;; + esac + - name: check for the report + if: github.event.action == 'completed' id: report env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} RUN_ID: ${{ github.event.workflow_run.id }} run: | artifacts=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID/artifacts" --paginate --slurp) available=$(jq 'any(.[] | .artifacts[]; .name == "pkgcheck-report")' <<< "$artifacts") echo "available=$available" >> "$GITHUB_OUTPUT" + elog=$(jq 'any(.[] | .artifacts[]; .name | startswith("elog-"))' <<< "$artifacts") + echo "elog=$elog" >> "$GITHUB_OUTPUT" - name: download the report if: steps.report.outputs.available == 'true' @@ -39,16 +64,41 @@ jobs: - name: post the report if: steps.report.outputs.available == 'true' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - HEAD_SHA: ${{ github.event.workflow_run.head_sha }} - RUN_URL: ${{ github.event.workflow_run.html_url }} run: scripts/pkgcheck-comment.sh pkgcheck-report - - name: explain why a pull request breaks the pull request rules + - name: post a missing report + if: steps.report.outputs.available == 'false' && github.event.workflow_run.name == 'pkgcheck' + run: | + scripts/comment-status.sh pkgcheck ":x: the scan left no report, see the [run](${RUN_URL})" + + - name: download the elog + if: steps.report.outputs.elog == 'true' + uses: actions/download-artifact@v8 + with: + pattern: elog-* + path: elog + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: post the elog + if: steps.report.outputs.elog == 'true' + run: scripts/emerge-elog-comment.sh elog + + # a successful run without elog had no emerge targets + - name: post a missing elog + if: steps.report.outputs.elog == 'false' && github.event.workflow_run.name == 'emerge-on-pr' env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + CONCLUSION: ${{ github.event.workflow_run.conclusion }} + run: | + if [ "$CONCLUSION" = success ]; then + scripts/comment-status.sh elog + else + scripts/comment-status.sh elog ":x: no package was emerged, see the [run](${RUN_URL})" + fi + + # the pkgcheck and pr-rules runs of the same commit already post this + - name: explain why a pull request breaks the pull request rules + if: github.event.action == 'completed' && github.event.workflow_run.name != 'emerge-on-pr' run: | pulls=$(gh api "repos/$GITHUB_REPOSITORY/pulls?state=open&per_page=100" --paginate --slurp) pr=$(jq -r --arg sha "$HEAD_SHA" 'first(.[][] | select(.head.sha == $sha) | .number) // empty' <<< "$pulls") diff --git a/scripts/comment-status.sh b/scripts/comment-status.sh new file mode 100755 index 0000000000..4f0c48c2a9 --- /dev/null +++ b/scripts/comment-status.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# usage: comment-status.sh
[] +# Sets a section of the pkgcheck report comment to its heading and a status +# line, or removes the section when no status is given. +set -euo pipefail +MARKER='' +section=${1:?section} +status=${2:-} +body_file=$(mktemp) +trap 'rm -f "$body_file"' EXIT + +pr=$(scripts/pr-at-commit.sh "$GITHUB_REPOSITORY" "$HEAD_SHA") +if [ -z "$pr" ]; then + echo 'no open pull request at this commit' + exit 0 +fi +echo "pull request #${pr}" + +if [ -n "$status" ]; then + case $section in + pkgcheck) echo '## Pull request pkgcheck report' ;; + elog) echo '## emerge elog' ;; + esac > "$body_file" + echo >> "$body_file" + echo "*Status*: ${status}" >> "$body_file" +fi + +scripts/upsert-comment-section.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" "$section" "$body_file" diff --git a/scripts/emerge-elog-comment.sh b/scripts/emerge-elog-comment.sh new file mode 100755 index 0000000000..91bd67f540 --- /dev/null +++ b/scripts/emerge-elog-comment.sh @@ -0,0 +1,232 @@ +#!/usr/bin/env bash +# usage: emerge-elog-comment.sh +# Each subdirectory holds one emerge-on-pr target: atom, profile, outcome, elog. +set -euo pipefail +MARKER='' +MAX_LINES=40 +MAX_BYTES=40000 +MAX_TABLE=20000 +artifacts_dir=${1:?artifacts-directory} +body_file=$(mktemp) +trap 'rm -f "$body_file"' EXIT + +pr=$(scripts/pr-at-commit.sh "$GITHUB_REPOSITORY" "$HEAD_SHA") +if [ -z "$pr" ]; then + echo 'no open pull request at this commit' + exit 0 +fi +echo "pull request #${pr}" + +# field : one artifact value. The pull request's run wrote it, so only +# atom characters are kept. +field() { + { head -c 200 "$1/$2" 2>/dev/null || true; } | tr -cd '[:alnum:]/._+=~@:-' +} + +targets=() +while IFS= read -r dir; do + targets+=("$dir") +done < <( + find "$artifacts_dir" -mindepth 1 -maxdepth 1 -type d | while IFS= read -r dir; do + echo "$(field "$dir" atom) $(field "$dir" profile) $dir" + done | sort -V | cut -d ' ' -f 3- +) +if [ "${#targets[@]}" -eq 0 ]; then + echo 'no elog reports' + exit 0 +fi + +# sections : Portage starts every elog section with "CLASS: phase". +sections() { + grep -cE "^(${2}): [a-z]+\$" "$1" || true +} + +# add_detail <file> [<build-log-url>]: a collapsed block, shared +# by the profiles that printed the same text +keys=() +declare -A detail_atom detail_title detail_text detail_profiles detail_links detail_unlinked atom_profiles +add_detail() { + local text key + text=$(sed 's/\x1b\[[0-9;]*m//g' "$4") + # the fetch lines carry a wget time stamp and byte count that differ between runners + key=$(sed -E '/^[0-9-]{10} [0-9:]{8} /{s///; s/\[[0-9/]+\]//g}' <<< "$1 $3"$'\n'"$text" | md5sum) + if [ -z "${detail_text[$key]+set}" ]; then + keys+=("$key") + detail_atom[$key]=$1 + detail_title[$key]="<code>$1</code> $3" + detail_text[$key]=$text + fi + detail_profiles[$key]+="${detail_profiles[$key]:+, }<code>$2</code>" + if [ -n "${5:-}" ]; then + detail_links[$key]+="${detail_links[$key]:+ ยท }<a href=\"$5\">${2/-desktop/}</a>" + else + detail_unlinked[$key]=1 + fi +} + +t_atom=() +t_profile=() +t_emerge=() +t_elog=() +broken=0 +output=0 +failing=0 +warned=0 +logged=0 +for dir in "${targets[@]}"; do + atom=$(field "$dir" atom) + atom=${atom#=} + profile=$(field "$dir" profile) + atom_profiles[$atom]+="${atom_profiles[$atom]:+, }<code>${profile}</code>" + outcome=$(field "$dir" outcome) + if [ "$(field "$dir" setup)" = failure ]; then + emerge='portage setup failed' + elif [ "$(field "$dir" deps)" = failure ]; then + emerge='dependencies failed' + else + case $outcome in + success|failure) emerge=$outcome ;; + skipped) emerge='not run, an earlier step failed' ;; + *) emerge=unknown ;; + esac + fi + [ "$outcome" = success ] || broken=$(( broken + 1 )) + build_logs=$(field "$dir" build-logs) + [[ $build_logs == "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/"* ]] || build_logs= + if [ -s "$dir/output" ]; then + add_detail "$atom" "$profile" 'emerge output' "$dir/output" "$build_logs" + output=1 + fi + elog=$dir/elog + if [ ! -s "$elog" ]; then + case $outcome in + success|failure) verdict=none ;; + *) verdict=N/A ;; + esac + else + qa=$(sections "$elog" QA) + errors=$(sections "$elog" ERROR) + warnings=$(sections "$elog" WARN) + messages=$(sections "$elog" LOG) + counts=() + [ "$qa" -eq 0 ] || counts+=("${qa} QA") + [ "$errors" -eq 0 ] || counts+=("${errors} error") + [ "$warnings" -eq 0 ] || counts+=("${warnings} warn") + [ "$messages" -eq 0 ] || counts+=("${messages} log") + if [ $(( qa + errors )) -gt 0 ]; then + failing=$(( failing + 1 )) + elif [ "$warnings" -gt 0 ]; then + warned=$(( warned + 1 )) + else + logged=$(( logged + 1 )) + fi + verdict=$(printf '%s, ' "${counts[@]}") + verdict=${verdict%, } + add_detail "$atom" "$profile" elog "$elog" + fi + t_atom+=("$atom") + t_profile+=("$profile") + t_emerge+=("$emerge") + t_elog+=("$verdict") +done + +# One row per package when every profile gave the same result, one per profile otherwise; +# packages that emerged everywhere without elog are only counted. +rows=() +clean=0 +i=0 +while [ "$i" -lt "${#t_atom[@]}" ]; do + j=$i + same=1 + while [ "$j" -lt "${#t_atom[@]}" ] && [ "${t_atom[$j]}" = "${t_atom[$i]}" ]; do + [ "${t_emerge[$j]}" = "${t_emerge[$i]}" ] && [ "${t_elog[$j]}" = "${t_elog[$i]}" ] || same=0 + j=$(( j + 1 )) + done + if [ "$same" -eq 1 ] && [ "${t_emerge[$i]}" = success ] && [ "${t_elog[$i]}" = none ]; then + clean=$(( clean + 1 )) + elif [ "$same" -eq 1 ] && [ $(( j - i )) -gt 1 ]; then + rows+=("| \`${t_atom[$i]}\` | all | ${t_emerge[$i]} | ${t_elog[$i]} |") + else + for (( k = i; k < j; k++ )); do + rows+=("| \`${t_atom[$k]}\` | \`${t_profile[$k]}\` | ${t_emerge[$k]} | ${t_elog[$k]} |") + done + fi + i=$j +done + +{ + echo '## emerge elog' + echo + echo "*Newest commit emerged*: \`${HEAD_SHA:0:9}\`" + if [ "$broken" -gt 0 ] && [ "$output" -gt 0 ]; then + echo "*Status*: :x: **emerge failed**, the output is below and in the [run](${RUN_URL})" + elif [ "$broken" -gt 0 ]; then + echo "*Status*: :x: **emerge failed**, see the [run](${RUN_URL})" + elif [ "$failing" -gt 0 ]; then + echo '*Status*: :x: **QA or error elog**, which fails the emerge job' + elif [ "$warned" -gt 0 ]; then + echo '*Status*: :warning: warnings only, which do not fail the emerge job' + elif [ "$logged" -gt 0 ]; then + echo '*Status*: :white_check_mark: messages only, which do not fail the emerge job' + else + echo '*Status*: :white_check_mark: no elog' + fi + if [ "${#rows[@]}" -gt 0 ]; then + echo + echo '| Package | Profile | emerge | elog |' + echo '| --- | --- | --- | --- |' + table=0 + for (( k = 0; k < ${#rows[@]}; k++ )); do + table=$(( table + ${#rows[$k]} + 1 )) + if [ "$table" -gt "$MAX_TABLE" ]; then + echo + echo "$(( ${#rows[@]} - k )) more rows in the [run](${RUN_URL})." + break + fi + printf '%s\n' "${rows[$k]}" + done + fi + packages=packages + [ "$clean" -ne 1 ] || packages=package + if [ "$clean" -gt 0 ] && [ "${#rows[@]}" -gt 0 ]; then + echo + echo "${clean} more ${packages} emerged on every profile with no elog." + elif [ "$clean" -gt 0 ]; then + echo + echo "All ${clean} ${packages} emerged on every profile with no elog." + fi +} > "$body_file" +# a comment holds at most 65536 characters, shared with the pkgcheck section +for key in "${keys[@]}"; do + text=${detail_text[$key]} + title=${detail_title[$key]} + links=${detail_links[$key]:-} + # name the profiles when they did not all print the same, unless every one has a build.log link + if [ -z "$links" ] || [ -n "${detail_unlinked[$key]:-}" ]; then + [ "${detail_profiles[$key]}" = "${atom_profiles[${detail_atom[$key]}]}" ] || title+=" (${detail_profiles[$key]})" + fi + [ -z "$links" ] || title+=", build.log: ${links}" + lines=$(wc -l <<< "$text") + detail=$( + echo + echo "<details><summary>${title}</summary>" + echo + echo '``````' + head -n "$MAX_LINES" <<< "$text" + echo '``````' + if [ "$lines" -gt "$MAX_LINES" ]; then + echo + echo "$(( lines - MAX_LINES )) more lines in the [run](${RUN_URL})." + fi + echo + echo '</details>' + ) + if [ $(( $(wc -c < "$body_file") + ${#detail} )) -gt "$MAX_BYTES" ]; then + printf '\nMore elog in the [run](%s).\n' "$RUN_URL" >> "$body_file" + break + fi + printf '%s\n' "$detail" >> "$body_file" +done + +scripts/upsert-comment-section.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" elog "$body_file" +echo "commented on #${pr}" diff --git a/scripts/pkgcheck-comment.sh b/scripts/pkgcheck-comment.sh index 67df96ec44..b6a3733d1c 100755 --- a/scripts/pkgcheck-comment.sh +++ b/scripts/pkgcheck-comment.sh @@ -8,12 +8,7 @@ findings=$report_dir/findings.json body_file=$(mktemp) trap 'rm -f "$body_file"' EXIT -# commits/{sha}/pulls returns nothing for a fork PR; the artifact is not trusted -pulls=$(gh api "repos/$GITHUB_REPOSITORY/pulls?state=open&per_page=100" --paginate --slurp) -matches=$(jq -r --arg head_sha "$HEAD_SHA" ' - .[][] | select(.head.sha == $head_sha) | .number -' <<< "$pulls") -pr=${matches%%$'\n'*} +pr=$(scripts/pr-at-commit.sh "$GITHUB_REPOSITORY" "$HEAD_SHA") if [ -z "$pr" ]; then echo 'no open pull request at this commit' exit 0 @@ -60,6 +55,16 @@ block() { count=$(wc -l < "$report_dir"/packages) if [ "$count" -eq 0 ]; then + { + echo '## Pull request pkgcheck report' + echo + echo "*Newest commit scanned*: \`$(cat "$report_dir"/commit)\`" + echo '*Status*: :white_check_mark: no packages touched' + } > "$body_file" + scripts/upsert-comment-section.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" pkgcheck "$body_file" + # emerge-on-pr skips a pull request that only touches .github, so drop its report here + : > "$body_file" + scripts/upsert-comment-section.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" elog "$body_file" echo 'no packages touched' exit 0 fi @@ -98,9 +103,7 @@ minor=$(list true style info) block 'New style and info findings' yes "$minor" block 'Existing findings in these packages' yes "$(list false error warning style info)" fi - echo - echo "${MARKER}" } > "$body_file" -scripts/upsert-comment.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" "$body_file" +scripts/upsert-comment-section.sh "$GITHUB_REPOSITORY" "$pr" "$MARKER" pkgcheck "$body_file" echo "commented on #${pr}" diff --git a/scripts/pr-at-commit.sh b/scripts/pr-at-commit.sh new file mode 100755 index 0000000000..bf89a4128b --- /dev/null +++ b/scripts/pr-at-commit.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# usage: pr-at-commit.sh <repository> <sha> +set -euo pipefail + +repository=${1:?repository} +sha=${2:?sha} + +# commits/{sha}/pulls returns nothing for a fork PR, and artifacts are not trusted to name it +pulls=$(gh api "repos/$repository/pulls?state=open&per_page=100" --paginate --slurp) +jq -r --arg sha "$sha" ' + first(.[][] | select(.head.sha == $sha) | .number) // empty +' <<< "$pulls" diff --git a/scripts/upsert-comment-section.sh b/scripts/upsert-comment-section.sh new file mode 100755 index 0000000000..b59b6a92c5 --- /dev/null +++ b/scripts/upsert-comment-section.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# usage: upsert-comment-section.sh <repository> <issue> <marker> <section> <body-file> +# Several workflow runs share one bot comment, each owning one section of it. +# An empty body file removes the section. +set -euo pipefail +SECTIONS=(pkgcheck elog) +ATTEMPTS=4 +PAUSE=10 + +repository=${1:?repository} +issue=${2:?issue} +marker=${3:?marker} +section=${4:?section} +body_file=${5:?body-file} +: "${HEAD_SHA:?}" +case $section in + pkgcheck|elog) ;; + *) echo "unknown section: $section" >&2; exit 1 ;; +esac + +new_body=$(mktemp) +trap 'rm -f "$new_body"' EXIT + +# Runs of the other section and of older pushes write the same comment at the +# same time, so write only while the pull request is at HEAD_SHA, then read it +# back after a pause and write again if another run overwrote this section. +for attempt in $(seq "$ATTEMPTS"); do + head=$(gh api "repos/$repository/pulls/$issue" --jq .head.sha) + if [ "$head" != "$HEAD_SHA" ]; then + echo "the pull request moved on to ${head}" + exit 0 + fi + + comments=$(gh api "repos/$repository/issues/$issue/comments" --paginate --slurp) + # Section text comes from pull request runs; dropping "<!--" keeps it from forging a marker. + plan=$(jq -c --arg marker "$marker" --arg section "$section" --rawfile text "$body_file" ' + def trim: gsub("\r"; "") | ltrimstr("\n") | rtrimstr("\n"); + def between($n): + split("<!-- \($n):begin -->") + | if length > 1 then .[1] | split("<!-- \($n):end -->")[0] | trim else null end; + + [.[][] | select(.user.type == "Bot" and (.body | contains($marker)))] as $found + | ($found[0].body // "") as $old + | ($text | gsub("<!--"; "") | trim | if . == "" then null else . end) as $want + | [$ARGS.positional[] as $n + | (if $n == $section then $want else $old | between($n) end) + | select(. != null) + | "<!-- \($n):begin -->\n\(.)\n<!-- \($n):end -->" + ] as $sections + | { + id: $found[0].id, + duplicates: [$found[1:][].id], + done: (($old | between($section)) == $want), + body: (($sections | join("\n\n")) + "\n\n" + $marker) + } + ' --args "${SECTIONS[@]}" <<< "$comments") + + # two runs that both found no comment each create one; keep the oldest + for id in $(jq -r '.duplicates[]' <<< "$plan"); do + gh api -X DELETE "repos/$repository/issues/comments/$id" >/dev/null + done + if [ "$(jq -r .done <<< "$plan")" = true ]; then + echo "the ${section} section is up to date" + exit 0 + fi + if [ "$attempt" -eq "$ATTEMPTS" ]; then + echo "the ${section} section kept being overwritten" >&2 + exit 1 + fi + + jq -r .body <<< "$plan" > "$new_body" + comment_id=$(jq -r '.id // empty' <<< "$plan") + if [ -n "$comment_id" ]; then + gh api -X PATCH "repos/$repository/issues/comments/$comment_id" -F "body=@$new_body" >/dev/null + else + gh api "repos/$repository/issues/$issue/comments" -F "body=@$new_body" >/dev/null + fi + sleep "$PAUSE" +done