Add modifying operations

This commit is contained in:
2025-03-22 01:19:29 +01:00
parent 75a26ef61a
commit 5929c27731
3 changed files with 75 additions and 4 deletions

2
go.mod
View File

@@ -1,3 +1,5 @@
module modifier
go 1.24.1
require github.com/Knetic/govaluate v3.0.0+incompatible

2
go.sum Normal file
View File

@@ -0,0 +1,2 @@
github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=

75
main.go
View File

@@ -1,14 +1,21 @@
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/Knetic/govaluate"
)
var Error *log.Logger
var Warning *log.Logger
func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
logger := io.MultiWriter(os.Stdout)
@@ -23,7 +30,67 @@ func init() {
}
func main() {
log.Println("Hello, World!")
Warning.Println("Hello, World!")
Error.Println("Hello, World!")
}
flag.Parse()
args := flag.Args()
if len(args) == 0 {
Error.Println("No files provided")
log.Printf("Usage: %s <field> <operation> <...files>", os.Args[0])
log.Printf("Example: %s go run . \"<ticksBetweenBursts>(\\d+)</ticksBetweenBursts>\" \"/10\" Vehicle_JLTV.xml", os.Args[0])
log.Printf("Note: Field must include valid regex with one capture group")
return
}
field := args[0]
operation := args[1]
files := args[2:]
if field == "" || operation == "" || len(files) == 0 {
Error.Println("Invalid arguments")
log.Printf("Usage: %s <field> <operation> <...files>", os.Args[0])
return
}
log.Printf("Field: %s", field)
log.Printf("Operation: %s", operation)
log.Printf("Processing files: %v", files)
fieldRegex, err := regexp.Compile(field)
if err != nil {
Error.Printf("Error compiling field regex: %v", err)
return
}
for _, file := range files {
log.Printf("Processing file: %s", file)
fullPath := filepath.Join(".", file)
content, err := os.ReadFile(fullPath)
if err != nil {
Error.Printf("Error reading file: %v", err)
continue
}
lines := strings.Split(string(content), "\n")
for i, line := range lines {
matches := fieldRegex.FindStringSubmatch(line)
if len(matches) > 1 {
log.Printf("Line: %s", line)
oldValue := matches[1]
expression, err := govaluate.NewEvaluableExpression(oldValue + operation)
if err != nil {
Error.Printf("Error creating expression: %v", err)
continue
}
parameters := map[string]interface{}{"oldValue": oldValue}
newValue, err := expression.Evaluate(parameters)
if err != nil {
Error.Printf("Error evaluating expression: %v", err)
continue
}
updatedLine := strings.Replace(line, oldValue, fmt.Sprintf("%v", newValue), 1)
log.Printf("Updated line: %s", updatedLine)
lines[i] = updatedLine
}
}
err = os.WriteFile(fullPath, []byte(strings.Join(lines, "\n")), 0644)
if err != nil {
Error.Printf("Error writing file: %v", err)
continue
}
log.Printf("File %s updated successfully", file)
}
}