-
Notifications
You must be signed in to change notification settings - Fork 3
/
generate_command.go
80 lines (67 loc) · 2.52 KB
/
generate_command.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
package main
import (
"fmt"
"os"
"strings"
"github.com/urfave/cli/v2"
)
func generateCommand(ctx *cli.Context) error {
packagePath := ctx.Args().First()
elems := strings.Split(packagePath, "/")
for i := range elems {
elems[i] = strings.TrimSpace(elems[i])
if elems[i] == "" {
elems = append(elems[:i], elems[i+1:]...)
}
}
if len(elems) == 0 {
return fmt.Errorf("invalid package path, must not be empty")
}
path := strings.Join(elems, "/")
if err := os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create package directory: %w", err)
}
builder := strings.Builder{}
builder.WriteString("package main\n\n")
builder.WriteString("import (\n")
builder.WriteString("\t\"context\"\n")
builder.WriteString("\t\"os\"\n")
builder.WriteString("\t\"log\"\n")
builder.WriteString("\t\"github.com/snowmerak/lux/v3/lux\"\n")
builder.WriteString("\t\"github.com/snowmerak/lux/v3/provider\"\n")
builder.WriteString(")\n\n")
builder.WriteString("func main() {\n")
builder.WriteString("\tctx, cancel := context.WithCancel(context.Background())\n")
builder.WriteString("\tdefer cancel()\n\n")
builder.WriteString("\tconstructors := []any{\n")
builder.WriteString("\t\tlux.New,\n")
builder.WriteString("\t\tlux.GenerateListenAddress(\":8080\"),\n")
builder.WriteString("\t\t// Add your constructors here\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\tupdaters := []any{\n")
builder.WriteString("\t\t// Add your updaters here\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\tp := provider.New()\n")
builder.WriteString("\tif err := p.Register(constructors...); err != nil {\n")
builder.WriteString("\t\tlog.Fatal(err)\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\tif err := p.Construct(ctx); err != nil {\n")
builder.WriteString("\t\tlog.Fatal(err)\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\tif err := provider.Update(p, updaters...); err != nil {\n")
builder.WriteString("\t\tlog.Fatal(err)\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\tif err := provider.JustRun(p, lux.ListenAndServe1); err != nil {\n")
builder.WriteString("\t\tlog.Fatal(err)\n")
builder.WriteString("\t}\n\n")
builder.WriteString("\t<-ctx.Done()\n")
builder.WriteString("}\n")
cmdFilePath := path + "/main.go"
if _, err := os.Stat(cmdFilePath); !os.IsNotExist(err) {
return fmt.Errorf("command already exists")
}
if err := os.WriteFile(cmdFilePath, []byte(builder.String()), 0644); err != nil {
return fmt.Errorf("failed to write main.go: %w", err)
}
return nil
}