package utils import ( "fmt" "modify/logger" "sort" ) type ReplaceCommand struct { From int To int With string } func ExecuteModifications(modifications []ReplaceCommand, fileData string) (string, int) { var err error sort.Slice(modifications, func(i, j int) bool { return modifications[i].From > modifications[j].From }) logger.Trace("Applying %d replacement commands in reverse order", len(modifications)) executed := 0 for _, modification := range modifications { fileData, err = modification.Execute(fileData) if err != nil { logger.Error("Failed to execute modification: %v", err) continue } executed++ } logger.Info("Executed %d modifications", executed) return fileData, executed } func (m *ReplaceCommand) Execute(fileDataStr string) (string, error) { err := m.Validate(len(fileDataStr)) if err != nil { return "", fmt.Errorf("failed to validate modification: %v", err) } logger.Trace("Replace pos %d-%d with %q", m.From, m.To, m.With) return fileDataStr[:m.From] + m.With + fileDataStr[m.To:], nil } func (m *ReplaceCommand) Validate(maxsize int) error { if m.To < m.From { return fmt.Errorf("command to is less than from: %v", m) } if m.From > maxsize || m.To > maxsize { return fmt.Errorf("command from or to is greater than replacement length: %v", m) } return nil }