github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/stub/stubgen/gen.go (about) 1 package stubgen 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/clubpay/ronykit/kit/desc" 10 "github.com/clubpay/ronykit/kit/utils" 11 ) 12 13 type Input struct { 14 desc.Stub 15 Name string 16 Pkg string 17 } 18 19 type Generator struct { 20 cfg genConfig 21 } 22 23 func New(opt ...Option) *Generator { 24 cfg := defaultConfig 25 for _, o := range opt { 26 o(&cfg) 27 } 28 29 return &Generator{ 30 cfg: cfg, 31 } 32 } 33 34 func (g *Generator) Generate(descs ...desc.ServiceDesc) error { 35 stubs := make([]*desc.Stub, 0, len(descs)) 36 for _, serviceDesc := range descs { 37 stubDesc, err := serviceDesc.Desc().Stub(g.cfg.tags...) 38 if err != nil { 39 return err 40 } 41 42 stubs = append(stubs, stubDesc) 43 } 44 45 rawContent, err := g.cfg.genFunc( 46 Input{ 47 Stub: utils.PtrVal(desc.MergeStubs(stubs...)), 48 Name: g.cfg.stubName, 49 Pkg: g.cfg.pkgName, 50 }, 51 ) 52 if err != nil { 53 return err 54 } 55 56 dirPath := filepath.Join(g.cfg.outputDir, g.cfg.folderName) 57 _ = os.Mkdir(dirPath, os.ModePerm) 58 59 return os.WriteFile( 60 fmt.Sprintf("%s/stub.%s", dirPath, strings.TrimLeft(g.cfg.fileExtension, ".")), 61 utils.S2B(rawContent), 62 os.ModePerm, 63 ) 64 } 65 66 func (g *Generator) MustGenerate(desc ...desc.ServiceDesc) { 67 if err := g.Generate(desc...); err != nil { 68 panic(err) 69 } 70 }