Skip to content

Generate the docs relative to the source protos #399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/protoc-gen-doc/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ protoc --doc_out=. --doc_opt=html,index.html:google/*,somedir/* protos/*.proto
EXAMPLE: Use a custom template
protoc --doc_out=. --doc_opt=custom.tmpl,docs.txt protos/*.proto

EXAMPLE: Generate docs relative to source protos
protoc --doc_out=. --doc_opt=html,index.html,source_relative protos/*.proto

See https://github.com/pseudomuto/protoc-gen-doc for more details.
`

Expand Down
Binary file modified fixtures/fileset.pb
Binary file not shown.
2 changes: 1 addition & 1 deletion fixtures/generate.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package fixtures

//go:generate protoc --descriptor_set_out=fileset.pb --include_imports --include_source_info -I. -I../thirdparty Booking.proto Vehicle.proto
//go:generate protoc --descriptor_set_out=fileset.pb --include_imports --include_source_info -I. -I../thirdparty Booking.proto Vehicle.proto nested/Book.proto
36 changes: 36 additions & 0 deletions fixtures/nested/Book.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
syntax = "proto3";

package com.book;

message Book {
int64 isbn = 1;
string title = 2;
string author = 3;
}

message GetBookRequest {
int64 isbn = 1;
}

message GetBookViaAuthor {
string author = 1;
}

service BookService {
rpc GetBook (GetBookRequest) returns (Book) {}
rpc GetBooksViaAuthor (GetBookViaAuthor) returns (stream Book) {}
rpc GetGreatestBook (stream GetBookRequest) returns (Book) {}
rpc GetBooks (stream GetBookRequest) returns (stream Book) {}
}

message BookStore {
string name = 1;
map<int64, string> books = 2;
}

enum EnumSample {
option allow_alias = true;
UNKNOWN = 0;
STARTED = 1;
RUNNING = 1;
}
59 changes: 47 additions & 12 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io/ioutil"
"path"
"path/filepath"
"regexp"
"strings"

Expand All @@ -19,6 +20,7 @@ type PluginOptions struct {
TemplateFile string
OutputFile string
ExcludePatterns []*regexp.Regexp
SourceRelative bool
}

// Plugin describes a protoc code generate plugin. It's an implementation of Plugin from github.com/pseudomuto/protokit
Expand All @@ -33,7 +35,6 @@ func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGen
}

result := excludeUnwantedProtos(protokit.ParseCodeGenRequest(r), options.ExcludePatterns)
template := NewTemplate(result)

customTemplate := ""

Expand All @@ -45,21 +46,43 @@ func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGen

customTemplate = string(data)
}
resp := new(plugin_go.CodeGeneratorResponse)

output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}
fdsGroup := groupProtosByDirectory(result, options.SourceRelative)

resp := new(plugin_go.CodeGeneratorResponse)
resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(options.OutputFile),
Content: proto.String(string(output)),
})
for dir, fds := range fdsGroup {
template := NewTemplate(fds)

output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}

resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(filepath.Join(dir, options.OutputFile)),
Content: proto.String(string(output)),
})
}

return resp, nil
}

func groupProtosByDirectory(fds []*protokit.FileDescriptor, sourceRelative bool) map[string][]*protokit.FileDescriptor {
fdsGroup := make(map[string][]*protokit.FileDescriptor)

for _, fd := range fds {
dir := ""
if sourceRelative {
dir, _ = filepath.Split(fd.GetName())
}
if dir == "" {
dir = "./"
}
fdsGroup[dir] = append(fdsGroup[dir], fd)
}
return fdsGroup
}

func excludeUnwantedProtos(fds []*protokit.FileDescriptor, excludePatterns []*regexp.Regexp) []*protokit.FileDescriptor {
descs := make([]*protokit.FileDescriptor, 0)

Expand All @@ -80,13 +103,14 @@ OUTER:
// ParseOptions parses plugin options from a CodeGeneratorRequest. It does this by splitting the `Parameter` field from
// the request object and parsing out the type of renderer to use and the name of the file to be generated.
//
// The parameter (`--doc_opt`) must be of the format <TYPE|TEMPLATE_FILE>,<OUTPUT_FILE>:<EXCLUDE_PATTERN>,<EXCLUDE_PATTERN>*.
// The parameter (`--doc_opt`) must be of the format <TYPE|TEMPLATE_FILE>,<OUTPUT_FILE>[,default|source_relative]:<EXCLUDE_PATTERN>,<EXCLUDE_PATTERN>*.
// The file will be written to the directory specified with the `--doc_out` argument to protoc.
func ParseOptions(req *plugin_go.CodeGeneratorRequest) (*PluginOptions, error) {
options := &PluginOptions{
Type: RenderTypeHTML,
TemplateFile: "",
OutputFile: "index.html",
SourceRelative: false,
}

params := req.GetParameter()
Expand All @@ -112,12 +136,23 @@ func ParseOptions(req *plugin_go.CodeGeneratorRequest) (*PluginOptions, error) {
}

parts := strings.Split(params, ",")
if len(parts) != 2 {
if len(parts) < 2 || len(parts) > 3 {
return nil, fmt.Errorf("Invalid parameter: %s", params)
}

options.TemplateFile = parts[0]
options.OutputFile = path.Base(parts[1])
if len(parts) > 2 {
switch parts[2] {
case "source_relative":
options.SourceRelative = true
case "default":
options.SourceRelative = false
default:
return nil, fmt.Errorf("Invalid parameter: %s", params)
}
}
options.SourceRelative = len(parts) > 2 && parts[2] == "source_relative"

renderType, err := NewRenderType(options.TemplateFile)
if err == nil {
Expand Down
41 changes: 39 additions & 2 deletions plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
plugin_go "github.com/golang/protobuf/protoc-gen-go/plugin"
. "github.com/pseudomuto/protoc-gen-doc"
"github.com/stretchr/testify/require"
"github.com/pseudomuto/protokit/utils"
)

func TestParseOptionsForBuiltinTemplates(t *testing.T) {
Expand Down Expand Up @@ -46,6 +47,24 @@ func TestParseOptionsForCustomTemplate(t *testing.T) {
require.Equal(t, "output.md", options.OutputFile)
}

func TestParseOptionsForSourceRelative(t *testing.T) {
req := new(plugin_go.CodeGeneratorRequest)
req.Parameter = proto.String("markdown,index.md,source_relative")
options, err := ParseOptions(req)
require.NoError(t, err)
require.Equal(t, options.SourceRelative, true)

req.Parameter = proto.String("markdown,index.md,default")
options, err = ParseOptions(req)
require.NoError(t, err)
require.Equal(t, options.SourceRelative, false)

req.Parameter = proto.String("markdown,index.md")
options, err = ParseOptions(req)
require.NoError(t, err)
require.Equal(t, options.SourceRelative, false)
}

func TestParseOptionsForExcludePatterns(t *testing.T) {
req := new(plugin_go.CodeGeneratorRequest)
req.Parameter = proto.String(":google/*,notgoogle/*")
Expand All @@ -66,6 +85,7 @@ func TestParseOptionsWithInvalidValues(t *testing.T) {
"html",
"/some/path.tmpl",
"more,than,1,comma",
"markdown,index.md,unknown",
}

for _, value := range badValues {
Expand All @@ -78,7 +98,8 @@ func TestParseOptionsWithInvalidValues(t *testing.T) {
}

func TestRunPluginForBuiltinTemplate(t *testing.T) {
req := new(plugin_go.CodeGeneratorRequest)
set, _ := utils.LoadDescriptorSet("fixtures", "fileset.pb")
req := utils.CreateGenRequest(set, "Booking.proto", "Vehicle.proto", "nested/Book.proto")
req.Parameter = proto.String("markdown,/base/name/only/output.md")

plugin := new(Plugin)
Expand All @@ -90,7 +111,8 @@ func TestRunPluginForBuiltinTemplate(t *testing.T) {
}

func TestRunPluginForCustomTemplate(t *testing.T) {
req := new(plugin_go.CodeGeneratorRequest)
set, _ := utils.LoadDescriptorSet("fixtures", "fileset.pb")
req := utils.CreateGenRequest(set, "Booking.proto", "Vehicle.proto", "nested/Book.proto")
req.Parameter = proto.String("resources/html.tmpl,/base/name/only/output.html")

plugin := new(Plugin)
Expand All @@ -109,3 +131,18 @@ func TestRunPluginWithInvalidOptions(t *testing.T) {
_, err := plugin.Generate(req)
require.Error(t, err)
}

func TestRunPluginForSourceRelative(t *testing.T) {
set, _ := utils.LoadDescriptorSet("fixtures", "fileset.pb")
req := utils.CreateGenRequest(set, "Booking.proto", "Vehicle.proto", "nested/Book.proto")
req.Parameter = proto.String("markdown,index.md,source_relative")

plugin := new(Plugin)
resp, err := plugin.Generate(req)
require.NoError(t, err)
require.Len(t, resp.File, 2)
require.Equal(t, "index.md", resp.File[0].GetName())
require.Equal(t, "nested/index.md", resp.File[1].GetName())
require.NotEmpty(t, resp.File[0].GetContent())
require.NotEmpty(t, resp.File[1].GetContent())
}