-
-
Notifications
You must be signed in to change notification settings - Fork 250
/
include.go
79 lines (63 loc) · 1.79 KB
/
include.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
// SPDX-License-Identifier: MIT
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
)
const constantsFile = "./processor/constants.go"
func fatalf(f string, v ...interface{}) {
fmt.Fprintf(os.Stderr, f+"\n", v...)
os.Exit(1)
}
// Reads all .json files in the current folder
// and encodes them as strings literals in constants.go
func generateConstants() error {
files, _ := ioutil.ReadDir(".")
out, err := ioutil.TempFile(".", "temp_constants")
if err != nil {
return fmt.Errorf("failed to open temp file: %v", err)
}
defer os.Remove(out.Name())
// Open constants
out.Write([]byte("package processor \n\nconst (\n"))
for _, f := range files {
if strings.HasPrefix(f.Name(), "languages") && strings.HasSuffix(f.Name(), ".json") {
f, err := os.Open(f.Name())
if err != nil {
return fmt.Errorf("failed to open file '%s': %v", f.Name(), err)
}
// validate the json by decoding into an empty struct
if err := json.NewDecoder(f).Decode(&struct{}{}); err != nil {
return fmt.Errorf("failed to validate json in file '%s': %v", f.Name(), err)
}
// Reset position
f.Seek(0, io.SeekStart)
// The constant variable name
out.Write([]byte(strings.TrimSuffix(f.Name(), ".json") + " = `"))
enc := base64.NewEncoder(base64.StdEncoding, out)
if _, err := io.Copy(enc, f); err != nil {
return fmt.Errorf("failed to encode file '%s': %v", f.Name(), err)
}
enc.Close()
out.Write([]byte("`\n"))
}
}
// Close out constants
out.Write([]byte(")\n"))
out.Close()
if err := os.Rename(out.Name(), constantsFile); err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
func main() {
if err := generateConstants(); err != nil {
fmt.Fprintf(os.Stderr, "failed to generate constants: %v\n", err)
os.Exit(1)
}
}