From 44d52040ec857248710d454f27e81b0fa0f4b0f4 Mon Sep 17 00:00:00 2001 From: Ramesh Padmanabhaiah Date: Sat, 30 May 2026 18:35:12 -0700 Subject: [PATCH] Reject mismatched file section markers --- lib/bash/file/lib_file.sh | 8 ++++++++ lib/bash/file/tests/lib_file.bats | 30 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/bash/file/lib_file.sh b/lib/bash/file/lib_file.sh index 92b35ca..490eada 100644 --- a/lib/bash/file/lib_file.sh +++ b/lib/bash/file/lib_file.sh @@ -72,6 +72,14 @@ update_file_section() { return 0 fi + local beginning_marker_count end_marker_count + beginning_marker_count=$(grep -cF -- "$beginning_marker" "$target_file" || true) + end_marker_count=$(grep -cF -- "$end_marker" "$target_file" || true) + if ((beginning_marker_count != end_marker_count)); then + log_error "Asymmetric markers in '$target_file': $beginning_marker_count start, $end_marker_count end. Manual repair needed." + return 1 + fi + log_info "Updating '$target_file'" local new_content_string="" if [[ "$remove_section" == false ]]; then diff --git a/lib/bash/file/tests/lib_file.bats b/lib/bash/file/tests/lib_file.bats index d1d395c..3098225 100644 --- a/lib/bash/file/tests/lib_file.bats +++ b/lib/bash/file/tests/lib_file.bats @@ -104,6 +104,36 @@ EOF [ "$(cat "$target")" = $'before\nafter' ] } +@test "update_file_section rejects a section with only a start marker" { + local target="$TEST_TMPDIR/config.txt" + cat <<'EOF' > "$target" +before +# BEGIN +orphaned +EOF + + bats_run update_file_section "$target" "# BEGIN" "# END" "new" + + [ "$status" -eq 1 ] + [[ "$output" == *"Asymmetric markers in '$target': 1 start, 0 end. Manual repair needed."* ]] + [ "$(cat "$target")" = $'before\n# BEGIN\norphaned' ] +} + +@test "update_file_section rejects a section with only an end marker" { + local target="$TEST_TMPDIR/config.txt" + cat <<'EOF' > "$target" +before +orphaned +# END +EOF + + bats_run update_file_section "$target" "# BEGIN" "# END" "new" + + [ "$status" -eq 1 ] + [[ "$output" == *"Asymmetric markers in '$target': 0 start, 1 end. Manual repair needed."* ]] + [ "$(cat "$target")" = $'before\norphaned\n# END' ] +} + @test "update_file_section is a no-op for a missing target file" { local target="$TEST_TMPDIR/missing.txt"