-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
96 lines (77 loc) · 1.78 KB
/
generator.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
//go:generate go run generator.go
//go:build generator
package main
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/dave/jennifer/jen"
)
const modsFile = ".modules"
const baseModulePath = "github.com/risor-io/risor/modules/"
const modPrefix = "rsm"
func main() {
source := jen.NewFile("main")
source.NoFormat = false
source.HeaderComment("//go:generate go run generator.go")
list := datasources()
if len(list) == 0 {
return
}
globals := map[string]string{}
for _, ds := range list {
mAlias := modPrefix + filepath.Base(ds)
source.ImportAlias(ds, mAlias)
globals[ds] = mAlias
//source.Anon(ds)
}
var stmts []jen.Code
for k, _ := range globals {
stmts = append(stmts, jen.Lit(filepath.Base(k)).Op(":").Qual(k, "Module").Call())
}
source.Func().Id("globalModules").Params().Map(jen.String()).Any().Block(
jen.Id("a").Op(":=").Map(jen.String()).Any().Values(
stmts...,
),
jen.Return(jen.Id("a")),
)
f, err := os.Create("modules.go")
if err != nil {
genFailed(err)
}
defer f.Close()
fmt.Fprintf(f, "%#v", source)
}
func datasources() []string {
var datasources []string
f, err := os.Open(modsFile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(os.Stderr, "** no %s file found\n", modsFile)
return datasources
}
genFailed(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
ds := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(ds, "//") || ds == "" {
continue
}
// local data sources
if !strings.Contains(ds, "/") {
ds = baseModulePath + ds
}
datasources = append(datasources, ds)
}
return datasources
}
func genFailed(err error) {
fmt.Fprintf(os.Stderr, "generating modules.go failed: %s", err)
os.Exit(1)
}