github.com/fumiama/NanoBot@v0.0.0-20231122134259-c22d8183efca/codegen/context/main.go (about) 1 package main 2 3 import ( 4 "io/fs" 5 "os" 6 "regexp" 7 "strings" 8 9 nano "github.com/fumiama/NanoBot" 10 ) 11 12 const apirestr = `(\n//\s\w+\s.+\n(//.*\n)*)func\s\(bot\s\*Bot\)\s(.*)\s\{` 13 14 var apire = regexp.MustCompile(apirestr) 15 16 func main() { 17 f, err := os.Create("api_generated.go") 18 if err != nil { 19 panic(err) 20 } 21 defer f.Close() 22 f.WriteString(`// Code generated by codegen/context. DO NOT EDIT. 23 24 package nano 25 `) 26 err = fs.WalkDir(os.DirFS("./"), ".", func(path string, d fs.DirEntry, err error) error { 27 if err != nil { 28 return err 29 } 30 if !strings.HasPrefix(path, "openapi_") { 31 return nil 32 } 33 data, err := os.ReadFile(path) 34 if err != nil { 35 return err 36 } 37 f.WriteString("\n/* vvvvvvvvvvvvvvvvvvvv 生成自文件 ") 38 f.WriteString(path) 39 f.WriteString(" vvvvvvvvvvvvvvvvvvvvv */\n") 40 for _, define := range apire.FindAllStringSubmatch(nano.BytesToString(data), -1) { 41 if strings.Contains(define[3], "NoContext") { 42 continue 43 } 44 f.WriteString(define[1]) // 注释 45 f.WriteString("func (ctx *Ctx) ") // 函数声明 46 f.WriteString(define[3]) 47 f.WriteString(" {\n") 48 // 函数调用 49 f.WriteString("\treturn ctx.caller.") 50 funcname, after, _ := strings.Cut(define[3], "(") 51 f.WriteString(funcname) 52 f.WriteString("(") 53 after, _, _ = strings.Cut(after, ")") 54 paras := strings.Split(after, ", ") 55 switch len(paras) { 56 case 0: 57 case 1: 58 name, def, _ := strings.Cut(paras[0], " ") 59 f.WriteString(name) 60 if strings.Contains(def, "...") { 61 f.WriteString("...") 62 } 63 default: 64 for _, para := range paras[:len(paras)-1] { 65 name, _, _ := strings.Cut(para, " ") 66 f.WriteString(name) 67 f.WriteString(", ") 68 } 69 name, def, _ := strings.Cut(paras[len(paras)-1], " ") 70 f.WriteString(name) 71 if strings.Contains(def, "...") { 72 f.WriteString("...") 73 } 74 } 75 f.WriteString(")\n}\n") 76 } 77 f.WriteString("\n/* ^^^^^^^^^^^^^^^^^^^^ 生成自文件 ") 78 f.WriteString(path) 79 f.WriteString(" ^^^^^^^^^^^^^^^^^^^^ */\n") 80 return nil 81 }) 82 if err != nil { 83 panic(err) 84 } 85 }