refactor: improve key tracking in upsert_env function

This commit is contained in:
chenyw1990 2026-01-27 22:16:47 +08:00
parent 3f83afe4a6
commit a7e90a2575

View File

@ -124,7 +124,18 @@ upsert_env() {
local -a keys=("$@") local -a keys=("$@")
local tmp local tmp
tmp="$(mktemp)" tmp="$(mktemp)"
declare -A seen=() local -a seen_keys=()
local has_seen
has_seen() {
local candidate="$1"
local existing
for existing in "${seen_keys[@]:-}"; do
if [[ "$existing" == "$candidate" ]]; then
return 0
fi
done
return 1
}
if [[ -f "$file" ]]; then if [[ -f "$file" ]]; then
while IFS= read -r line || [[ -n "$line" ]]; do while IFS= read -r line || [[ -n "$line" ]]; do
@ -133,7 +144,7 @@ upsert_env() {
for k in "${keys[@]}"; do for k in "${keys[@]}"; do
if [[ "$key" == "$k" ]]; then if [[ "$key" == "$k" ]]; then
printf '%s=%s\n' "$k" "${!k-}" >>"$tmp" printf '%s=%s\n' "$k" "${!k-}" >>"$tmp"
seen["$k"]=1 seen_keys+=("$k")
replaced=true replaced=true
break break
fi fi
@ -145,7 +156,7 @@ upsert_env() {
fi fi
for k in "${keys[@]}"; do for k in "${keys[@]}"; do
if [[ -z "${seen[$k]:-}" ]]; then if ! has_seen "$k"; then
printf '%s=%s\n' "$k" "${!k-}" >>"$tmp" printf '%s=%s\n' "$k" "${!k-}" >>"$tmp"
fi fi
done done