From 15ed770a12b6330ccc38dcb0dad4cc21b63dfc57 Mon Sep 17 00:00:00 2001 From: Matt Blum Date: Wed, 7 Jan 2026 11:10:59 -0600 Subject: [PATCH] fix issue where keys were sorted incorrectly --- flex_ini.sh | 25 ++++++++++- tests/src/test_flex_ini_save_alphabetizing.sh | 41 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 tests/src/test_flex_ini_save_alphabetizing.sh diff --git a/flex_ini.sh b/flex_ini.sh index 8af0321..80f8294 100644 --- a/flex_ini.sh +++ b/flex_ini.sh @@ -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 diff --git a/tests/src/test_flex_ini_save_alphabetizing.sh b/tests/src/test_flex_ini_save_alphabetizing.sh new file mode 100644 index 0000000..3133d65 --- /dev/null +++ b/tests/src/test_flex_ini_save_alphabetizing.sh @@ -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 <