Files
gitea/tools/hash-id
T
jiantw83andClaude Sonnet 5 96a0772d65 feat(gitea): 為 hash-id 新增 key 子命令並拆出獨立的名稱正規化模組
為什麼:多個技能各自手動拼接計畫名稱與 owner/repo 字串再算雜湊,重複邏輯容易長出分歧的正規化寫法,也讓 hash-id 混雜了業務規則,職責變得不單純。

做了什麼:
- hash-id 新增 key 子命令(hash-id key <計畫名稱> <owner/repo>),將計畫名稱正規化後以 | 分隔接上 owner/repo 再計算雜湊,提供統一的組法入口,讓其他技能不必各自接字串。
- 將正規化規則(Unicode NFC、去除頭尾空白、內部連續空白壓成一個、全形英數轉半形,大小寫維持不變)獨立成 tools/normalize-name.sh,hash-id 只呼叫它,不再內嵌業務規則,保持雜湊職責單純,也方便日後其他工具重用同一套正規化邏輯。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-08 10:32:24 +08:00

57 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env sh
# hash-id — 產生完整 40 碼大寫 SHA-1 hash。
# 用法:
# hash-id <text>
# hash-id key <計畫名稱> <owner/repo>
# printf '%s' <text> | hash-id
# key 子命令的參數:
# 計畫名稱: 交給 normalize-name.sh 正規化後再接字串,同名不同打法算出同一把 key。
# owner/repo: 存取庫識別,原樣接上,不經正規化。
# 規則:
# 取完整 SHA-1 四十碼,a-f 轉大寫,不截短、不加前綴。
# 輸入為空即 exit 2。空字串本身也有合法的 SHA-1,靜靜回傳它就會生出
# 一個看起來正常的頁名,把內容寫到沒有人讀的那一頁。
# key 子命令把多個欄位接成雜湊輸入的組法收在這裡當單一入口:固定用 `|`
# 分隔,避免各技能各自接字串各接各的。正規化規則本身不是雜湊職責,收在
# 獨立那支工具,這裡只管接字串。
# 結束碼: 0=成功 1=這台機器沒有 sha1sum 也沒有 shasum,算不出雜湊
# 2=用法錯誤:沒有給文字,或給的是空字串
set -eu
dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
input=''
if [ "${1:-}" = 'key' ]; then
shift
name="${1:-}"; repo="${2:-}"
if [ -z "$name" ] || [ -z "$repo" ]; then
echo 'usage: hash-id key <計畫名稱> <owner/repo>' >&2
exit 2
fi
# 正規化計畫名稱,讓「我的 計畫」與「我的 計畫」這類同名不同打法算出同一把 key。
name=$(sh "$dir/normalize-name.sh" "$name")
input="${name}|${repo}"
elif [ "$#" -gt 0 ]; then
input=$*
elif [ -t 0 ]; then
input=''
else
input=$(cat)
fi
if [ -z "$input" ]; then
echo 'usage: hash-id <text>' >&2
exit 2
fi
if command -v sha1sum >/dev/null 2>&1; then
raw=$(printf '%s' "$input" | sha1sum | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
raw=$(printf '%s' "$input" | shasum -a 1 | awk '{print $1}')
else
echo 'no SHA-1 helper found' >&2
exit 1
fi
printf '%s\n' "$raw" | tr a-f A-F