-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_to_properties.go
More file actions
164 lines (151 loc) · 3.89 KB
/
json_to_properties.go
File metadata and controls
164 lines (151 loc) · 3.89 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
// flatten walks a JSON value and collects scalar paths -> string values.
// Paths are joined with "."; arrays use numeric indices.
func flatten(v any, prefix string, out map[string]string) {
switch vv := v.(type) {
case map[string]any:
for k, val := range vv {
key := k
if prefix != "" {
key = prefix + "." + k
}
flatten(val, key, out)
}
case []any:
for i, val := range vv {
key := strconv.Itoa(i)
if prefix != "" {
key = prefix + "." + key
}
flatten(val, key, out)
}
case nil:
out[prefix] = ""
case string:
out[prefix] = vv
case float64, bool:
out[prefix] = fmt.Sprint(vv)
default:
// Numbers decoded with UseNumber? Not needed; default fmt ok.
out[prefix] = fmt.Sprint(vv)
}
}
// escBackslashes first, then do other replacements on the result.
func escBackslashes(s string) string { return strings.ReplaceAll(s, `\`, `\\`) }
// escKey: similar to the jq version (practical subset):
// - escape backslashes
// - ":" -> "\:"
// - "=" -> "\="
// - if starts with space or '#' or '!' then escape that first char
// - also make control characters visible (\n,\r,\t) just in case
func escKey(s string) string {
if s == "" {
return s
}
s = escBackslashes(s)
s = strings.ReplaceAll(s, ":", `\:`)
s = strings.ReplaceAll(s, "=", `\=`)
s = strings.ReplaceAll(s, "\n", `\n`)
s = strings.ReplaceAll(s, "\r", `\r`)
s = strings.ReplaceAll(s, "\t", `\t`)
// Escape a leading space, #, or ! to avoid comment/trim semantics
switch s[0] {
case ' ', '#', '!':
s = `\` + s
}
return s
}
// escVal: escape backslashes and control characters; if begins with space prefix with "\ "
func escVal(s string) string {
s = escBackslashes(s)
s = strings.ReplaceAll(s, "\n", `\n`)
s = strings.ReplaceAll(s, "\r", `\r`)
s = strings.ReplaceAll(s, "\t", `\t`)
if strings.HasPrefix(s, " ") {
s = `\` + s
}
return s
}
func main() {
var (
inPath string
outPath string
prefix string
doSort bool
)
flag.StringVar(&inPath, "in", "", "Input Tolgee JSON file (e.g. en.json). If empty, read stdin")
flag.StringVar(&outPath, "out", "", "Output .properties file (e.g. messages_en.properties). If empty, write to stdout")
flag.StringVar(&prefix, "prefix", "", "Optional prefix to add to all keys (e.g. app)")
flag.BoolVar(&doSort, "sort", false, "Sort keys alphabetically for stable output")
flag.Parse()
// Read input
var data []byte
var err error
if inPath == "" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(inPath)
}
if err != nil {
fmt.Fprintf(os.Stderr, "read error: %v\n\n", err)
flag.Usage()
os.Exit(2)
}
// Decode JSON (with decoder to allow comments/extra whitespace if needed)
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
var root any
if err := dec.Decode(&root); err != nil {
fmt.Fprintf(os.Stderr, "json decode error: %v\n", err)
os.Exit(1)
}
flat := make(map[string]string, 256)
base := strings.TrimSpace(prefix)
flatten(root, base, flat)
// Collect items
type kv struct{ k, v string }
items := make([]kv, 0, len(flat))
for k, v := range flat {
// Skip empty path (can happen if top-level scalar without prefix)
if k == "" {
continue
}
items = append(items, kv{k: k, v: v})
}
if doSort {
sort.Slice(items, func(i, j int) bool { return items[i].k < items[j].k })
}
// Prepare output
var b strings.Builder
if inPath != "" {
fmt.Fprintf(&b, "# Generated from %s. Do not edit manually.\n", inPath)
}
for _, it := range items {
k := escKey(it.k)
v := escVal(it.v)
b.WriteString(k)
b.WriteByte('=')
b.WriteString(v)
b.WriteByte('\n')
}
// Write output
if outPath == "" {
_, _ = io.WriteString(os.Stdout, b.String())
} else {
if err := os.WriteFile(outPath, []byte(b.String()), 0o644); err != nil {
fmt.Fprintf(os.Stderr, "write error: %v\n", err)
os.Exit(1)
}
}
}