From f66d9d7f3bb40c364279d388cf50805d1159b535 Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Mon, 18 Apr 2022 20:39:41 +0200 Subject: [PATCH] fixed panic when using mutators on floats --- README.md | 20 ++++++++++++++++++++ main.go | 34 ++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e280e91..ca3f3b7 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,26 @@ day: 2 | month: 1 | year: 2006 day: 2 | month: 2 | year: 1962 ``` +### Adding 2 values together + +Input: +``` +5 7 +3 2 +10 152 +-15 3.7 +``` + +Command: `format -i '(-?\d+) (-?\d+(?:.\d+)?)' -o '{1} + {2} = {1:%.2f:+(2)}'` + +Output: +``` +5 + 7 = 12.00 +3 + 2 = 5.00 +10 + 152 = 162.00 +-15 + 3.7 = -11.30 +``` + ### Bulk renaming files Rename a bunch of files using format at once diff --git a/main.go b/main.go index 92db1d6..4c29cbf 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "reflect" "regexp" "strconv" "strings" @@ -164,14 +165,13 @@ func numMut2func[T int64 | float64](mutation string) (f func(value T, vars []str mutators = append(mutators, mut) } + numberParser := number_parser[T]() + return func(value T, vars []string) T { for _, mutator := range mutators { var otherValue T if mutator.Var { - other, err := strconv.Atoi(vars[mutator.Value]) - if err != nil { - panic("back reference group for number mutator is not a number") - } + other := numberParser(vars[mutator.Value]) otherValue = T(other) } else { otherValue = T(mutator.Value) @@ -193,3 +193,29 @@ func numMut2func[T int64 | float64](mutation string) (f func(value T, vars []str return value } } + +func number_parser[T int64 | float64]() func(str string) T { + typeOfT := reflect.TypeOf(new(T)).Elem() + typeOfInt64 := reflect.TypeOf(new(int64)).Elem() + typeOfFloat64 := reflect.TypeOf(new(float64)).Elem() + + if typeOfT == typeOfInt64 { + return func(str string) T { + num, err := strconv.Atoi(str) + if err != nil { + panic("expected integer but found " + str) + } + return T(num) + } + } else if typeOfT == typeOfFloat64 { + return func(str string) T { + num, err := strconv.ParseFloat(str, 64) + if err != nil { + panic("expected float but found " + str) + } + return T(num) + } + } + + panic("invalid number type") +}