Refactor modify and replace to their own files
This commit is contained in:
47
utils/replacecommand.go
Normal file
47
utils/replacecommand.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"modify/logger"
|
||||
)
|
||||
|
||||
type ReplaceCommand struct {
|
||||
From int
|
||||
To int
|
||||
With string
|
||||
}
|
||||
|
||||
func ExecuteModifications(modifications []ReplaceCommand, fileData string) (string, int) {
|
||||
var err error
|
||||
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
|
||||
}
|
Reference in New Issue
Block a user