forked from highcard-dev/scrolls
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-scrolls.go
More file actions
337 lines (289 loc) · 9.03 KB
/
Copy pathgenerate-scrolls.go
File metadata and controls
337 lines (289 loc) · 9.03 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"unicode"
cp "github.com/otiai10/copy"
"github.com/blang/semver"
)
type TemplateVars struct {
Artifact string
Version string
VersionEscaped string
ColdstarterImage string
SteamImage string
Artifacts map[string]string
ArtifactsUnescaped map[string]string
Vars map[string]string
Ports []PortSpec
ChunksYaml string
}
type PortSpec struct {
Name string
Port string
Protocol string
Description string
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Please enter a path.")
return
}
basepath := os.Args[1]
buildPath := basepath + "/.build"
artifactsPath := buildPath + "/artifacts.json"
switchScrollDir := buildPath + "/scroll-switch"
scrollYamlTemplate := buildPath + "/scroll.yaml.tmpl"
varsFile := buildPath + "/vars.json"
println("Path: " + buildPath)
println("Artifacts Path: " + artifactsPath)
println("Switch Scroll Dir: " + switchScrollDir)
println("Scroll Yaml Template: " + scrollYamlTemplate)
println("Vars File: " + varsFile)
//parse vars json file, if exists
vars := make(map[string]map[string]string)
varsBytes, err := ioutil.ReadFile(varsFile)
if err != nil {
fmt.Printf("Error reading vars.json file. %s", err.Error())
}
if varsBytes != nil {
json.Unmarshal(varsBytes, &vars)
}
//parse artifacs json file
artifacts := make(map[string]string)
artifactBytes, err := ioutil.ReadFile(artifactsPath)
if err != nil {
fmt.Printf("Error reading artifacts.json file. %s", err.Error())
return
}
json.Unmarshal(artifactBytes, &artifacts)
// Create template with custom functions
funcMap := template.FuncMap{
"split": func(sep, s string) []string {
return strings.Split(s, sep)
},
"upper": strings.ToUpper,
"env": func(value string) string {
var out strings.Builder
for i, r := range value {
if i > 0 && unicode.IsUpper(r) {
out.WriteByte('_')
}
if r == '-' || r == ' ' {
out.WriteByte('_')
continue
}
out.WriteRune(unicode.ToUpper(r))
}
return out.String()
},
}
scollYamltemplate, err := template.New(filepath.Base(scrollYamlTemplate)).Funcs(funcMap).ParseFiles(scrollYamlTemplate)
// Capture any error
if err != nil {
log.Fatalln(err)
}
coldstarterImage := os.Getenv("DRUID_COLDSTARTER_IMAGE")
if coldstarterImage == "" {
coldstarterImage = "artifacts.druid.gg/druid-team/druid:v0.1.249"
}
steamImage := os.Getenv("DRUID_STEAM_RUNTIME_IMAGE")
if steamImage == "" {
steamImage = "artifacts.druid.gg/druid-team/druid:v0.1.249-steamcmd"
}
//iterate through artifacts and generate scroll.yaml files
for version, artifact := range artifacts {
println("Generating scroll.yaml for " + artifact + " version " + version)
var templateVars TemplateVars
templateVars.Artifact = artifact
templateVars.Version = version
templateVars.VersionEscaped = strings.Replace(version, ".", "-", -1)
templateVars.ColdstarterImage = coldstarterImage
templateVars.SteamImage = steamImage
templateVars.Artifacts = GetArtifactsAbove(version, artifacts, true)
templateVars.ArtifactsUnescaped = GetArtifactsAbove(version, artifacts, false)
if varsBytes != nil && vars[version] == nil {
log.Println("No vars found for version " + version + " in vars.json file. Please add vars for this version.")
} else {
templateVars.Vars = vars[version]
}
templateVars.Ports = ParsePorts(templateVars.Vars["port"])
chunksYaml, err := ioutil.ReadFile(filepath.Join(buildPath, "versions", version, "chunks.yaml"))
if err == nil {
templateVars.ChunksYaml = string(chunksYaml)
} else if !os.IsNotExist(err) {
log.Println("read chunks.yaml: ", err)
return
}
//create scroll dir
dir := filepath.Join(basepath, version)
os.MkdirAll(dir, os.ModePerm)
// Create a new file for the rendered output
outputFile, err := os.Create(filepath.Join(dir, "scroll.yaml"))
if err != nil {
log.Println("create file: ", err)
return
}
defer outputFile.Close()
// Print out the template to std
scollYamltemplate.Execute(outputFile, templateVars)
cp.Copy(buildPath+"/data", dir+"/data")
cp.Copy(buildPath+"/packet_handler", dir+"/packet_handler")
cp.Copy(buildPath+"/update", dir+"/update")
//copy metadata, this might copy nothing
cp.Copy(buildPath+"/meta/"+version, dir+"/.meta")
//copy version specific files
cp.Copy(buildPath+"/versions/"+version, dir, cp.Options{
OnDirExists: func(src, dest string) cp.DirExistsAction {
return cp.Merge
},
Skip: func(info os.FileInfo, src, dest string) (bool, error) {
return info.Name() == "chunks.yaml", nil
},
})
//copy shell scripts
cp.Copy(buildPath, dir, cp.Options{
Skip: func(info os.FileInfo, src, dest string) (bool, error) {
return !strings.HasSuffix(src, ".sh") || strings.HasPrefix(info.Name(), "_"), nil
},
})
//render and copy switch scroll
subitems, _ := ioutil.ReadDir(switchScrollDir)
for _, subitem := range subitems {
if !subitem.IsDir() {
//just copy the files instead
cp.Copy(filepath.Join(switchScrollDir, subitem.Name()), filepath.Join(dir, "scroll-switch", subitem.Name()))
continue
}
filename := subitem.Name()
switchSrollYaml := filepath.Join(switchScrollDir, filename, "scroll-switch.sh.tmpl")
drdScrollName := strings.TrimSuffix(filename, "@version")
println("Generating switch scroll for " + drdScrollName + " version " + version)
filecontent, err := ioutil.ReadFile(switchSrollYaml)
if err != nil {
log.Fatalln(err)
}
for version, artifact := range GetArtifactsAbove(version, artifacts, false) {
escapedVersion := strings.Replace(version, ".", "-", -1)
switchScrollDir := filepath.Join(dir, "scroll-switch", drdScrollName+"@"+escapedVersion)
os.MkdirAll(switchScrollDir, os.ModePerm)
RenderScrollSwitch(switchScrollDir, "scroll-switch.sh", string(filecontent), artifact, version)
}
}
}
}
func ParsePorts(spec string) []PortSpec {
var ports []PortSpec
for _, part := range strings.Split(spec, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name := part
value := ""
if strings.Contains(part, "=") {
pieces := strings.SplitN(part, "=", 2)
name = strings.TrimSpace(pieces[0])
value = strings.TrimSpace(pieces[1])
}
if name == "" {
continue
}
port := value
protocol := "tcp"
if strings.Contains(value, "/") {
pieces := strings.SplitN(value, "/", 2)
port = strings.TrimSpace(pieces[0])
protocol = strings.TrimSpace(pieces[1])
}
if protocol == "" {
protocol = "tcp"
}
ports = append(ports, PortSpec{
Name: name,
Port: port,
Protocol: protocol,
Description: PortDescription(name),
})
}
return ports
}
func PortDescription(name string) string {
switch name {
case "query":
return "Steam Query Port. Use this to connect via the Steam client."
case "main":
return "Main game port. Use this port inside of your game client to connect to the server. Depending on the game you might need the query port to connect."
default:
return ""
}
}
func RenderScrollSwitch(dir string, filename string, filecontent string, artifact string, version string) {
escapedVersion := strings.Replace(version, ".", "-", -1)
templateVars := TemplateVars{Artifact: artifact, Version: version, VersionEscaped: escapedVersion}
RenderFile(dir, filename, filecontent, templateVars)
}
func RenderFolder(dir string, targetFolder string, data any) {
// Create a new file for the rendered output
outputFile, err := os.Create(filepath.Join(dir, targetFolder))
if err != nil {
log.Println("create file: ", err)
return
}
defer outputFile.Close()
templ, err := template.New(dir).Parse(string(targetFolder))
// Capture any error
if err != nil {
log.Fatalln(err)
}
// Print out scroll switch template
templ.Execute(outputFile, data)
}
func RenderFile(dir string, filename string, filecontent string, data any) {
// Create a new file for the rendered output
outputFile, err := os.Create(filepath.Join(dir, filename))
if err != nil {
log.Println("create file: ", err)
return
}
defer outputFile.Close()
templ, err := template.New(dir).Parse(string(filecontent))
// Capture any error
if err != nil {
log.Fatalln(err)
}
// Print out scroll switch template
templ.Execute(outputFile, data)
}
func GetArtifactsAbove(version string, artifacts map[string]string, escaped bool) map[string]string {
artifactsAbove := make(map[string]string)
for artifactVersion, artifact := range artifacts {
aV := SafeParseVersion(artifactVersion)
v := SafeParseVersion(version)
fmt.Printf("aV %v v: %v \n", aV, v)
if escaped {
artifactVersion = strings.Replace(artifactVersion, ".", "-", -1)
}
if aV.GT(v) {
artifactsAbove[artifactVersion] = artifact
}
}
return artifactsAbove
}
func SafeParseVersion(version string) semver.Version {
parts := strings.Split(version, ".")
if len(parts) < 1 {
log.Fatalln("Invalid version format " + version)
}
if len(parts) == 2 {
version = version + ".0"
}
v, _ := semver.Parse(version)
return v
}