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

Custom types #20

Open
wants to merge 6 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
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,63 @@ Then, in your project, add a dependency on the runtime library:

`elm install tiziano88/elm-protobuf`


## Options

Options can be passed to the plugin in the --elm_out value, with the following
syntax:

`protoc "--elm_out=option=value;option=value1,value2:."`

The valid options are:

- `excludeFile`: A list of files that should be ignored. Usefull to ignore a
proto2 file that is a dependency of the compiled file.

- `options`: A file to customize the output, see below

## Customize the output

The elm type used for each field is automatically determined, but can be
overridden by passing an option file to the plugin.

For example, if a message has a Uuid field, the proto definition will probably
be something like this:

```proto
message MyObject {
string id = 1;
string name = 2;
}
```

By adding an option file, it is possible to get a 'Maybe Uuid' field instead
of a string.

Write a yaml file with all the options, 'elm-proto-options.yaml':

```yaml
types:
Uuid.Uuid:
json:
encoder: Uuid.encode
decoder: Uuid.decoder

files:
my_proto_file.proto:
imports:
- Uuid
fields:
MyObject.id:
type: Uuid.Uuid
required: false
```

Pass the option file as a parameter to the plugin:

```
`protoc --elm_out='options=./elm-proto-options.yaml:.' my_proto_file.proto`
```
## References

https://developers.google.com/protocol-buffers/
Expand Down
19 changes: 17 additions & 2 deletions protoc-gen-elm/file_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,34 @@ import (
)

type FileGenerator struct {
w io.Writer
options Options
w io.Writer
// Used to avoid qualifying names in the same file.
inFileName string
indent uint
}

func NewFileGenerator(w io.Writer, inFileName string) *FileGenerator {
func NewFileGenerator(options Options, w io.Writer, inFileName string) *FileGenerator {
return &FileGenerator{
options: options,
w: w,
inFileName: inFileName,
}
}

func (fg *FileGenerator) FileOptions() FileOptions {
o, _ := fg.options.Files[fg.inFileName]
return o
}

func (fg *FileGenerator) FieldOptions(name string) *FieldOptions {
o := fg.FileOptions()
if fo, ok := o.Fields[name]; ok {
return &fo
}
return nil
}

func (fg *FileGenerator) In() {
fg.indent++
}
Expand Down
46 changes: 43 additions & 3 deletions protoc-gen-elm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/golang/protobuf/protoc-gen-go/generator"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"gopkg.in/yaml.v2"
)

var (
Expand Down Expand Up @@ -102,6 +103,38 @@ func main() {
inFile.SourceCodeInfo = nil
}

var options Options

if parameter := req.GetParameter(); parameter != "" {
list := strings.Split(parameter, ";")
for _, item := range list {
splitted := strings.Split(item, "=")
if len(splitted) != 2 {
log.Fatalf("Invalid parameter. Expected 'variable=value', got: '%s'", item)
}
switch splitted[0] {
case "excludeFile":
fileList := strings.Split(splitted[1], ",")
for _, name := range fileList {
excludedFiles[name] = true
}
case "options":
b, err := ioutil.ReadFile(splitted[1])
if err != nil {
log.Fatalf("Could not ready option file: %s", err)
}
if err := yaml.Unmarshal(b, &options); err != nil {
log.Fatalf("Could not decode the option file: %s", err)
}
log.Printf("Loaded options file: %s", splitted[1])

default:
log.Fatalf("Unknow parameter: %s", splitted[0])

}
}
}

log.Printf("Input data: %v", proto.MarshalTextString(req))

resp := &plugin.CodeGeneratorResponse{}
Expand All @@ -113,7 +146,7 @@ func main() {
log.Printf("Skipping well known type")
continue
}
outFile, err := processFile(inFile)
outFile, err := processFile(options, inFile)
if err != nil {
log.Fatalf("Could not process file: %v", err)
}
Expand All @@ -131,7 +164,7 @@ func main() {
}
}

func processFile(inFile *descriptor.FileDescriptorProto) (*plugin.CodeGeneratorResponse_File, error) {
func processFile(options Options, inFile *descriptor.FileDescriptorProto) (*plugin.CodeGeneratorResponse_File, error) {
if inFile.GetSyntax() != "proto3" {
return nil, fmt.Errorf("Only proto3 syntax is supported")
}
Expand All @@ -158,7 +191,7 @@ func processFile(inFile *descriptor.FileDescriptorProto) (*plugin.CodeGeneratorR
outFile.Name = proto.String(outFileName)

b := &bytes.Buffer{}
fg := NewFileGenerator(b, inFileName)
fg := NewFileGenerator(options, b, inFileName)

fg.GenerateModule(fullModuleName)
fg.GenerateComments(inFile)
Expand Down Expand Up @@ -237,6 +270,13 @@ func (fg *FileGenerator) GenerateImports() {
fg.P("")
fg.P("import Json.Decode as JD")
fg.P("import Json.Encode as JE")
o := fg.FileOptions()
if len(o.Imports) != 0 {
fg.P("")
for _, name := range o.Imports {
fg.P("import " + name)
}
}
}

func (fg *FileGenerator) GenerateEverything(prefix string, inMessage *descriptor.DescriptorProto) error {
Expand Down
38 changes: 32 additions & 6 deletions protoc-gen-elm/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ import (
"github.com/golang/protobuf/protoc-gen-go/descriptor"
)

func (fg *FileGenerator) isOptional(
msgName string, inField *descriptor.FieldDescriptorProto, fieldOptions *FieldOptions,
) bool {
return (inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_OPTIONAL) &&
(inField.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE) ||
(fieldOptions != nil && !fieldOptions.Required)

}

func (fg *FileGenerator) GenerateMessageDefinition(prefix string, inMessage *descriptor.DescriptorProto) error {
typeName := prefix + inMessage.GetName()

Expand All @@ -26,12 +35,15 @@ func (fg *FileGenerator) GenerateMessageDefinition(prefix string, inMessage *des
// Handled in the oneof only.
continue
}
fieldOptions := fg.FieldOptions(typeName + "." + inField.GetName())

optional := (inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_OPTIONAL) &&
(inField.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE)
optional := fg.isOptional(inMessage.GetName(), inField, fieldOptions)
repeated := inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED

fType := fieldElmType(inField)
if fieldOptions != nil {
fType = fieldOptions.Type
}

fName := elmFieldName(inField.GetName())
fNumber := inField.GetNumber()
Expand Down Expand Up @@ -90,12 +102,20 @@ func (fg *FileGenerator) GenerateMessageDecoder(prefix string, inMessage *descri
continue
}

optional := (inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_OPTIONAL) &&
(inField.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE)
fieldOptions := fg.FieldOptions(typeName + "." + inField.GetName())

optional := fg.isOptional(inMessage.GetName(), inField, fieldOptions)

repeated := inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED
d := fieldDecoderName(inField)
def := fieldDefaultValue(inField)

if fieldOptions != nil {
if t, ok := fg.options.Types[fieldOptions.Type]; ok && t.JSON.Decoder != "" {
d = t.JSON.Decoder
}
}

if repeated {
fg.P("|> repeated %q %s", jsonFieldName(inField), d)
} else {
Expand Down Expand Up @@ -145,10 +165,16 @@ func (fg *FileGenerator) GenerateMessageEncoder(prefix string, inMessage *descri
continue
}

optional := (inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_OPTIONAL) &&
(inField.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE)
fieldOptions := fg.FieldOptions(typeName + "." + inField.GetName())

optional := fg.isOptional(inMessage.GetName(), inField, fieldOptions)
repeated := inField.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED
d := fieldEncoderName(inField)
if fieldOptions != nil {
if t, ok := fg.options.Types[fieldOptions.Type]; ok && t.JSON.Encoder != "" {
d = t.JSON.Encoder
}
}
val := argName + "." + elmFieldName(inField.GetName())
def := fieldDefaultValue(inField)
if repeated {
Expand Down
31 changes: 31 additions & 0 deletions protoc-gen-elm/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

// EncDec defines a encoder and decoder
type EncDec struct {
Encoder string
Decoder string
}

// CustomType defines a custom type
type CustomType struct {
JSON EncDec
Default string
}

// FieldOptions overrides the data type of a field
type FieldOptions struct {
Type string
Required bool
}

// FileOptions contains file-specific options
type FileOptions struct {
Imports []string
Fields map[string]FieldOptions
}

// Options contains the code generator options
type Options struct {
Types map[string]CustomType
Files map[string]FileOptions
}