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
8 changes: 8 additions & 0 deletions lib/bash/file/lib_file.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions lib/bash/file/tests/lib_file.bats
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
Loading