Patcher/new.go
2024-12-11 16:41:49 +01:00

44 lines
1.1 KiB
Go

package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// applyNewModifications handles `t:new` type patches
func applyNewModifications(targetFilePath string, modifications []string) error {
// Ensure the directory structure exists
dir := filepath.Dir(targetFilePath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create directories for target file: %v", err)
}
// Check if the file exists
if _, err := os.Stat(targetFilePath); err == nil {
// File exists, delete it
if err := os.Remove(targetFilePath); err != nil {
return fmt.Errorf("failed to delete existing target file: %v", err)
}
}
// Create a new file and apply modifications
tempFile, err := os.Create(targetFilePath)
if err != nil {
return fmt.Errorf("failed to create target file: %v", err)
}
defer tempFile.Close()
// Write new modifications
for _, mod := range modifications {
if strings.HasPrefix(mod, "+") {
newLine := strings.TrimPrefix(mod, "+")
if _, err := tempFile.WriteString(newLine + "\n"); err != nil {
return fmt.Errorf("failed to write new content to target file: %v", err)
}
}
}
return nil
}