forked from evcc-io/evcc
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toml.go
98 lines (80 loc) · 1.78 KB
/
toml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bufio"
"bytes"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
)
func process(filepath string) error {
in, err := os.ReadFile(filepath)
if err != nil {
return err
}
pre := new(strings.Builder)
{
sc := bufio.NewScanner(bytes.NewReader(in))
for sc.Scan() {
col := strings.SplitN(sc.Text(), "=", 2)
if len(col) < 2 {
fmt.Fprintln(pre, sc.Text())
continue
}
key := strings.TrimSpace(col[0])
val := strings.TrimSpace(col[1])
if strings.HasPrefix(val, "\"") {
fmt.Fprintln(pre, sc.Text())
continue
}
quote := `"`
if strings.Contains(val, quote) {
quote = `'`
}
fmt.Fprintf(pre, "%s = %s%s%s\n", key, quote, val, quote)
}
}
var config map[string]any
if _, err := toml.Decode(pre.String(), &config); err != nil {
return fmt.Errorf("%s: %v", filepath, err)
}
s := new(strings.Builder)
enc := toml.NewEncoder(s)
enc.Indent = ""
if err := enc.Encode(config); err != nil {
return fmt.Errorf("%s: %v", filepath, err)
}
out := new(strings.Builder)
sc := bufio.NewScanner(strings.NewReader(s.String()))
for sc.Scan() {
if strings.HasPrefix(sc.Text(), "[") && strings.Contains(sc.Text(), ".") && out.Len() > 0 {
fmt.Fprintln(out, "")
}
fmt.Fprintln(out, sc.Text())
}
if err := os.WriteFile(filepath, []byte(out.String()), 0o644); err != nil {
return fmt.Errorf("%s: %v", filepath, err)
}
return nil
}
func main() {
var err error
if len(os.Args) > 1 {
err = process(os.Args[1])
} else {
err = filepath.WalkDir("./i18n", func(filepath string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("%s: %v", filepath, err)
}
if d.IsDir() {
return nil
}
return process(filepath)
})
}
if err != nil {
panic(err)
}
}