Skip to content
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

feat: source_relative #450

Merged
merged 3 commits into from
Aug 11, 2021
Merged
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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ All noteworthy changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) (as of Feb 2018)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased](https://github.com/pseudomuto/protoc-gen-doc/compare/v1.4.1...master)
## [Unreleased](https://github.com/pseudomuto/protoc-gen-doc/compare/v1.5.0...master)

## [v1.5.0](https://github.com/pseudomuto/protoc-gen-doc/compare/v1.4.1...v1.5.0)

* Add `source_relative` flag [#450](https://github.com/pseudomuto/protoc-gen-doc/pull/450)

## [v1.4.1](https://github.com/pseudomuto/protoc-gen-doc/compare/v1.3.2...v1.4.1)

Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ If you'd like to install this locally, you can `go get` it.
The plugin is invoked by passing the `--doc_out`, and `--doc_opt` options to the `protoc` compiler. The option has the
following format:

--doc_opt=<FORMAT>|<TEMPLATE_FILENAME>,<OUT_FILENAME>
--doc_opt=<FORMAT>|<TEMPLATE_FILENAME>,<OUT_FILENAME>[,default|source_relative]

The format may be one of the built-in ones ( `docbook`, `html`, `markdown` or `json`)
or the name of a file containing a custom [Go template][gotemplate].

If the `source_relative` flag is specified, the output file is written in the same relative directory as the input file.

### Using the Docker Image (Recommended)

The docker image has two volumes: `/out` and `/protos` which are the directory to write the documentation to and the
Expand Down
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,6 +1,6 @@
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

// Compiling proto3 optional fields requires using protoc >=3.12.x and passing the --experimental_allow_proto3_optional flag.
// Rather than use this flag to compile all of the protocol buffers (which would eliminate test coverage for descriptors
Expand Down
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;
}
63 changes: 49 additions & 14 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
}

// SupportedFeatures describes a flag setting for supported features.
Expand All @@ -36,7 +38,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 @@ -49,21 +50,43 @@ func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGen
customTemplate = string(data)
}

output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
resp := new(plugin_go.CodeGeneratorResponse)
fdsGroup := groupProtosByDirectory(result, options.SourceRelative)
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)),
})
}

resp := new(plugin_go.CodeGeneratorResponse)
resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(options.OutputFile),
Content: proto.String(string(output)),
})
resp.SupportedFeatures = proto.Uint64(SupportedFeatures)

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 @@ -84,13 +107,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",
Type: RenderTypeHTML,
TemplateFile: "",
OutputFile: "index.html",
SourceRelative: false,
}

params := req.GetParameter()
Expand All @@ -116,12 +140,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
45 changes: 43 additions & 2 deletions plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/golang/protobuf/proto"
plugin_go "github.com/golang/protobuf/protoc-gen-go/plugin"
. "github.com/pseudomuto/protoc-gen-doc"
"github.com/pseudomuto/protokit/utils"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -34,6 +35,24 @@ func TestParseOptionsForBuiltinTemplates(t *testing.T) {
}
}

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 TestParseOptionsForCustomTemplate(t *testing.T) {
req := new(plugin_go.CodeGeneratorRequest)
req.Parameter = proto.String("/path/to/template.tmpl,/base/name/only/output.md")
Expand Down Expand Up @@ -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,22 @@ 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)
expected := map[string]int{"index.md": 1, "nested/index.md": 1}
require.Contains(t, expected, resp.File[0].GetName())
delete(expected, resp.File[0].GetName())
require.Contains(t, expected, resp.File[1].GetName())
delete(expected, resp.File[1].GetName())

require.NotEmpty(t, resp.File[0].GetContent())
require.NotEmpty(t, resp.File[1].GetContent())
}