Skip to content

Commit

Permalink
feat: Support multiple return
Browse files Browse the repository at this point in the history
  • Loading branch information
soulteary committed Apr 19, 2023
1 parent 21199a8 commit e367523
Showing 1 changed file with 43 additions and 4 deletions.
47 changes: 43 additions & 4 deletions internal/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,55 @@ import (
)

func EncodeEscapeChars(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `\t`, `{{\\}}t`), `\s`, `{{\\}}s`), `\r`, `{{\\}}r`), `\n`, `{{\\}}n`)
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `\t`, `【\\】t`), `\s`, `【\\】s`), `\r`, `【\\】r`), `\n`, `【\\】n`)
}

func DecodeEscapeChars(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `{{\}}t`, `\t`), `{{\}}s`, `\s`), `{{\}}r`, `\r`), `{{\}}n`, `\n`)
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `【\】t`, `\t`), `【\】s`, `\s`), `【\】r`, `\r`), `【\】n`, `\n`)
}

// scenes:
//
// return 200 "1" ;
// return 200 "1";
// return "1" ;
// return 200;
// return "aaa\naa";
// return 200 "a\n" ;
// return BACKEND\n;
func FixReturn(s string) string {
var scene1 = regexp.MustCompile(`return\s+(\d+)\s(\S+)\s*;`)
var scene2 = regexp.MustCompile(`return\s+(\d+)\s"(\S+)"\s*;`)
var scene3 = regexp.MustCompile(`return\s+(\S+)\s*;`)
var scene4 = regexp.MustCompile(`return\s+"(\S+)"\s*;`)
var scene5 = regexp.MustCompile(`return\s+(\d+)\s*;`)

if scene1.MatchString(s) {
if scene2.MatchString(s) { // eg: `return 200 "ok";`
s = scene2.ReplaceAllString(s, "return $1 \"$2\";")
} else { // eg: `return 200 $content;`
s = scene1.ReplaceAllString(s, "return $1 \"$2\";")
}
} else if scene3.MatchString(s) {
if scene5.MatchString(s) { // eg: `return 200;`
s = scene5.ReplaceAllString(s, "return $1;")
} else if scene4.MatchString(s) { // eg: `return "ok";`
s = scene4.ReplaceAllString(s, "return \"$1\";")
} else { // eg: `return BACKEND\n;`
found := scene3.FindString(s)
if !(strings.HasPrefix(found, `"`) && strings.HasSuffix(found, `"`)) {
s = scene3.ReplaceAllString(s, "return $1;")
} else {
s = scene3.ReplaceAllString(s, "return \"$1\";")
}
}
}
return s
}

func FixVars(s string) string {
s = regexp.MustCompile(`(\$)(\{\S+?\})`).ReplaceAllString(s, "[dollar]$2")
return regexp.MustCompile(`(return\s+\d+\s+?)([\s\S]+?);`).ReplaceAllString(s, "$1\"$2\";")
return s
}

func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error {
Expand All @@ -37,7 +76,7 @@ func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error {
return err
}

modifiedData, err := fn(FixVars(EncodeEscapeChars(string(data))))
modifiedData, err := fn(FixVars(FixReturn(EncodeEscapeChars(string(data)))))
if err != nil {
return err
}
Expand Down

0 comments on commit e367523

Please sign in to comment.