-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
130 lines (111 loc) · 2.33 KB
/
utils.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
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
package entgqlplus
import (
"log"
"os"
"path"
"strings"
"entgo.io/ent/entc/gen"
"gopkg.in/yaml.v3"
)
var (
lower = strings.ToLower
camel = gen.Funcs["camel"].(func(string) string)
snake = gen.Funcs["snake"].(func(string) string)
beforeMode appendMode = "before"
afterMode appendMode = "after"
)
func writeFiles(files []file) {
for i := range files {
writeFile(files[i])
}
}
func writeFile(f file) {
err := os.MkdirAll(path.Dir(f.Path), 0777)
catch(err)
os.WriteFile(f.Path, []byte(f.Buffer), 0777)
}
func readFile(filePath string) string {
buffer, err := os.ReadFile(filePath)
if err != nil {
log.Fatalln(err)
}
return string(buffer)
}
func catch(err error) {
if err != nil {
log.Fatalln("entgqlplus:", err)
}
}
func readGqlGen(fpath string) gqlGen {
buffer, err := os.ReadFile(fpath)
catch(err)
out := gqlGen{}
err = yaml.Unmarshal(buffer, &out)
catch(err)
out.Exec.Dir = path.Dir(out.Exec.FileName)
out.Model.Dir = path.Dir(out.Model.FileName)
return out
}
func inArray[T string | int | uint](array []T, value T) bool {
for _, v := range array {
if v == value {
return true
}
}
return false
}
func cleanFiles(resolverDir, schemaDir string) {
os.RemoveAll(resolverDir)
os.RemoveAll(schemaDir)
}
func in(lines []string, line string) bool {
for _, l := range lines {
if strings.Contains(l, line) {
return true
}
}
return false
}
func appendLines(filePath string, addedLines []string, pos int, mode appendMode, check []string) string {
if mode == beforeMode {
pos -= 2
} else if mode == afterMode {
pos -= 1
}
lines := strings.Split(readFile(filePath), "\n")
newLines := []string{}
for i, l := range lines {
newLines = append(newLines, l)
if i == pos {
for ni, nl := range addedLines {
if !in(lines, check[ni]) {
newLines = append(newLines, nl)
}
}
}
}
return strings.Join(newLines, "\n")
}
type removeLine struct {
substr string
end bool
}
func removeLines(buffer string, rlines []removeLine) string {
lines := strings.Split(buffer, "\n")
newLines := []string{}
for _, rl := range rlines {
inRange := false
for _, l := range lines {
if strings.Contains(l, rl.substr) {
inRange = true
continue
}
if !inRange || !rl.end {
newLines = append(newLines, l)
}
}
lines = newLines
newLines = []string{}
}
return strings.Join(lines, "\n")
}