Skip to content

Commit 21199a8

Browse files
committed
feat: Support nginx escape chars
1 parent bad7284 commit 21199a8

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

internal/formatter/beautifier.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,16 @@ function add_empty_line_after_nginx_directives(lines) {
173173
return output.reverse();
174174
}
175175

176+
function fixDollarVar(lines) {
177+
const placeHolder = `[dollar]`;
178+
return lines.map((line) => {
179+
while (line.indexOf(placeHolder) !== -1) {
180+
line = line.replace(placeHolder, "$");
181+
}
182+
return line;
183+
});
184+
}
185+
176186
var options = { INDENTATION: "\t" };
177187

178188
function perform_indentation(lines) {
@@ -205,5 +215,6 @@ function FormatNginxConf(text, indentation = " ") {
205215
lines = join_opening_bracket(lines);
206216
lines = perform_indentation(lines);
207217
lines = add_empty_line_after_nginx_directives(lines);
218+
lines = fixDollarVar(lines);
208219
return fold_empty_brackets(lines);
209220
}

internal/updater/updater.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,23 @@ import (
44
"fmt"
55
"os"
66
"path/filepath"
7+
"regexp"
78
"strings"
89
)
910

11+
func EncodeEscapeChars(s string) string {
12+
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `\t`, `{{\\}}t`), `\s`, `{{\\}}s`), `\r`, `{{\\}}r`), `\n`, `{{\\}}n`)
13+
}
14+
15+
func DecodeEscapeChars(s string) string {
16+
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, `{{\}}t`, `\t`), `{{\}}s`, `\s`), `{{\}}r`, `\r`), `{{\}}n`, `\n`)
17+
}
18+
19+
func FixVars(s string) string {
20+
s = regexp.MustCompile(`(\$)(\{\S+?\})`).ReplaceAllString(s, "[dollar]$2")
21+
return regexp.MustCompile(`(return\s+\d+\s+?)([\s\S]+?);`).ReplaceAllString(s, "$1\"$2\";")
22+
}
23+
1024
func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error {
1125
if rootDir == "" {
1226
return fmt.Errorf("scandir is empty")
@@ -23,12 +37,12 @@ func UpdateConfInDir(rootDir string, fn func(s string) (string, error)) error {
2337
return err
2438
}
2539

26-
modifiedData, err := fn(string(data))
40+
modifiedData, err := fn(FixVars(EncodeEscapeChars(string(data))))
2741
if err != nil {
2842
return err
2943
}
3044

31-
err = os.WriteFile(path, []byte(modifiedData), info.Mode())
45+
err = os.WriteFile(path, []byte(DecodeEscapeChars(modifiedData)), info.Mode())
3246
if err != nil {
3347
return err
3448
}

0 commit comments

Comments
 (0)