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") { // 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 } } } 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.Contains(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] { // Remove the `+` prefix before writing cleanReplacement := strings.TrimPrefix(replacement, "+") if _, err := tempFile.WriteString(cleanReplacement + "\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 }