Protect install target and add tests

This commit is contained in:
2026-04-17 11:58:18 +08:00
parent bd6dc0279e
commit 479c416b2f
4 changed files with 84 additions and 2 deletions

View File

@@ -25,21 +25,38 @@ require_root() {
fi
}
target_is_current_link() {
[[ -L ${TARGET_BIN} ]] || return 1
[[ $(readlink -- "${TARGET_BIN}") == "${SOURCE_SCRIPT}" ]]
}
install_link() {
[[ -f ${SOURCE_SCRIPT} ]] || {
printf '未找到入口脚本: %s\n' "${SOURCE_SCRIPT}" >&2
exit 1
}
mkdir -p "$(dirname -- "${TARGET_BIN}")"
ln -sfn "${SOURCE_SCRIPT}" "${TARGET_BIN}"
if [[ -e ${TARGET_BIN} || -L ${TARGET_BIN} ]]; then
if target_is_current_link; then
chmod 755 "${SOURCE_SCRIPT}"
printf '链接已存在: %s -> %s\n' "${TARGET_BIN}" "${SOURCE_SCRIPT}"
return 0
fi
printf '目标已存在且不是当前脚本的链接,拒绝覆盖: %s\n' "${TARGET_BIN}" >&2
exit 1
fi
ln -s "${SOURCE_SCRIPT}" "${TARGET_BIN}"
chmod 755 "${SOURCE_SCRIPT}"
printf '已创建链接: %s -> %s\n' "${TARGET_BIN}" "${SOURCE_SCRIPT}"
}
uninstall_link() {
if [[ -L ${TARGET_BIN} || -e ${TARGET_BIN} ]]; then
if target_is_current_link; then
rm -f "${TARGET_BIN}"
printf '已删除链接: %s\n' "${TARGET_BIN}"
elif [[ -L ${TARGET_BIN} || -e ${TARGET_BIN} ]]; then
printf '目标不是当前脚本创建的链接,拒绝删除: %s\n' "${TARGET_BIN}" >&2
exit 1
else
printf '未发现已安装链接: %s\n' "${TARGET_BIN}"
fi