github.com/fumiama/NanoBot@v0.0.0-20231122134259-c22d8183efca/codegen/engine/main.go (about) 1 package main 2 3 import ( 4 "os" 5 "strings" 6 7 "gopkg.in/yaml.v3" 8 ) 9 10 const head = `// Code generated by codegen/engine. DO NOT EDIT. 11 12 package nano 13 ` 14 15 const emptyon = ` 16 // On[Message] ... 17 func (e *Engine) On[Message](rules ...Rule) *Matcher { return e.On("[Message]", rules...) } 18 19 // On[Message] ... 20 func On[Message](rules ...Rule) *Matcher { return On("[Message]", rules...) } 21 ` 22 23 const ruleon = ` 24 // On[Message][Rule] ... 25 func On[Message][Rule]([Name] [Type], rules ...Rule) *Matcher { 26 return defaultEngine.On[Message][Rule]([Name], rules...) 27 } 28 29 // On[Message][Rule] ... 30 func (e *Engine) On[Message][Rule]([Name] [Type], rules ...Rule) *Matcher { 31 matcher := &Matcher{ 32 Type: "[Message]", 33 Rules: append([]Rule{[Rule]Rule([Name][...])}, rules...), 34 Engine: e, 35 } 36 e.matchers = append(e.matchers, matcher) 37 return StoreMatcher(matcher) 38 } 39 ` 40 41 const ruleonshell = ` 42 // On[Message]Shell shell命令触发器 43 func On[Message]Shell(command string, model interface{}, rules ...Rule) *Matcher { 44 return defaultEngine.On[Message]Shell(command, model, rules...) 45 } 46 47 // On[Message]Shell shell命令触发器 48 func (e *Engine) On[Message]Shell(command string, model interface{}, rules ...Rule) *Matcher { 49 matcher := &Matcher{ 50 Type: "[Message]", 51 Rules: append([]Rule{ShellRule(command, model)}, rules...), 52 Engine: e, 53 } 54 e.matchers = append(e.matchers, matcher) 55 return StoreMatcher(matcher) 56 } 57 ` 58 59 type config struct { 60 EmptyOn []string `yaml:"emptyon"` 61 RuleOn struct { 62 Message []string `yaml:"Message"` 63 Rule [][3]string `yaml:"Rule"` 64 } `yaml:"ruleon"` 65 } 66 67 func main() { 68 f, err := os.Create("engine_generated.go") 69 if err != nil { 70 panic(err) 71 } 72 defer f.Close() 73 _, err = f.WriteString(head) 74 if err != nil { 75 panic(err) 76 } 77 ef, err := os.Open("codegen/engine/engine.yml") 78 if err != nil { 79 panic(err) 80 } 81 defer ef.Close() 82 cfg := config{} 83 err = yaml.NewDecoder(ef).Decode(&cfg) 84 if err != nil { 85 panic(err) 86 } 87 for _, msg := range cfg.EmptyOn { 88 _, err = f.WriteString(strings.ReplaceAll(emptyon, "[Message]", msg)) 89 if err != nil { 90 panic(err) 91 } 92 } 93 for _, msg := range cfg.RuleOn.Message { 94 for _, x := range cfg.RuleOn.Rule { 95 s := strings.ReplaceAll(ruleon, "[Message]", msg) 96 s = strings.ReplaceAll(s, "[Rule]", x[0]) 97 s = strings.ReplaceAll(s, "[Name]", x[1]) 98 s = strings.ReplaceAll(s, "[Type]", x[2]) 99 if strings.Contains(x[0], "Group") { 100 s = strings.ReplaceAll(s, "[...]", "...") 101 } else { 102 s = strings.ReplaceAll(s, "[...]", "") 103 } 104 _, err = f.WriteString(s) 105 if err != nil { 106 panic(err) 107 } 108 } 109 _, err = f.WriteString(strings.ReplaceAll(ruleonshell, "[Message]", msg)) 110 if err != nil { 111 panic(err) 112 } 113 } 114 }