github.com/nytimes/openapi2proto@v0.2.1/transpiler.go (about)

     1  package openapi2proto
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/NYTimes/openapi2proto/compiler"
     7  	"github.com/NYTimes/openapi2proto/openapi"
     8  	"github.com/NYTimes/openapi2proto/protobuf"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  // Transpile is a convenience function that takes an OpenAPI
    13  // spec file and transpiles it into a Protocol Buffers v3 declaration,
    14  // which is written to `dst`.
    15  //
    16  // Options to the compiler and encoder can be passed using
    17  // `WithCompilerOptions` and `WithEncoderOptions`, respectively
    18  //
    19  // For more control, use `openapi`, `compiler`, and `protobuf`
    20  // packages directly.
    21  func Transpile(dst io.Writer, srcFn string, options ...Option) error {
    22  	var encoderOptions []protobuf.Option
    23  	var compilerOptions []compiler.Option
    24  
    25  	for _, o := range options {
    26  		switch o.Name() {
    27  		case optkeyEncoderOptions:
    28  			encoderOptions = o.Value().([]protobuf.Option)
    29  		case optkeyCompilerOptions:
    30  			compilerOptions = o.Value().([]compiler.Option)
    31  		}
    32  	}
    33  
    34  	s, err := openapi.LoadFile(srcFn)
    35  	if err != nil {
    36  		return errors.Wrap(err, `failed to load OpenAPI spec`)
    37  	}
    38  
    39  	p, err := compiler.Compile(s, compilerOptions...)
    40  	if err != nil {
    41  		return errors.Wrap(err, `failed to compile OpenAPI spec to Protocol buffers`)
    42  	}
    43  
    44  	if err := protobuf.NewEncoder(dst, encoderOptions...).Encode(p); err != nil {
    45  		return errors.Wrap(err, `failed to encode protocol buffers to text`)
    46  	}
    47  
    48  	return nil
    49  }