updated patch system
This commit is contained in:
parent
bb64cea202
commit
6c9c66bd7a
10 changed files with 434 additions and 208 deletions
85
pref.go
Normal file
85
pref.go
Normal file
|
@ -0,0 +1,85 @@
|
|||
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") {
|
||||
parts := strings.SplitN(mod, "(", 2)
|
||||
if len(parts) > 1 {
|
||||
key := strings.TrimSpace(parts[0][1:])
|
||||
modMap[key] = strings.TrimSpace(mod)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
if strings.HasPrefix(line, key) && !modifiedLines[key] {
|
||||
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] {
|
||||
if _, err := tempFile.WriteString(replacement + "\n"); err != nil {
|
||||
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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue