Patcher/marker.go
2025-04-09 20:21:38 +02:00

81 lines
1.9 KiB
Go

package main
import (
"fmt"
"os"
"strings"
)
func applyMarkerPatch(targetFilePath string, modifications []string) error {
// Parse patch content
var marker string
var entriesToAdd []string
var entriesToRemove []string
collecting := false
for _, line := range modifications {
switch {
case strings.HasPrefix(line, "#"):
// Capture marker line (first # line only)
if marker == "" {
marker = strings.TrimSpace(strings.TrimPrefix(line, "#"))
collecting = true
}
case collecting && strings.HasPrefix(line, "+"):
entriesToAdd = append(entriesToAdd, strings.TrimPrefix(line, "+"))
case collecting && strings.HasPrefix(line, "-"):
entriesToRemove = append(entriesToRemove, strings.TrimPrefix(line, "-"))
}
}
// Validate input
if marker == "" {
return fmt.Errorf("missing marker line starting with #")
}
// Read entire file
content, err := os.ReadFile(targetFilePath)
if err != nil {
return fmt.Errorf("failed to read file: %v", err)
}
lines := strings.Split(string(content), "\n")
var modifiedLines []string
markerFound := false
for _, line := range lines {
// Check if current line is our marker
if !markerFound && strings.TrimSpace(line) == marker {
markerFound = true
modifiedLines = append(modifiedLines, line)
// Add new entries immediately after marker
modifiedLines = append(modifiedLines, entriesToAdd...)
continue
}
// Check if line should be removed
keep := true
for _, removeLine := range entriesToRemove {
if line == removeLine {
keep = false
break
}
}
if keep {
modifiedLines = append(modifiedLines, line)
}
}
if !markerFound {
return fmt.Errorf("marker line not found: %q", marker)
}
// Write directly to target file
err = os.WriteFile(targetFilePath, []byte(strings.Join(modifiedLines, "\n")), 0644)
if err != nil {
return fmt.Errorf("failed to write changes: %v", err)
}
return nil
}