trpc.group/trpc-go/trpc-cmdline@v1.0.9/cmd/create/rpcstub.go (about) 1 // Tencent is pleased to support the open source community by making tRPC available. 2 // 3 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 4 // All rights reserved. 5 // 6 // If you have downloaded a copy of the tRPC source code from Tencent, 7 // please note that tRPC source code is licensed under the Apache 2.0 License, 8 // A copy of the Apache 2.0 License is included in this file. 9 10 package create 11 12 import ( 13 "fmt" 14 "os" 15 "path/filepath" 16 "strings" 17 "time" 18 19 "trpc.group/trpc-go/trpc-cmdline/parser" 20 "trpc.group/trpc-go/trpc-cmdline/tpl" 21 "trpc.group/trpc-go/trpc-cmdline/util/fs" 22 ) 23 24 func (c *Create) createRPCOnlyStub() error { 25 fd, options, outputDir := c.fileDescriptor, c.options, c.options.OutputDir 26 // In case where the current output directory is not empty, 27 // generate all the files inside a temporary directory. 28 // Then move them into the expected output directory. 29 tmpDir := filepath.Join(outputDir, fmt.Sprintf("tmp-%d", time.Now().UnixNano())) 30 if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil { 31 return fmt.Errorf("os.MkdirAll inside create rpc only stub %w", err) 32 } 33 defer os.RemoveAll(tmpDir) 34 // The format of pkg is like: "trpc.group/testapp/testserver". 35 pkg, err := parser.GetPackage(fd, options.Language) 36 if err != nil { 37 return fmt.Errorf("parser get package inside create rpc stub err: %w", err) 38 } 39 // Traverse each file in install/asset_${lang}. 40 if len(fd.Services) != 0 { 41 if err := tpl.GenerateFiles(fd, tmpDir, options); err != nil { 42 return fmt.Errorf("generate files from template inside create rpc stub err: %w", err) 43 } 44 } 45 46 // Generate IDL stub code for protobuf/flatbuffers. 47 if err := c.generateIDLStub(tmpDir); err != nil { 48 return fmt.Errorf("generate rpc stub from template inside create rpc stub err: %w", err) 49 } 50 savedir := filepath.Join(tmpDir, "stub", pkg) 51 saveFiles, err := os.ReadDir(savedir) 52 if err != nil { 53 return err 54 } 55 for _, f := range saveFiles { 56 if strings.HasSuffix(f.Name(), "proto") { 57 continue 58 } 59 if options.NoGoMod && f.Name() == "go.mod" { 60 continue 61 } 62 fs.Move(filepath.Join(savedir, f.Name()), outputDir) 63 } 64 return nil 65 }