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

Feature/separate files #492

Open
wants to merge 5 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
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,25 @@ example](examples/gradle).
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>[,default|source_relative]
--doc_opt=<FORMAT>|<TEMPLATE_FILENAME>,<OUT_FILENAME>[,default|source_relative][,default|separate_files]

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].

### `source_relative`

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

### `separate_files`

If the `separate_files` flag is specified, there will be one file outputted per input file and the second parameter,
`<OUT_FILENAME>`, will be used as the extension of the outputted files.

For example, the following will result in the outputted files `foo.md` and `bar.md` since `md` is passed as the second parameter.
```
--doc_opt=markdown,md,source_relative,separate_files foo.proto bar.proto
```

### 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 @@ -24,6 +24,9 @@ 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

EXAMPLE: Generate docs relative to source protos, one output file per input file
protoc --doc_out=. --doc_opt=html,html,source_relative,separate_files protos/*.proto

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

Expand Down
78 changes: 59 additions & 19 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type PluginOptions struct {
OutputFile string
ExcludePatterns []*regexp.Regexp
SourceRelative bool
SeparateFiles bool
}

// SupportedFeatures describes a flag setting for supported features.
Expand Down Expand Up @@ -51,19 +52,40 @@ func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGen
}

resp := new(plugin_go.CodeGeneratorResponse)

fdsGroup := groupProtosByDirectory(result, options.SourceRelative)
for dir, fds := range fdsGroup {
template := NewTemplate(fds)
if !options.SeparateFiles {
template := NewTemplate(fds)

output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}
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)),
})
} else {
for _, fd := range fds {
template := NewTemplate([]*protokit.FileDescriptor{fd})

resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(filepath.Join(dir, options.OutputFile)),
Content: proto.String(string(output)),
})
output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}

_, protoFilename := filepath.Split(fd.GetName())

filenameParts := strings.Split(protoFilename, ".")

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

resp.SupportedFeatures = proto.Uint64(SupportedFeatures)
Expand Down Expand Up @@ -107,14 +129,15 @@ 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>[,default|source_relative]:<EXCLUDE_PATTERN>,<EXCLUDE_PATTERN>*.
// The parameter (`--doc_opt`) must be of the format <TYPE|TEMPLATE_FILE>,<OUTPUT_FILE>[,default|source_relative][,default|separate_files]:<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,
SeparateFiles: false,
}

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

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

options.TemplateFile = parts[0]
options.OutputFile = path.Base(parts[1])

// Handle extra options
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)
extraOptions := parts[2:]

for i := range extraOptions {
switch i {
case 0: // Third option
switch extraOptions[i] {
case "source_relative":
options.SourceRelative = true
case "default":
options.SourceRelative = false
default:
return nil, fmt.Errorf("Invalid parameter: %s", params)
}
case 1: // Fourth option
switch extraOptions[i] {
case "separate_files":
options.SeparateFiles = true
case "default":
options.SeparateFiles = 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
62 changes: 62 additions & 0 deletions plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,24 @@ func TestParseOptionsForSourceRelative(t *testing.T) {
require.Equal(t, options.SourceRelative, false)
}

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

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

req.Parameter = proto.String("markdown,index.md,source_relative")
options, err = ParseOptions(req)
require.NoError(t, err)
require.Equal(t, options.SeparateFiles, 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 @@ -150,3 +168,47 @@ func TestRunPluginForSourceRelative(t *testing.T) {
require.NotEmpty(t, resp.File[0].GetContent())
require.NotEmpty(t, resp.File[1].GetContent())
}

func TestRunPluginForSeparateFilesSourceRelative(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,md,source_relative,separate_files")

plugin := new(Plugin)
resp, err := plugin.Generate(req)
require.NoError(t, err)
require.Len(t, resp.File, 3)
expected := map[string]int{"Booking.md": 1, "Vehicle.md": 1, "nested/Book.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.Contains(t, expected, resp.File[2].GetName())
delete(expected, resp.File[2].GetName())

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

func TestRunPluginForSeparateFilesNoSourceRelative(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,md,default,separate_files")

plugin := new(Plugin)
resp, err := plugin.Generate(req)
require.NoError(t, err)
require.Len(t, resp.File, 3)
expected := map[string]int{"Booking.md": 1, "Vehicle.md": 1, "Book.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.Contains(t, expected, resp.File[2].GetName())
delete(expected, resp.File[2].GetName())

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