Files
dress-pr/.gitea/workflows/auto_fix.yml
T
xhgitandClaude Code cf17c9ea42 Initial commit: 小南娘 - 面向可爱的蓝孩子的 git 学习实践项目
仿 Dress 的照片投稿仓库, 适配自建 Gitea 平台 git.xhmcl.com:
- README / GUIDE (PR 教程) / CONTRIBUTING / Q&A / EXIF / PARTIAL_CLONE (中英双语)
- A-Z + # 首字母目录结构
- .gitea: PR 模板、维护者名单、7 个纯 bash + API 的 Actions 工作流 (可选功能)

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-07 17:17:27 +08:00

288 lines
13 KiB
YAML

# Auto-fix Image Files
#
# PR 评论 /auto-fix 触发 (仅维护者或 PR 作者). (纯 shell + 平台 API)
# 对变更图片: 去除全部 EXIF, 循环压缩至 <= 1 MiB, 再 push 回 PR 分支.
# push 后由 check_file_size / check_exif 的 pull_request_target 自然重跑.
#
# 前置条件:
# - 平台启用 Gitea Actions 并注册 ubuntu runner (需要 apt 安装工具)
# - 仓库「设置 → Actions → Secrets」中配置:
# BOT_USER 有 Fork 仓库写权限的账号名
# BOT_TOKEN 该账号的访问令牌 (本平台无 SSH, 仅 HTTP push)
# 未配置时工作流会评论说明并退出, 不进行修复.
name: Auto-fix Image Files
on:
issue_comment:
types: [created]
jobs:
auto-fix:
name: Auto-fix Images (EXIF & Size)
if: >
github.event.issue.pull_request &&
startsWith(github.event.comment.body, '/auto-fix')
runs-on: ubuntu-latest
steps:
- name: Install dependencies
run: |
sudo apt-get install -y --no-install-recommends libimage-exiftool-perl imagemagick jpegoptim optipng pngquant jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends libimage-exiftool-perl imagemagick jpegoptim optipng pngquant jq)
- name: Check permission (PR author or write access)
id: perm
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.issue.number }}
COMMENT_USER: ${{ github.event.comment.user.login }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() { curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"; }
PR_AUTHOR=$(api "$API/repos/$OWNER/$NAME/pulls/$PR_NUM" | jq -r '.user.login // ""')
if [ "$COMMENT_USER" = "$PR_AUTHOR" ] && [ -n "$PR_AUTHOR" ]; then
echo "Commenter is the PR author, allowed."
exit 0
fi
perm=$(api "$API/repos/$OWNER/$NAME/collaborators/$COMMENT_USER/permission" 2>/dev/null | jq -r '.permission // "none"' || echo none)
case "$perm" in
admin|write|owner) echo "Commenter has $perm permission, allowed." ;;
*) echo "Commenter $COMMENT_USER has no write permission."; exit 1 ;;
esac
- name: Acknowledge command and start processing
id: init
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.issue.number }}
COMMENT_ID: ${{ github.event.comment.id }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() { curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"; }
# rocket 反应
api -X POST -d '{"content":"rocket"}' "$API/repos/$OWNER/$NAME/issues/comments/$COMMENT_ID/reactions" || true
# 处理中评论
ACK=$(api -X POST -d '{"body":"自动修复工作中... (Auto-fix initiated! Processing images...)"}' \
"$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments")
ACK_ID=$(echo "$ACK" | jq -r '.id')
echo "ack_comment_id=$ACK_ID" >> "$GITHUB_OUTPUT"
- name: Fetch PR branch and process images
id: process
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
SERVER: ${{ gitea.server_url || 'https://git.xhmcl.com' }}
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.issue.number }}
HEAD_OWNER: ${{ github.event.pull_request.head.repo.owner.login }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.name }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
BOT_USER: ${{ secrets.BOT_USER }}
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() { curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"; }
HOST=$(printf '%s' "$SERVER" | sed -E 's#^https?://##')
IMAGE_EXT_RE='\.(jpe?g|jfif|png|webp|tiff?|hei[cf]|avif|gif|bmp)$'
MAX_SIZE=$((1024 * 1024))
fail_msg() {
local msg="$1"
BODY_JSON=$(jq -n --arg b "$msg" '{"body": $b}')
api -X POST -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments"
exit 1
}
if [ -z "$BOT_USER" ] || [ -z "$BOT_TOKEN" ]; then
fail_msg "**自动修复未执行 (Auto-fix not run).**
未配置仓库 Secrets \`BOT_USER\` / \`BOT_TOKEN\` (需要一个有 Fork 仓库写权限的账号令牌, 本平台仅支持 HTTP push).
请维护者在 设置 → Actions → Secrets 中配置, 或在本地自行处理后重新 push.
(Missing repo secrets BOT_USER / BOT_TOKEN; a bot account with write access to the fork is required. Please configure them, or fix the images manually and push again.)"
fi
WORK="$RUNNER_TEMP/dress-pr-work"
mkdir -p "$WORK"
CLONE_URL="https://${BOT_USER}:${BOT_TOKEN}@${HOST}/${HEAD_OWNER}/${HEAD_REPO}.git"
echo "Cloning head repo $HEAD_OWNER/$HEAD_REPO branch $HEAD_REF ..."
git clone --depth 1 --branch "$HEAD_REF" "$CLONE_URL" "$WORK/repo" || \
fail_msg "**自动修复失败 (Auto-fix failed).** 无法克隆 PR 分支, 请检查 \`BOT_TOKEN\` 是否有效且有该 Fork 仓库的写权限. (Cannot clone the PR branch; please check that BOT_TOKEN is valid and has write access to the fork.)"
cd "$WORK/repo"
git config user.name "dress-bot"
git config user.email "dress-bot@users.noreply.git.xhmcl.com"
# 变更图片列表 (与 size/exif 检查同一份 diff)
FILES_TMP=$(mktemp)
page=1
while :; do
resp=$(api "$API/repos/$OWNER/$NAME/pulls/$PR_NUM/files?limit=50&page=$page")
n=$(echo "$resp" | jq 'if type=="array" then length else 0 end')
echo "$resp" | jq -r '.[] | "\(.status // "unknown")\t\(.filename // "")"' >> "$FILES_TMP" || true
[ "$n" -lt 50 ] && break
page=$((page + 1))
done
awk -F'\t' '$1 ~ /^(added|modified|renamed|copied)$/ {print $2}' "$FILES_TMP" \
| grep -iE "$IMAGE_EXT_RE" > "$WORK/changed_images.txt" || true
if [ ! -s "$WORK/changed_images.txt" ]; then
fail_msg "**自动修复完成 (Auto-fix: nothing to do).** 该 PR 没有图片变更. (No changed images in this PR.)"
fi
echo "Changed images to process:"; cat "$WORK/changed_images.txt"
BASE_SHA=$(git rev-parse HEAD)
# Phase 1: 清除全部 EXIF
exif_changed=0
while IFS= read -r file; do
[ -z "$file" ] && continue
if [ -f "$file" ]; then
count=$(exiftool -EXIF:all -S -q -- "$file" 2>/dev/null | wc -l)
count=${count// /}
if [ "${count:-0}" -gt 0 ]; then
echo "Removing EXIF: $file"
exiftool -all= -overwrite_original "$file"
git add -- "$file"
exif_changed=1
fi
fi
done < "$WORK/changed_images.txt"
if [ "$exif_changed" -eq 1 ]; then
git commit -m "chore: auto-remove EXIF data from images" || true
fi
# Phase 2: 压缩超限图片
failed_files=()
size_changed=0
file_size() { stat -c%s "$1" 2>/dev/null || echo 0; }
while IFS= read -r file; do
[ -z "$file" ] && continue
[ -f "$file" ] || continue
size=$(file_size "$file")
[ "$size" -le "$MAX_SIZE" ] && continue
echo "Compressing: $file ($size bytes)"
ext_lower=$(echo "${file##*.}" | tr '[:upper:]' '[:lower:]')
attempt=0
while [ "$(file_size "$file")" -gt "$MAX_SIZE" ] && [ "$attempt" -lt 20 ]; do
attempt=$((attempt + 1))
echo " attempt $attempt / 20"
case "$ext_lower" in
jpg|jpeg|jfif)
if [ "$attempt" -eq 1 ]; then
jpegoptim --size=990k "$file" || true
elif [ "$attempt" -le 8 ]; then
q=$((85 - attempt * 10)); [ "$q" -lt 25 ] && q=25
mogrify -quality "$q" "$file"
else
mogrify -resize 90% -quality 40 "$file"
fi
;;
png)
if [ "$attempt" -le 5 ]; then
pngquant --quality=40-70 --ext .png --force "$file" || optipng -o2 "$file" || true
else
mogrify -resize 90% "$file"
fi
;;
*)
if [ "$attempt" -le 5 ]; then
q=$((80 - attempt * 10)); [ "$q" -lt 25 ] && q=25
mogrify -quality "$q" "$file"
else
mogrify -resize 90% -quality 40 "$file"
fi
;;
esac
done
new_size=$(file_size "$file")
if [ "$new_size" -gt "$MAX_SIZE" ]; then
echo "Failed to compress $file below 1 MiB (current: $new_size bytes)"
failed_files+=("$file")
else
echo "OK: $file -> $new_size bytes"
git add -- "$file"
size_changed=1
fi
done < "$WORK/changed_images.txt"
if [ "${#failed_files[@]}" -gt 0 ]; then
# 回滚本地修改, 不 push 半成品
git reset --hard "$BASE_SHA"
FAILED_LIST=$(printf '%s\n' "${failed_files[@]}" | sed 's/^/- /')
echo "failed_list=$FAILED_LIST" >> "$GITHUB_OUTPUT"
echo "failed=true" >> "$GITHUB_OUTPUT"
exit 2
fi
if [ "$size_changed" -eq 1 ]; then
git commit -m "chore: auto-compress oversized images" || true
fi
# Phase 3: push 回 PR 分支
git push origin "HEAD:${HEAD_REF}"
echo "pushed=true" >> "$GITHUB_OUTPUT"
- name: Report Completion
if: always()
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
SERVER: ${{ gitea.server_url || 'https://git.xhmcl.com' }}
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.issue.number }}
ACK_ID: ${{ steps.init.outputs.ack_comment_id }}
PROCESS_OUTCOME: ${{ steps.process.outcome }}
FAILED_LIST: ${{ steps.process.outputs.failed_list }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() { curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"; }
if [ "$PROCESS_OUTCOME" = "failure" ] && [ -n "$FAILED_LIST" ]; then
MSG="**自动修复未完全成功 (Auto-fix failed to compress some files).**
经多次压缩仍无法将以下文件压至 1 MiB 以内 (已回滚, 未推送):
(Still over 1 MiB after repeated compression; changes were reverted and not pushed:)
$FAILED_LIST
**如何手动修复 (How to fix manually):**
请在本地缩小分辨率或改用更高压缩率格式后再次提交.
(Please scale down resolution or use a more efficient format, then push again.)"
elif [ "$PROCESS_OUTCOME" = "success" ]; then
MSG="**自动修复成功 (Auto-fix completed successfully)!**
已去除全部 EXIF (如有) 并压缩超限图片 (如有). push 后将由 size / EXIF 检查自动重跑.
(All EXIF stripped if present; oversized images compressed if needed. size / EXIF checks will re-run after the push.)"
else
MSG="**自动修复失败 (Auto-fix failed).**\n请查看 [Actions Log]($SERVER/$OWNER/$NAME/actions/runs/${GITHUB_RUN_ID:-unknown}) 获取详情。(Please check the Actions Log for details.)"
fi
if [ -n "$ACK_ID" ] && [ "$ACK_ID" != "0" ]; then
BODY_JSON=$(jq -n --arg b "$MSG" '{"body": $b}')
api -X PATCH -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/comments/$ACK_ID" || true
else
BODY_JSON=$(jq -n --arg b "$MSG" '{"body": $b}')
api -X POST -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments" || true
fi