Simplify helpers under line cap

This commit is contained in:
2026-04-17 11:33:45 +08:00
parent 4c431584eb
commit af871a67a3
5 changed files with 87 additions and 168 deletions

View File

@@ -9,60 +9,38 @@ IPF_STORAGE_SH_LOADED=1
: "${IPF_STORAGE_DB:=${IPF_STORAGE_DIR}/rules.db}"
: "${IPF_LOCK_FILE:=${IPF_STORAGE_DIR}/.lock}"
storage_dir() {
printf '%s\n' "${IPF_STORAGE_DIR}"
}
storage_db_path() {
printf '%s\n' "${IPF_STORAGE_DB}"
}
storage_lock_path() {
printf '%s\n' "${IPF_LOCK_FILE}"
}
storage_dir() { printf '%s\n' "${IPF_STORAGE_DIR}"; }
storage_db_path() { printf '%s\n' "${IPF_STORAGE_DB}"; }
storage_lock_path() { printf '%s\n' "${IPF_LOCK_FILE}"; }
storage_init() {
local dir db lock
dir=$(storage_dir)
db=$(storage_db_path)
lock=$(storage_lock_path)
mkdir -p "${dir}"
touch "${db}" "${lock}"
chmod 750 "${dir}"
chmod 640 "${db}"
chmod 600 "${lock}"
mkdir -p "${IPF_STORAGE_DIR}"
touch "${IPF_STORAGE_DB}" "${IPF_LOCK_FILE}"
chmod 750 "${IPF_STORAGE_DIR}"
chmod 640 "${IPF_STORAGE_DB}"
chmod 600 "${IPF_LOCK_FILE}"
}
storage_with_lock() {
local lock
storage_init
lock=$(storage_lock_path)
(
flock -x 9
"$@"
) 9>>"${lock}"
) 9>>"${IPF_LOCK_FILE}"
}
storage_add_unlocked() {
local line=${1-}
local db
[[ -n ${line} ]] || return 1
storage_init
db=$(storage_db_path)
printf '%s\n' "${line}" >>"${db}"
printf '%s\n' "${line}" >>"${IPF_STORAGE_DB}"
}
storage_add() {
storage_with_lock storage_add_unlocked "$@"
}
storage_add() { storage_with_lock storage_add_unlocked "$@"; }
storage_list() {
local db
db=$(storage_db_path)
[[ -f ${db} ]] || return 0
cat "${db}"
[[ -f ${IPF_STORAGE_DB} ]] || return 0
cat "${IPF_STORAGE_DB}"
}
storage_parse() {
@@ -95,11 +73,10 @@ storage_get() {
storage_delete_unlocked() {
local uuid=${1-}
local db tmp found=0 line current
local tmp found=0 line current
[[ -n ${uuid} ]] || return 1
storage_init
db=$(storage_db_path)
tmp="${db}.tmp.$$"
tmp="${IPF_STORAGE_DB}.tmp.$$"
: >"${tmp}"
while IFS= read -r line || [[ -n ${line} ]]; do
@@ -109,19 +86,12 @@ storage_delete_unlocked() {
continue
fi
printf '%s\n' "${line}" >>"${tmp}"
done <"${db}"
if (( found == 0 )); then
rm -f "${tmp}"
return 1
fi
mv "${tmp}" "${db}"
done <"${IPF_STORAGE_DB}"
(( found == 1 )) || { rm -f "${tmp}"; return 1; }
mv "${tmp}" "${IPF_STORAGE_DB}"
}
storage_delete() {
storage_with_lock storage_delete_unlocked "$@"
}
storage_delete() { storage_with_lock storage_delete_unlocked "$@"; }
storage_count() {
local count=0 line