Patcher/standard.go

76 lines
1.9 KiB
Go
Raw Normal View History

2024-12-08 17:51:31 +01:00
package main
import (
"fmt"
"os"
"strings"
)
2025-01-06 23:18:05 +01:00
// applyStandardModifications handles `standard` type patches
func applyStandardModifications(filePath string, modifications []string) error {
contentBytes, err := os.ReadFile(filePath)
2024-12-08 17:51:31 +01:00
if err != nil {
return fmt.Errorf("failed to read file: %v", err)
2024-12-08 17:51:31 +01:00
}
lines := strings.Split(string(contentBytes), "\n")
2025-01-06 23:18:05 +01:00
var delBlock []string
var addBlock []string
var patchBlocks []struct {
del []string
add []string
}
2024-12-08 17:51:31 +01:00
// Group lines into delete and add blocks
for _, line := range modifications {
if strings.HasPrefix(line, "-") {
delBlock = append(delBlock, strings.TrimPrefix(line, "-"))
} else if strings.HasPrefix(line, "+") {
addBlock = append(addBlock, strings.TrimPrefix(line, "+"))
} else if line == "" && len(delBlock) > 0 {
patchBlocks = append(patchBlocks, struct {
del []string
add []string
}{append([]string{}, delBlock...), append([]string{}, addBlock...)})
delBlock = nil
addBlock = nil
}
2024-12-08 17:51:31 +01:00
}
if len(delBlock) > 0 || len(addBlock) > 0 {
patchBlocks = append(patchBlocks, struct {
del []string
add []string
}{delBlock, addBlock})
2024-12-08 17:51:31 +01:00
}
// Apply each block
for _, patch := range patchBlocks {
matchIndex := -1
for i := 0; i <= len(lines)-len(patch.del); i++ {
matched := true
for j := range patch.del {
if strings.TrimSpace(lines[i+j]) != strings.TrimSpace(patch.del[j]) {
matched = false
break
}
}
if matched {
matchIndex = i
2025-01-06 23:18:05 +01:00
break
}
}
if matchIndex == -1 {
return fmt.Errorf("patch block not found in file: %v", patch.del)
2025-01-06 23:18:05 +01:00
}
2024-12-08 17:51:31 +01:00
// Replace matched block
newLines := append([]string{}, lines[:matchIndex]...)
newLines = append(newLines, patch.add...)
newLines = append(newLines, lines[matchIndex+len(patch.del):]...)
lines = newLines
2024-12-08 17:51:31 +01:00
}
// Write updated file
return os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644)
2024-12-08 17:51:31 +01:00
}