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>
This commit is contained in:
xhgitandClaude Code committed 2026-11-07 17:17:27 +08:00
commit cf17c9ea42
51 files changed
+2450

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# 维护者名单 / Maintainers
#
# 想要在 PR 多次未通过内容检查时收到通知的维护者, 把自己加进这个列表即可.
# 不想收通知的可以不添加 (仓库订阅仍会收到普通提醒).
# Add yourself if you want to be notified when a PR keeps failing the content check.
#
# 此文件由 .gitea/workflows/check_pr_content.yml 读取 (需平台启用 Gitea Actions).
maintainers:
- xhgit # ← 请替换为实际的维护者用户名, 每行一个
+42
View File
@@ -0,0 +1,42 @@
<!-- pr-type: images -->
<!-- 请勿删除以上 pr-type 行。非照片 PR 请把 images 改为 ci_wf / docs / others,并按模板底部说明勾选清单 -->
<details>
<summary>第一次提交?点我查看新手说明 / First time? Click for guide</summary>
请先阅读 [新手指南](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/GUIDE.md)。
也可参考 [已合并的 PR](https://git.xhmcl.com/xhgit/dress-pr/pulls?state=closed)。
Please read the [Beginner Guide](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/GUIDE.md).
See [merged PRs](https://git.xhmcl.com/xhgit/dress-pr/pulls?state=closed) for examples.
</details>
**PR 类型**:图片提交 / Photo submission
**简单描述**(可选):
### 自查清单 / Checklist
请自行确认并勾选。Please check each item yourself.
- [ ] 图片已压缩至 1 MiB 以内 / Images are under 1 MiB(见 [CONTRIBUTING.md](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/CONTRIBUTING.md))
- [ ] 已移除高敏感 EXIF(GPS/地址/联系方式)/ High-sensitivity EXIF removed([字段说明](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/EXIF.md) · [清理方法](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/CONTRIBUTING.md))
- [ ] 文件在对应首字母目录下 `A-Z/#/昵称/` / Folder under matching `A-Z/#`(见 [GUIDE.md](https://git.xhmcl.com/xhgit/dress-pr/src/branch/main/GUIDE.md);无需强制账号 ID)
- 正确: `M/moe/photo.jpg` 或 `#/233/photo.jpg`
- 错误: `moe/photo.jpg`(缺少首字母目录)
- [ ] 图片为本人原创,未盗用他人作品 / Images are original and not stolen from others
- [ ] 已阅读 [新手指南](GUIDE.md),并按其中流程提交 / Have read and followed the [Beginner Guide](GUIDE.md)
---
**本次不是交照片?** / Not a photo PR?
请把最上方的 `pr-type` 改为对应类型,并替换上方清单为对应自查项(同样使用 `- [ ]` 格式并全部勾选):
- `ci_wf`:CI / 工作流修改 → 自查:改动均在 `.gitea/` 下;已在 fork 上确认 workflow 行为符合预期
- `docs`:文档修改 → 自查:本次以文档/说明为主,不含照片;链接与路径已核对
- `others`:其他 → 自查:已说明为何不属于「图片提交 / CI / 文档」
> 平台说明:Gitea 暂不支持像 GitHub 那样的多模板切换,本仓库统一使用这一个模板,由顶部的 `pr-type` 标记区分 PR 类型(自动化检查会读取它)。
+287
View File
@@ -0,0 +1,287 @@
# 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
+146
View File
@@ -0,0 +1,146 @@
# Check Image EXIF Data
#
# 仅在 PR 为图片提交时检查变更图片是否含高敏感 EXIF (GPS / 地址 / 联系方式).
# 普通摄影参数 (光圈, 快门等) 不拦截. (纯 shell + 平台 API)
#
# 要求:
# - 平台启用 Gitea Actions 并注册 ubuntu runner (需要 apt 安装 exiftool)
# - 若 Gitea 版本不支持 pull_request_target, 请改为 pull_request
name: Check Image EXIF Data
on:
pull_request_target:
types: [opened, synchronize, reopened]
concurrency:
group: exif-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check-exif:
runs-on: ubuntu-latest
steps:
- name: Install exiftool and jq
run: |
sudo apt-get install -y --no-install-recommends libimage-exiftool-perl jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends libimage-exiftool-perl jq)
- name: Check EXIF in changed images
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.pull_request.number }}
HEAD_OWNER: ${{ github.event.pull_request.head.repo.owner.login }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.name }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
IMAGE_EXT_RE='\.(jpe?g|jfif|png|webp|tiff?|hei[cf]|avif|gif|bmp)$'
ACTIVE_RE='^(added|modified|renamed|copied)$'
# GPS / IPTC address / XMP location & contact
HIGH_SENS_ARGS=(
'-GPS:GPSLatitude' '-GPS:GPSLongitude' '-GPS:GPSAltitude'
'-GPS:GPSDateStamp' '-GPS:GPSTimeStamp'
'-GPS:GPSSpeed' '-GPS:GPSTrack' '-GPS:GPSImgDirection'
'-IPTC:City' '-IPTC:Country-PrimaryLocationName'
'-IPTC:Sub-location' '-IPTC:Province-State'
'-XMP-photoshop:City' '-XMP-photoshop:Country' '-XMP-photoshop:State'
'-XMP-iptcCore:CreatorWorkEmail' '-XMP-iptcCore:CreatorWorkTelephone'
'-XMP-iptcCore:CreatorCity' '-XMP-iptcCore:CreatorCountry'
'-XMP-iptcCore:CreatorPostalCode'
)
api() {
curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"
}
PR_BODY=$(api "$API/repos/$OWNER/$NAME/pulls/$PR_NUM" | jq -r '.body // ""')
PR_TYPE=$(printf '%s\n' "$PR_BODY" | grep -oE 'pr-type:[[:space:]]*[A-Za-z_0-9]+' | head -1 | cut -d: -f2 | tr -d '[:space:]')
PR_TYPE=${PR_TYPE:-images}
if [ "$PR_TYPE" != "images" ]; then
echo "pr-type is \"$PR_TYPE\", skip EXIF check."
exit 0
fi
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
IMAGES=$(awk -F'\t' -v re="$ACTIVE_RE" '$1 ~ re {print $2}' "$FILES_TMP" | grep -iE "$IMAGE_EXT_RE" || true)
if [ -z "$IMAGES" ]; then
echo "No changed images found, skip EXIF check."
exit 0
fi
echo "Checking $(printf '%s\n' "$IMAGES" | grep -c .) image(s) for high-sensitivity EXIF."
encode_path() {
printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/#/%23/g' -e 's/?/%3F/g' -e 's/ /%20/g'
}
TMP_DIR=$(mktemp -d)
EXIF_FILES=()
while IFS= read -r file; do
[ -z "$file" ] && continue
enc=$(encode_path "$file")
content_json=$(api "$API/repos/$HEAD_OWNER/$HEAD_REPO/contents/$enc?ref=$HEAD_SHA" 2>/dev/null || true)
b64=$(echo "$content_json" | jq -r 'if type=="object" and .content then .content else empty end' 2>/dev/null || true)
if [ -z "$b64" ]; then
echo "Warning: cannot fetch $file, skip."
continue
fi
tmp_file="$TMP_DIR/$(printf '%s' "$file" | tr '/\\' '__')"
printf '%s' "$b64" | base64 -d > "$tmp_file" 2>/dev/null || { echo "Warning: decode failed $file, skip."; continue; }
# Drop empty/undef/all-zero placeholders (e.g. GPS IFD with no coords).
count=$(exiftool "${HIGH_SENS_ARGS[@]}" -S -q -- "$tmp_file" 2>/dev/null \
| grep -Ev ': *(undef|00:00:00)?$' | wc -l)
count=${count// /}
if [ "${count:-0}" -gt 0 ]; then
EXIF_FILES+=("$file")
echo "Sensitive EXIF found: $file ($count tags)"
fi
rm -f "$tmp_file"
done <<< "$IMAGES"
rm -rf "$TMP_DIR"
if [ "${#EXIF_FILES[@]}" -gt 0 ]; then
MSG="我们检测到以下文件包含**高敏感 EXIF 信息**(如 GPS 坐标, 地址或联系方式), 请移除后再次提交:
We detected **high-sensitivity EXIF data** (e.g. GPS coordinates, address, or contact fields) in the following files. Please remove them and resubmit:
$(printf '%s\n' "${EXIF_FILES[@]}" | sed 's/^/- /')
**仅高敏感字段 (GPS / 地址 / 联系方式) 需要移除, 普通摄影参数 (光圈, 快门等) 无需处理.**
**Only high-sensitivity fields (GPS / address / contact info) need to be removed. Regular photography parameters (aperture, shutter speed, etc.) are fine to keep.**
[EXIF 说明 / EXIF Guide](https://git.xhmcl.com/$OWNER/$NAME/src/branch/main/EXIF.md) · [CONTRIBUTING.md](https://git.xhmcl.com/$OWNER/$NAME/src/branch/main/CONTRIBUTING.md)
---
温馨提示: 您可以直接使用 \`/auto-fix\` 命令来自动修复这些文件.
Warm reminder: You can use the \`/auto-fix\` command to automatically fix these files.
该命令会将图片压缩到 1 MiB 内, 并且去除**所有的 EXIF**信息, 若您不希望文件被改动, 请自行处理后重新提交 PR
This command will compress images to under 1 MiB and strip all EXIF metadata.
If you do not want your files modified, please fix them yourself and push again."
BODY_JSON=$(jq -n --arg b "$MSG" '{"body": $b}')
api -X POST -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments" \
|| echo "Warning: cannot comment (check bot account permission)."
echo "High-sensitivity EXIF data detected."
exit 1
fi
echo "No high-sensitivity EXIF data found."
+115
View File
@@ -0,0 +1,115 @@
# Check File Size
#
# 仅在 PR 为图片提交时检查变更图片是否均 <= 1 MiB (纯 shell + 平台 API).
#
# 检查 pr-type (PR body 中的 <!-- pr-type: xxx -->):
# - images (或缺省无标签) -> 执行检查
# - ci_wf / docs / others -> 跳过, 不 fail
# 无变更图片时跳过, 不 fail (无图提醒交给 check_pr_content)
#
# 要求:
# - 平台启用 Gitea Actions 并注册 ubuntu runner
# - 若 Gitea 版本不支持 pull_request_target, 请改为 pull_request
name: Check File Size
on:
pull_request_target:
types: [opened, synchronize, reopened]
jobs:
check-size:
runs-on: ubuntu-latest
steps:
- name: Install jq
run: |
command -v jq && exit 0
sudo apt-get install -y --no-install-recommends jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends jq)
- name: Check file sizes
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.pull_request.number }}
HEAD_OWNER: ${{ github.event.pull_request.head.repo.owner.login }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.name }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
MAX_SIZE=$((1024 * 1024)) # 1 MiB
IMAGE_EXT_RE='\.(jpe?g|jfif|png|webp|tiff?|hei[cf]|avif|gif|bmp)$'
ACTIVE_RE='^(added|modified|renamed|copied)$'
api() {
curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"
}
PR_BODY=$(api "$API/repos/$OWNER/$NAME/pulls/$PR_NUM" | jq -r '.body // ""')
PR_TYPE=$(printf '%s\n' "$PR_BODY" | grep -oE 'pr-type:[[:space:]]*[A-Za-z_0-9]+' | head -1 | cut -d: -f2 | tr -d '[:space:]')
PR_TYPE=${PR_TYPE:-images}
if [ "$PR_TYPE" != "images" ]; then
echo "pr-type is \"$PR_TYPE\", skip file size check."
exit 0
fi
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
IMAGES=$(awk -F'\t' -v re="$ACTIVE_RE" '$1 ~ re {print $2}' "$FILES_TMP" | grep -iE "$IMAGE_EXT_RE" || true)
if [ -z "$IMAGES" ]; then
echo "No changed images found, skip file size check."
exit 0
fi
encode_path() {
# '#' 必须转义, 否则会被当作 URL fragment
printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/#/%23/g' -e 's/?/%3F/g' -e 's/ /%20/g'
}
OVERSIZED=()
while IFS= read -r file; do
[ -z "$file" ] && continue
enc=$(encode_path "$file")
content_json=$(api "$API/repos/$HEAD_OWNER/$HEAD_REPO/contents/$enc?ref=$HEAD_SHA" 2>/dev/null || true)
size=$(echo "$content_json" | jq -r 'if type=="object" and .size then .size else empty end' 2>/dev/null || true)
if [ -z "$size" ]; then
echo "Warning: cannot read $file (maybe a directory or deleted), skip."
continue
fi
if [ "$size" -gt "$MAX_SIZE" ]; then
OVERSIZED+=("- $file ($size bytes)")
fi
done <<< "$IMAGES"
if [ "${#OVERSIZED[@]}" -gt 0 ]; then
MSG="我们注意到以下文件的大小超过了 1 MiB, 请在压缩后再次提交 Pull Request:
We have noted that the following files exceed 1 MiB in size. Please resubmit your pull request after compressing them:
$(printf '%s\n' "${OVERSIZED[@]}")
---
温馨提示: 您可以直接使用 \`/auto-fix\` 命令来自动修复这些文件。
Warm reminder: You can use the \`/auto-fix\` command to automatically fix these files.
该命令会将图片压缩到 1 MiB 内, 并且去除**所有的 EXIF**信息, 若您不希望文件被改动, 请自行处理后重新提交 PR
This command will compress images to under 1 MiB and strip all EXIF metadata.
If you do not want your files modified, please fix them yourself and push again."
BODY_JSON=$(jq -n --arg b "$MSG" '{"body": $b}')
api -X POST -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments"
echo "File size check failed."
exit 1
fi
echo "All changed images are under 1 MiB."
+216
View File
@@ -0,0 +1,216 @@
# Check PR Content
#
# 综合检查 PR 描述与变更内容 (纯 shell + 平台 API, 不依赖第三方 action).
#
# 检查 pr-type (PR body 中的 <!-- pr-type: xxx -->):
# - 缺省无标签 -> 当作 images
# - 所有类型 -> 自查清单须存在且全部勾选
# - images -> 须有图片变更; 目录须符合 A-Z/#/昵称/
# - ci_wf -> 变更须均在 .gitea/ 下
# - docs/others -> 仅清单检查
#
# 任一项不通过: 评论 + fail
# 评论计数: 每条 check 失败评论带 <!-- check-pr-content --> marker
# 计数达到 3 后不再发 check 评论, 改为 @ 维护者 (.gitea/MAINTAINERS.yml) 通知, 带 <!-- maintainer-notify --> marker
# 通知只发一次; 之后完全静默 (检查照跑, 不发任何评论)
#
# 要求:
# - 平台启用 Gitea Actions 并注册 ubuntu runner
# - 若 Gitea 版本不支持 pull_request_target, 请改为 pull_request
name: Check PR Content
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
concurrency:
group: pr-content-${{ github.event.pull_request.number }}
cancel-in-progress: false
jobs:
check-content:
runs-on: ubuntu-latest
steps:
- name: Install jq
run: |
command -v jq && exit 0
sudo apt-get install -y --no-install-recommends jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends jq)
- name: Check PR content
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() {
curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"
}
IMAGE_EXT_RE='\.(jpe?g|jfif|png|webp|tiff?|hei[cf]|avif|gif|bmp)$'
ACTIVE_RE='^(added|modified|renamed|copied)$'
CHECK_COMMENT_MARKER='<!-- check-pr-content -->'
NOTIFY_MARKER='<!-- maintainer-notify -->'
MAX_CHECK_COMMENTS=3
# 1. 读取 PR body (避免在 yaml 中直接注入多行 payload)
PR_BODY=$(api "$API/repos/$OWNER/$NAME/pulls/$PR_NUM" | jq -r '.body // ""')
# 2. 解析 pr-type
PR_TYPE=$(printf '%s\n' "$PR_BODY" | grep -oE 'pr-type:[[:space:]]*[A-Za-z_0-9]+' | head -1 | cut -d: -f2 | tr -d '[:space:]')
if [ -z "$PR_TYPE" ]; then
PR_TYPE_MISSING=1
PR_TYPE=images
else
PR_TYPE_MISSING=0
fi
# 3. 自查清单
CHECK_TOTAL=$(printf '%s\n' "$PR_BODY" | grep -cE '^[[:space:]]*-[[:space:]]*\[[ xX]\]' || true)
UNCHECKED=$(printf '%s\n' "$PR_BODY" | grep -E '^[[:space:]]*-[[:space:]]*\[[[:space:]]\][[:space:]]*(.*)$' | sed -E 's/^[[:space:]]*-[[:space:]]*\[[[:space:]]\][[:space:]]*/- /' || true)
# 4. 变更文件列表 (分页)
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
ACTIVE_FILES=$(awk -F'\t' -v re="$ACTIVE_RE" '$1 ~ re {print $2}' "$FILES_TMP")
expected_bucket() {
first=$(printf '%s' "$1" | cut -c1 | tr '[:lower:]' '[:upper:]')
case "$first" in
[A-Z]) echo "$first" ;;
*) echo '#' ;;
esac
}
SECTIONS=()
FAILED=0
# 5. 清单检查 (所有 pr-type)
if [ "$CHECK_TOTAL" -eq 0 ]; then
FAILED=1
SECTIONS+=("我们未在 PR 描述中找到自查清单, 请使用仓库提供的 Pull Request 模板, 勿删除清单项:\nWe could not find a checklist in the PR body. Please use the repository Pull Request template and do not remove the checklist items.")
elif [ -n "$UNCHECKED" ]; then
FAILED=1
SECTIONS+=("我们注意到 PR 模板中的自查清单尚未全部勾选, 请确认并勾选后再次提交:\nWe noticed that the PR template checklist is incomplete. Please check all items and update the PR:\n\n$(printf '%s\n' "$UNCHECKED")")
fi
# 6. 按 pr-type 检查
case "$PR_TYPE" in
images)
IMAGES=$(printf '%s\n' "$ACTIVE_FILES" | grep -iE "$IMAGE_EXT_RE" || true)
if [ -z "$IMAGES" ]; then
FAILED=1
if [ "$PR_TYPE_MISSING" -eq 1 ]; then
SECTIONS+=("PR 描述中未找到 pr-type 标签, 已按图片提交 (images) 处理; 但未检测到任何图片文件变更.\nNo pr-type tag was found in the PR body, so it was treated as an image submission (images); no changed image files were detected.\n\n若本次不是提交照片, 请关闭后把 pr-type 改为 ci_wf / docs / others.\nIf this PR is not for photos, please close it and set pr-type to ci_wf / docs / others.\n\n若确为图片提交, 请将图片放入对应目录后再 push.\nIf this is a photo submission, please add images under the proper folders and push again.")
else
SECTIONS+=("当前 PR 类型为图片提交 (pr-type: images), 但未检测到任何图片文件变更.\nThis PR is typed as an image submission (pr-type: images), but no changed image files were detected.\n\n若本次不是提交照片, 请关闭后把 pr-type 改为 ci_wf / docs / others.\nIf this PR is not for photos, please close it and set pr-type to ci_wf / docs / others.\n\n若确为图片提交, 请将图片放入对应目录后再 push.\nIf this is a photo submission, please add images under the proper folders and push again.")
fi
fi
# 目录归类
INVALID=()
while IFS= read -r file; do
[ -z "$file" ] && continue
parts0=$(printf '%s' "$file" | cut -d/ -f1)
parts1=$(printf '%s' "$file" | cut -d/ -f2)
parts_count=$(printf '%s' "$file" | awk -F/ '{print NF}')
case "$parts0" in
.gitea|.github|en-US) continue ;;
esac
if [ "$parts_count" -eq 1 ]; then
case "$parts0" in
.gitattributes|.gitignore|CONTRIBUTING.md|EXIF.md|GUIDE.md|LICENSE|README.md|Q\&A.md|PARTIAL_CLONE.md) continue ;;
esac
INVALID+=("- ${file}(文件应位于 A-Z/# 下的个人文件夹内)")
continue
fi
if [ "$parts_count" -lt 3 ]; then
INVALID+=("- ${file}(文件应位于 A-Z/# 下的个人文件夹内)")
continue
fi
expected=$(expected_bucket "$parts1")
if [ "$parts0" != "$expected" ]; then
INVALID+=("- ${file}(应位于 ${expected}/${parts1}/...)")
fi
done <<< "$ACTIVE_FILES"
if [ "${#INVALID[@]}" -gt 0 ]; then
FAILED=1
SECTIONS+=("我们注意到以下文件的目录归类不正确, 请调整路径后再次推送:\nWe noticed that the following files are not under the correct A-Z/# folder. Please fix the paths and push again:\n\n$(printf '%s\n' "${INVALID[@]}")\n\n正确示例 / Examples:\n- M/moe/photo.jpg\n- #/233/photo.jpg")
fi
;;
ci_wf)
OUTSIDE=$(printf '%s\n' "$ACTIVE_FILES" | grep -vE '^(\.gitea/|$)' || true)
if [ -n "$OUTSIDE" ]; then
FAILED=1
SECTIONS+=("当前 PR 类型为 CI / 工作流修改 (pr-type: ci_wf), 但检测到 \`.gitea/\` 目录之外的文件变更:\nThis PR is typed as a CI / workflow change (pr-type: ci_wf), but files outside \`.gitea/\` were changed:\n\n$(printf '%s\n' "$OUTSIDE" | sed 's/^/- /')\n\n请将非 CI 改动拆到其他 PR, 或把 pr-type 改为对应类型 (images / docs / others).\nPlease split non-CI changes into another PR, or switch pr-type to the matching type (images / docs / others).")
fi
;;
docs|others)
echo "pr-type is \"$PR_TYPE\", only checklist rules apply."
;;
*)
FAILED=1
SECTIONS+=("未识别的 pr-type: \"$PR_TYPE\". 请使用模板中的 images / ci_wf / docs / others.\nUnrecognized pr-type: \"$PR_TYPE\". Please use images / ci_wf / docs / others from the template.")
;;
esac
# 7. 评论策略: 3 条 check 评论 → 维护者通知(一次) → 静默
if [ "${#SECTIONS[@]}" -gt 0 ]; then
COMMENT_PAGE=1
COMMENTS_TMP=$(mktemp)
while :; do
resp=$(api "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments?limit=50&page=$COMMENT_PAGE")
n=$(echo "$resp" | jq 'if type=="array" then length else 0 end')
echo "$resp" | jq -r '.[] | .body // ""' >> "$COMMENTS_TMP" || true
[ "$n" -lt 50 ] && break
COMMENT_PAGE=$((COMMENT_PAGE + 1))
done
CHECK_COUNT=$(grep -cF "$CHECK_COMMENT_MARKER" "$COMMENTS_TMP" || true)
NOTIFIED=$(grep -cF "$NOTIFY_MARKER" "$COMMENTS_TMP" || true)
BODY_MSG=$(printf '%s\n\n---\n\n' "${SECTIONS[@]}")
BODY_MSG=${BODY_MSG%$'\n\n---\n\n'}
if [ "$NOTIFIED" -gt 0 ]; then
echo "Maintainer already notified. Silent mode: no further comments."
elif [ "$CHECK_COUNT" -lt "$MAX_CHECK_COMMENTS" ]; then
COMMENT_JSON=$(jq -n --arg b "${BODY_MSG}\n\n${CHECK_COMMENT_MARKER}" '{"body": $b}')
api -X POST -d "$COMMENT_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments"
else
# 读取维护者名单
MAINTAINERS=""
MAINT_JSON=$(api "$API/repos/$OWNER/$NAME/contents/.gitea/MAINTAINERS.yml" || true)
if [ -n "$MAINT_JSON" ]; then
MAINTAINERS=$(echo "$MAINT_JSON" | jq -r '.content // ""' | base64 -d 2>/dev/null \
| grep -oE '^[[:space:]]*-[[:space:]]*@?[A-Za-z0-9-]+[[:space:]]*$' \
| sed -E 's/^[[:space:]]*-[[:space:]]*@?//; s/[[:space:]]*$//' \
| sed 's/^/@/' | tr '\n' ' ')
fi
if [ -z "$MAINTAINERS" ]; then
MAINTAINERS='(MAINTAINERS.yml 中暂无维护者)'
fi
NOTIFY_JSON=$(jq -n --arg b "该 PR 已连续多次未通过内容检查, 请维护者人工处理:\nThis PR has repeatedly failed the content check. Please have a maintainer review it manually:\n\n${MAINTAINERS}\n\n在维护者处理前, 本检查将不再自动评论.\nThis check will stay silent until a maintainer takes over.\n\n${NOTIFY_MARKER}" '{"body": $b}')
api -X POST -d "$NOTIFY_JSON" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments"
fi
fi
if [ "$FAILED" -ne 0 ]; then
echo "PR content check failed."
exit 1
fi
echo "PR content check passed."
+77
View File
@@ -0,0 +1,77 @@
# fast-forward for PR
#
# 维护者或写权限用户回复含 /fast-forward 的评论后, 调用平台 API 以变基 (rebase)
# 方式合并 PR, 保留原始提交与签名. 合并失败时评论说明原因.
# (纯 shell + 平台 API, 不依赖第三方 action)
#
# 要求: 平台启用 Gitea Actions 并注册 ubuntu runner.
name: fast-forward for PR
on:
issue_comment:
types: [created, edited]
pull_request_review_comment:
types: [created, edited]
jobs:
fast-forward:
if: >
contains(github.event.comment.body, '/fast-forward') &&
(github.event.issue.pull_request || github.event.pull_request)
runs-on: ubuntu-latest
steps:
- name: Install jq
run: |
command -v jq && exit 0
sudo apt-get install -y --no-install-recommends jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends jq)
- name: Check permission and merge
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
PR_NUM: ${{ github.event.issue.number || github.event.pull_request.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" "$@"; }
comment() {
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" || true
}
# 权限检查 (write 及以上)
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) ;;
*)
comment "**无法合并 (Merge rejected).** @$COMMENT_USER 没有该仓库的写权限, \`/fast-forward\` 仅限维护者使用. (You need write access to use \`/fast-forward\`.)"
exit 1
;;
esac
# 变基合并 (Gitea 的 rebase 合并会保留原始提交与 GPG 签名)
HTTP_CODE=$(curl -sS -o "$RUNNER_TEMP/merge.json" -w '%{http_code}' \
-X POST -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" \
-d '{"Do":"rebase"}' "$API/repos/$OWNER/$NAME/pulls/$PR_NUM/merge")
if [ "$HTTP_CODE" = "200" ]; then
MERGED=$(jq -r '.merged // false' "$RUNNER_TEMP/merge.json")
STATE=$(jq -r '.state // ""' "$RUNNER_TEMP/merge.json")
if [ "$MERGED" = "true" ] || [ "$STATE" = "closed" ]; then
comment "**合并完成 (Merged)!** 已以变基方式合并, 原始提交与签名得到保留. (Merged with rebase; original commits and signatures preserved.) 🎉"
exit 0
fi
comment "**合并结果 (Merge result):** state=$STATE merged=$MERGED\n$(jq -r '.message // ""' "$RUNNER_TEMP/merge.json")"
exit 1
fi
# 非 200: 输出错误原因
ERR_MSG=$(jq -r '.message // .error // "unknown error"' "$RUNNER_TEMP/merge.json" 2>/dev/null || echo "HTTP $HTTP_CODE")
comment "**合并失败 (Merge failed, HTTP $HTTP_CODE):**\n\n\`\`\`\n$ERR_MSG\n\`\`\`\n\n常见原因: 存在合并冲突、需要先变基到最新 main, 或检查未通过. 请先在本地 rebase 后再推送. (Common causes: conflicts, branch needs rebasing onto latest main, or checks failed.)"
exit 1
+59
View File
@@ -0,0 +1,59 @@
# Greetings
#
# 首次贡献者的 PR 欢迎评论.
# 纯 shell + 平台 API 实现, 不依赖第三方 action (无需从 GitHub 拉取任何内容).
#
# 要求:
# - 平台启用 Gitea Actions 并注册 ubuntu runner
# - 若 Gitea 版本不支持 pull_request_target, 请改为 pull_request
name: Greetings
on:
pull_request_target:
types: [opened]
jobs:
greeting:
runs-on: ubuntu-latest
steps:
- name: Install jq
run: |
command -v jq && exit 0
sudo apt-get install -y --no-install-recommends jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends jq)
- name: Welcome first-time contributor
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
ACTOR: ${{ github.actor }}
PR_NUM: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
api() {
curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"
}
# 统计该用户提交过的 PR 总数 (分页遍历)
total=0
page=1
while :; do
resp=$(api "$API/repos/$OWNER/$NAME/pulls?state=all&poster=$ACTOR&limit=50&page=$page")
n=$(echo "$resp" | jq 'if type=="array" then length else 0 end')
total=$((total + n))
[ "$n" -lt 50 ] && break
page=$((page + 1))
done
if [ "$total" -le 1 ]; then
body=$(jq -n --arg u "@$ACTOR" \
'{"body": ("你好 " + $u + ",感谢提交PR!\nHi " + $u + ", thanks for opening the Pull Request!\n我们会尽早审核回应😊\nWe will respond to it as soon as possible😊")}')
api -X POST -d "$body" "$API/repos/$OWNER/$NAME/issues/$PR_NUM/comments"
echo "Welcome comment posted for first PR of $ACTOR."
else
echo "Not the first PR of $ACTOR ($total PRs), skip."
fi
+101
View File
@@ -0,0 +1,101 @@
# Mark Stale Pull Requests
#
# 每日定时扫描: 长期无活动的 PR 先标记并提醒, 7 天后仍未回应则关闭.
# (纯 shell + 平台 API; issue 不处理, 只处理 PR)
#
# 要求: 平台启用 Gitea Actions 并注册 ubuntu runner.
name: Mark stale pull requests
on:
schedule:
- cron: '0 11 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- name: Install jq
run: |
command -v jq && exit 0
sudo apt-get install -y --no-install-recommends jq \
|| (sudo apt-get update && sudo apt-get install -y --no-install-recommends jq)
- name: Scan and mark stale PRs
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url || 'https://git.xhmcl.com' }}/api/v1
REPO: ${{ github.repository }}
STALE_DAYS: '30'
CLOSE_DAYS: '7'
run: |
set -euo pipefail
OWNER="${REPO%%/*}"
NAME="${REPO#*/}"
STALE_MARKER='<!-- stale-mark -->'
now=$(date -u +%s)
stale_limit=$((STALE_DAYS * 86400))
close_limit=$((CLOSE_DAYS * 86400))
api() { curl -fsS -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" "$@"; }
to_epoch() { date -u -d "$1" +%s 2>/dev/null || echo 0; }
post_comment() {
local num="$1" msg="$2"
BODY_JSON=$(jq -n --arg b "$msg" '{"body": $b}')
api -X POST -d "$BODY_JSON" "$API/repos/$OWNER/$NAME/issues/$num/comments" || true
}
# 逐页遍历 open PR
page=1
while :; do
prs=$(api "$API/repos/$OWNER/$NAME/pulls?state=open&limit=50&page=$page")
n=$(echo "$prs" | jq 'if type=="array" then length else 0 end')
# 每个 PR 一行 JSON, 逐行处理 (避免空格的字段拆分问题)
while read -r pr_json; do
[ -z "$pr_json" ] && continue
num=$(echo "$pr_json" | jq -r '.number')
updated=$(echo "$pr_json" | jq -r '.updated_at // .created_at')
ts=$(to_epoch "$updated")
[ "$ts" = "0" ] && ts=$now
age=$((now - ts))
# 未到 stale 阈值, 跳过
[ "$age" -lt "$stale_limit" ] && continue
# 该 PR 最后一次 stale 标记评论的时间
last_marker_ts=0
cpage=1
while :; do
comments=$(api "$API/repos/$OWNER/$NAME/issues/$num/comments?limit=50&page=$cpage")
cn=$(echo "$comments" | jq 'if type=="array" then length else 0 end')
while IFS=$'\t' read -r cts cbody; do
[ -z "$cts" ] && continue
cts_epoch=$(to_epoch "$cts")
[ "$cts_epoch" -gt "$last_marker_ts" ] && last_marker_ts="$cts_epoch"
done < <(echo "$comments" | jq -r '.[] | "\(.created_at // "")\t\(.body // "")"' | grep -F "$STALE_MARKER")
cpage=$((cpage + 1))
[ "$cn" -lt 50 ] && break
done
if [ "$last_marker_ts" -eq 0 ]; then
# 第一次标记: 评论提醒
echo "Mark stale PR #$num"
post_comment "$num" "这个 PR 已许久未活跃, 请在 7 天内回应, 否则将被关闭。
This PR has had no recent activity. Please respond within 7 days, otherwise it will be closed.
$STALE_MARKER"
elif [ $((now - last_marker_ts)) -ge "$close_limit" ]; then
# 标记后超过 7 天仍未回应: 关闭
echo "Close stale PR #$num"
api -X PATCH -d '{"state":"closed"}' "$API/repos/$OWNER/$NAME/issues/$num" || true
post_comment "$num" "这个 PR 因长期未活跃已关闭, 如需继续请重新打开。
This PR has been closed due to long-term inactivity. Please reopen it if you wish to continue."
fi
done < <(echo "$prs" | jq -c '.[]')
[ "$n" -lt 50 ] && break
page=$((page + 1))
done
echo "Stale scan finished."