Skip to content

Commit

Permalink
feat: Support nginx escape chars
Browse files Browse the repository at this point in the history
  • Loading branch information
soulteary committed Apr 18, 2023
1 parent bad7284 commit 21199a8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
11 changes: 11 additions & 0 deletions internal/formatter/beautifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
18 changes: 16 additions & 2 deletions internal/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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
}
Expand Down

0 comments on commit 21199a8

Please sign in to comment.