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