github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/protoc-gen-toolkit/generator/generator.go (about)

     1  /*
     2  Copyright [2014] - [2023] The Last.Backend authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package generator
    18  
    19  import (
    20  	"flag"
    21  
    22  	"github.com/lastbackend/toolkit/protoc-gen-toolkit/descriptor"
    23  	"github.com/lastbackend/toolkit/protoc-gen-toolkit/gentoolkit"
    24  	"google.golang.org/protobuf/compiler/protogen"
    25  	"google.golang.org/protobuf/types/pluginpb"
    26  )
    27  
    28  type Generator struct {
    29  	files []*descriptor.File
    30  }
    31  
    32  func Init() *Generator {
    33  	g := new(Generator)
    34  	g.files = make([]*descriptor.File, 0)
    35  	return g
    36  }
    37  
    38  func (g *Generator) Run() error {
    39  	var flagSet flag.FlagSet
    40  
    41  	protogen.Options{
    42  		ParamFunc: flagSet.Set,
    43  	}.Run(func(gen *protogen.Plugin) (err error) {
    44  
    45  		gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
    46  
    47  		desc := descriptor.NewDescriptor()
    48  
    49  		if err := desc.LoadFromPlugin(gen); err != nil {
    50  			return err
    51  		}
    52  
    53  		if err := g.LoadFiles(gen, desc); err != nil {
    54  			return err
    55  		}
    56  
    57  		// Generate generates a *.pb.toolkit.go file containing Toolkit service definitions.
    58  		contentFiles, err := gentoolkit.New(desc).Generate(g.files)
    59  		if err != nil {
    60  			return err
    61  		}
    62  
    63  		// Write generated files to disk
    64  		for _, f := range contentFiles {
    65  			genFile := gen.NewGeneratedFile(f.GetName(), protogen.GoImportPath(f.GoPkg.Path))
    66  			if _, err := genFile.Write([]byte(f.GetContent())); err != nil {
    67  				return err
    68  			}
    69  		}
    70  
    71  		return nil
    72  	})
    73  
    74  	return nil
    75  }
    76  
    77  func (g *Generator) LoadFiles(gen *protogen.Plugin, desc *descriptor.Descriptor) (err error) {
    78  	g.files = make([]*descriptor.File, 0)
    79  	for _, f := range gen.Request.FileToGenerate {
    80  		file, err := desc.FindFile(f)
    81  		if err != nil {
    82  			return err
    83  		}
    84  		g.files = append(g.files, file)
    85  	}
    86  	return err
    87  }