2016-11-04 21:45:25 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2016-11-06 17:20:57 +01:00
|
|
|
"path/filepath"
|
|
|
|
|
2016-11-04 21:45:25 +01:00
|
|
|
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
|
|
|
"github.com/golang/protobuf/protoc-gen-go/plugin"
|
2016-11-06 17:20:57 +01:00
|
|
|
"github.com/kr/fs"
|
2016-11-04 21:45:25 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type GenericTemplateBasedEncoder struct {
|
2016-11-06 17:20:57 +01:00
|
|
|
templateDir string
|
|
|
|
service *descriptor.ServiceDescriptorProto
|
|
|
|
file *descriptor.FileDescriptorProto
|
2016-11-04 21:45:25 +01:00
|
|
|
}
|
|
|
|
|
2016-11-06 17:20:57 +01:00
|
|
|
func NewGenericTemplateBasedEncoder(templateDir string, service *descriptor.ServiceDescriptorProto, file *descriptor.FileDescriptorProto) (e *GenericTemplateBasedEncoder) {
|
2016-11-04 21:45:25 +01:00
|
|
|
e = &GenericTemplateBasedEncoder{
|
2016-11-06 17:20:57 +01:00
|
|
|
service: service,
|
|
|
|
file: file,
|
|
|
|
templateDir: templateDir,
|
2016-11-04 21:45:25 +01:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:20:57 +01:00
|
|
|
func (e *GenericTemplateBasedEncoder) templates() ([]string, error) {
|
|
|
|
filenames := []string{}
|
|
|
|
|
|
|
|
walker := fs.Walk(e.templateDir)
|
|
|
|
for walker.Step() {
|
|
|
|
if err := walker.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if walker.Stat().IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if filepath.Ext(walker.Path()) != ".tmpl" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
rel, err := filepath.Rel(e.templateDir, walker.Path())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
filenames = append(filenames, rel)
|
|
|
|
}
|
|
|
|
|
|
|
|
return filenames, nil
|
|
|
|
}
|
|
|
|
|
2016-11-04 21:45:25 +01:00
|
|
|
func (e *GenericTemplateBasedEncoder) Files() []*plugin_go.CodeGeneratorResponse_File {
|
2016-11-06 17:20:57 +01:00
|
|
|
files := []*plugin_go.CodeGeneratorResponse_File{}
|
|
|
|
|
|
|
|
templates, err := e.templates()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, templateFilename := range templates {
|
|
|
|
filename := templateFilename[0 : len(templateFilename)-len(".tmpl")]
|
|
|
|
|
|
|
|
content := "hello world"
|
|
|
|
files = append(files, &plugin_go.CodeGeneratorResponse_File{
|
2016-11-04 21:45:25 +01:00
|
|
|
Content: &content,
|
2016-11-06 17:20:57 +01:00
|
|
|
Name: &filename,
|
|
|
|
})
|
2016-11-04 21:45:25 +01:00
|
|
|
}
|
2016-11-06 17:20:57 +01:00
|
|
|
|
|
|
|
return files
|
2016-11-04 21:45:25 +01:00
|
|
|
}
|