1
0
Fork 0
mirror of https://code.forgejo.org/forgejo/runner.git synced 2025-08-06 17:40:58 +00:00

Fix format function {{, }} are escapes (#752)

* Fix format function {{, }} are escapes

Added some tests for some corner cases

* Update format function added 2 error checks
This commit is contained in:
ChristopherHX 2021-08-09 17:19:10 +02:00 committed by GitHub
parent faaee889d5
commit 65f74c5c50
2 changed files with 38 additions and 6 deletions

View file

@ -4,11 +4,11 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/robertkrimen/otto"
@ -266,11 +266,35 @@ func vmEndsWith(vm *otto.Otto) {
}
func vmFormat(vm *otto.Otto) {
_ = vm.Set("format", func(s string, vals ...string) string {
for i, v := range vals {
s = strings.ReplaceAll(s, fmt.Sprintf("{%d}", i), v)
}
return s
_ = vm.Set("format", func(s string, vals ...otto.Value) string {
ex := regexp.MustCompile(`(\{[0-9]+\}|\{.?|\}.?)`)
return ex.ReplaceAllStringFunc(s, func(seg string) string {
switch seg {
case "{{":
return "{"
case "}}":
return "}"
default:
if len(seg) < 3 || !strings.HasPrefix(seg, "{") {
log.Errorf("The following format string is invalid: '%v'", s)
return ""
}
_i := seg[1 : len(seg)-1]
i, err := strconv.ParseInt(_i, 10, 32)
if err != nil {
log.Errorf("The following format string is invalid: '%v'. Error: %v", s, err)
return ""
}
if i >= int64(len(vals)) {
log.Errorf("The following format string references more arguments than were supplied: '%v'", s)
return ""
}
if vals[i].IsNull() || vals[i].IsUndefined() {
return ""
}
return vals[i].String()
}
})
})
}