Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions flex_ini.sh
Original file line number Diff line number Diff line change
Expand Up @@ -395,18 +395,39 @@ flex_ini_save() {

[[ "${has_free_keys}" == "true" ]] && echo >>"$ini_file"

# Collect all section names and sort them
declare -A sections
for key in $(flex_ini_keys "$ini_identifier"); do
[[ $key == *.* ]] || continue
local value=$(flex_ini_get "$key" "$ini_identifier")
IFS="." read -r section_name key_name <<<"$key"
sections["$section_name"]=1
done

# Process sections in alphabetical order
for section_name in $(printf '%s\n' "${!sections[@]}" | sort); do
# Check if this is a new section
if [[ "$current_section" != "$section_name" ]]; then
[[ $current_section ]] && echo >>"$ini_file"
echo "[$section_name]" >>"$ini_file"
current_section="$section_name"
fi

echo "$key_name = $value" >>"$ini_file"
# Collect and sort keys for this section only
section_keys=() # Clear the array first
for key in $(flex_ini_keys "$ini_identifier"); do
[[ $key == *.* ]] || continue
IFS="." read -r current_section_name key_name <<<"$key"
if [[ "$current_section_name" == "$section_name" ]]; then
section_keys+=("$key")
fi
done

# Sort keys within this section and write them
for key in $(printf '%s\n' "${section_keys[@]}" | sort); do
IFS="." read -r key_section key_name <<<"$key"
local value=$(flex_ini_get "$key" "$ini_identifier")
echo "$key_name = $value" >>"$ini_file"
done
done

# Back up the destination ini file if specified
Expand Down
41 changes: 41 additions & 0 deletions tests/src/test_flex_ini_save_alphabetizing.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
test_flex_ini_save_alphabetizing() {
local ini_one=$(create_ini)

flex_ini_load "$ini_one"

# Add keys in non-alphabetical order across multiple sections
flex_ini_update "env_prod.secret_key" "prod_secret"
flex_ini_update "env_ci.access_key" "ci_access"
flex_ini_update "env_prodeu.access_key" "prodeu_access"
flex_ini_update "env_prod.access_key" "prod_access"
flex_ini_update "env_ci.secret_key" "ci_secret"
flex_ini_update "env_prodeu.secret_key" "prodeu_secret"

# Save the ini file
flex_ini_save

# Read the file content and verify alphabetizing
local content=$(cat "$ini_one")

# Check that sections are in alphabetical order
# and keys within each section are alphabetical
local expected_order=$(cat <<EOF
[env_ci]
access_key = ci_access
secret_key = ci_secret

[env_prod]
access_key = prod_access
secret_key = prod_secret

[env_prodeu]
access_key = prodeu_access
secret_key = prodeu_secret
EOF
)

expect "$content" "$expected_order"

# Clean up
flex_ini_reset
}