diff --git a/internal/formatter/beautifier.js b/internal/formatter/beautifier.js index f9f7059..93c3d6a 100644 --- a/internal/formatter/beautifier.js +++ b/internal/formatter/beautifier.js @@ -173,6 +173,16 @@ function add_empty_line_after_nginx_directives(lines) { return output.reverse(); } +function fixDollarVar(lines) { + const placeHolder = `[dollar]`; + return lines.map((line) => { + while (line.indexOf(placeHolder) !== -1) { + line = line.replace(placeHolder, "$"); + } + return line; + }); +} + var options = { INDENTATION: "\t" }; function perform_indentation(lines) { @@ -205,5 +215,6 @@ function FormatNginxConf(text, indentation = " ") { lines = join_opening_bracket(lines); lines = perform_indentation(lines); lines = add_empty_line_after_nginx_directives(lines); + lines = fixDollarVar(lines); return fold_empty_brackets(lines); } diff --git a/internal/updater/updater.go b/internal/updater/updater.go index 3342264..e2c3f88 100644 --- a/internal/updater/updater.go +++ b/internal/updater/updater.go @@ -4,9 +4,23 @@ import ( "fmt" "os" "path/filepath" + "regexp" "strings" ) +func EncodeEscapeChars(s string) string { + 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`) +} + +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\";") +} + func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error { if rootDir == "" { return fmt.Errorf("scandir is empty") @@ -23,12 +37,12 @@ func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error { return err } - modifiedData, err := fn(string(data)) + modifiedData, err := fn(FixVars(EncodeEscapeChars(string(data)))) if err != nil { return err } - err = os.WriteFile(path, []byte(modifiedData), info.Mode()) + err = os.WriteFile(path, []byte(DecodeEscapeChars(modifiedData)), info.Mode()) if err != nil { return err }