Files

134 lines
2.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=scripts/github/_gh_env.sh
source "$SCRIPT_DIR/_gh_env.sh"
# shellcheck source=scripts/github/_gh_target.sh
source "$SCRIPT_DIR/_gh_target.sh"
TARGET_REPO=""
ISSUE_NUMBER=""
BODY_TEXT=""
BODY_FILE=""
DRY_RUN=0
SKIP_PREFLIGHT=0
usage() {
cat <<'EOF'
Usage:
bash scripts/github/issue-comment.sh [options]
Options:
--repo OWNER/REPO Target repository, default from git remote
--issue NUMBER Issue number
--body TEXT Comment body text
--body-file FILE Comment body file
--dry-run Print request payload without sending
--skip-preflight Skip GitHub preflight checks
-h, --help Show help
EOF
}
fail() {
echo "[错误] $1" >&2
exit 1
}
parse_args() {
while [[ $# -gt 0 ]]; do
case "$1" in
--repo)
TARGET_REPO="${2:?missing value for --repo}"
shift 2
;;
--issue)
ISSUE_NUMBER="${2:?missing value for --issue}"
shift 2
;;
--body)
BODY_TEXT="${2:?missing value for --body}"
shift 2
;;
--body-file)
BODY_FILE="${2:?missing value for --body-file}"
shift 2
;;
--dry-run)
DRY_RUN=1
shift
;;
--skip-preflight)
SKIP_PREFLIGHT=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
fail "未知参数: $1"
;;
esac
done
if [[ -z "$TARGET_REPO" ]]; then
TARGET_REPO="$(gh_target_resolve_repo_from_remote)"
fi
if [[ -z "$ISSUE_NUMBER" ]]; then
fail "必须提供 --issue"
fi
if [[ -n "$BODY_TEXT" && -n "$BODY_FILE" ]]; then
fail "--body 与 --body-file 只能使用一个"
fi
if [[ -z "$BODY_TEXT" && -z "$BODY_FILE" ]]; then
fail "必须提供 --body 或 --body-file"
fi
}
comment_body() {
if [[ -n "$BODY_FILE" ]]; then
cat "$BODY_FILE"
return 0
fi
printf '%s' "$BODY_TEXT"
}
main() {
local body=""
local payload=""
local response=""
parse_args "$@"
gh_env_prepare
gh_env_require_token
if [[ "$SKIP_PREFLIGHT" != "1" ]]; then
bash "$SCRIPT_DIR/preflight.sh" --repo "$TARGET_REPO" >/dev/null
fi
body="$(comment_body)"
payload="$(jq -nc --arg body "$body" '{body: $body}')"
if [[ "$DRY_RUN" == "1" ]]; then
echo "[dry-run] POST repos/${TARGET_REPO}/issues/${ISSUE_NUMBER}/comments"
printf '%s\n' "$payload" | jq .
exit 0
fi
response="$(
bash "$SCRIPT_DIR/github_api.sh" \
--method POST \
"repos/${TARGET_REPO}/issues/${ISSUE_NUMBER}/comments" \
--data "$payload"
)"
echo "[完成] 已创建 issue 评论: $(printf '%s' "$response" | jq -r '.html_url // .url')"
}
main "$@"