Patcher/pref.go

90 lines
2.4 KiB
Go
Raw Normal View History

2024-12-08 17:51:31 +01:00
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// applyPrefModifications handles `t:pref` type patches
func applyPrefModifications(targetFilePath string, modifications []string) error {
// Open the target file
targetFile, err := os.Open(targetFilePath)
if err != nil {
return fmt.Errorf("failed to open target file: %v", err)
}
defer targetFile.Close()
tempFilePath := targetFilePath + ".tmp"
tempFile, err := os.Create(tempFilePath)
if err != nil {
return fmt.Errorf("failed to create temp file: %v", err)
}
defer tempFile.Close()
scanner := bufio.NewScanner(targetFile)
modMap := map[string]string{}
// Prepare the modification map
for _, mod := range modifications {
if strings.HasPrefix(mod, "+pref") {
2024-12-08 18:22:32 +01:00
// Strip the `+` and extract the key within parentheses
start := strings.Index(mod, "(")
end := strings.LastIndex(mod, ")")
if start > 0 && end > start {
key := strings.TrimSpace(mod[start+1 : end])
modMap[key] = strings.TrimPrefix(mod, "+") // Remove the `+` prefix
2024-12-08 17:51:31 +01:00
}
}
}
modifiedLines := map[string]bool{}
for scanner.Scan() {
line := scanner.Text()
// Check if the line matches any modification key
lineModified := false
for key, replacement := range modMap {
2024-12-08 18:22:32 +01:00
if strings.Contains(line, key) && !modifiedLines[key] {
2024-12-08 17:51:31 +01:00
fmt.Printf("Replacing line: %s\n", line)
if _, err := tempFile.WriteString(replacement + "\n"); err != nil {
return fmt.Errorf("failed to write to temp file: %v", err)
}
modifiedLines[key] = true
lineModified = true
break
}
}
// Write the original line if no modification matches
if !lineModified {
if _, err := tempFile.WriteString(line + "\n"); err != nil {
return fmt.Errorf("failed to write to temp file: %v", err)
}
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("failed to read target file: %v", err)
}
// Write remaining modifications (new preferences)
for key, replacement := range modMap {
if !modifiedLines[key] {
2024-12-08 18:22:32 +01:00
// Remove the `+` prefix before writing
cleanReplacement := strings.TrimPrefix(replacement, "+")
if _, err := tempFile.WriteString(cleanReplacement + "\n"); err != nil {
2024-12-08 17:51:31 +01:00
return fmt.Errorf("failed to write new preference to temp file: %v", err)
}
}
}
// Replace the original file with the temporary file
if err := os.Rename(tempFilePath, targetFilePath); err != nil {
return fmt.Errorf("failed to replace target file: %v", err)
}
return nil
}