helpers

package
v1.13.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2022 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package pgghelpers provides members for internal use in grpc-gateway.

Index

Constants

This section is empty.

Variables

View Source
var ProtoHelpersFuncMap = tmpl.FuncMap{
	"string": func(i interface {
		String() string
	}) string {
		return i.String()
	},
	"json": func(v interface{}) string {
		a, err := json.Marshal(v)
		if err != nil {
			return err.Error()
		}
		return string(a)
	},
	"prettyjson": func(v interface{}) string {
		a, err := json.MarshalIndent(v, "", "  ")
		if err != nil {
			return err.Error()
		}
		return string(a)
	},
	"makeimport": func(imp ...string) string {
		prefix := ""
		i := ""
		if len(imp) > 0 {
			i = imp[0]
		}
		if len(imp) > 1 {
			prefix = imp[1]
		}
		if len(prefix) == 0 {
			return fmt.Sprintf("\"%s\"", i)
		}
		return fmt.Sprintf("%s \"%s\"", prefix, i)
	},
	"makeimports": func(dependencies []string, imps []interface{}) string {
		impmap := make(map[string]string, len(imps)*2)
		for _, dep := range dependencies {
			gopkg := getProtoFile(dep).GoPkg
			key := gopkg.Path
			val := gopkg.Alias
			wrap := ""
			if !strings.Contains(key, "\"") {
				wrap = "\""
			}
			key = fmt.Sprintf("%s%s%s", wrap, key, wrap)
			impmap[key] = val
		}
		for _, itimp := range imps {
			timp := fmt.Sprintf("%s", itimp)
			imp := []string{"", timp}
			if strings.Contains(timp, " ") {
				imp = strings.Split(timp, " ")
			}
			wrap := ""
			if !strings.Contains(imp[1], "\"") {
				wrap = "\""
			}
			imp[1] = fmt.Sprintf("%s%s%s", wrap, imp[1], wrap)
			impmap[imp[1]] = imp[0]
		}

		r := make([]string, 0, len(impmap))
		for k := range impmap {
			r = append(r, k)
		}
		sort.Strings(r)
		var i string
		for _, ir := range r {
			prefix := impmap[ir]
			line := fmt.Sprintf("%s %s", prefix, ir)
			if len(prefix) == 0 {
				line = fmt.Sprintf("%s", ir)
			}
			if len(i) == 0 {
				i = fmt.Sprintf("%s", line)
			} else {
				i = fmt.Sprintf("%s%s%s", i, "\n\t", line)
			}

		}

		return i
	},
	"splitArray": func(sep string, s string) []interface{} {
		var r []interface{}
		t := strings.Split(s, sep)
		for i := range t {
			if t[i] != "" {
				r = append(r, t[i])
			}
		}
		return r
	},
	"joinSort": func(sep string, s ...string) string {
		res := ""

		sort.Strings(s)
		for _, str := range s {
			if len(res) == 0 {
				res = fmt.Sprintf("%s", str)
			} else {
				res = fmt.Sprintf("%s%s%s", res, sep, str)
			}
		}
		return res
	},
	"first": func(a []string) string {
		return a[0]
	},
	"last": func(a []string) string {
		return a[len(a)-1]
	},
	"concat": func(a string, b ...string) string {
		return strings.Join(append([]string{a}, b...), "")
	},
	"join": func(sep string, a ...string) string {
		return strings.Join(a, sep)
	},
	"upperFirst": func(s string) string {
		return strings.ToUpper(s[:1]) + s[1:]
	},
	"lowerFirst": func(s string) string {
		return strings.ToLower(s[:1]) + s[1:]
	},
	"camelCase": func(s string) string {
		if len(s) > 1 {
			return xstrings.ToCamelCase(s)
		}

		return strings.ToUpper(s[:1])
	},
	"lowerCamelCase": func(s string) string {
		if len(s) > 1 {
			s = xstrings.ToCamelCase(s)
		}

		return strings.ToLower(s[:1]) + s[1:]
	},
	"upperCase": func(s string) string {
		return strings.ToUpper(s)
	},
	"kebabCase": func(s string) string {
		return strings.Replace(xstrings.ToSnakeCase(s), "_", "-", -1)
	},
	"contains": func(sub, s string) bool {
		return strings.Contains(s, sub)
	},
	"trimstr": func(cutset, s string) string {
		return strings.Trim(s, cutset)
	},
	"index": func(array interface{}, i int) interface{} {
		slice := reflect.ValueOf(array)
		if slice.Kind() != reflect.Slice {
			panic("Error in index(): given a non-slice type")
		}
		if i < 0 || i >= slice.Len() {
			panic("Error in index(): index out of bounds")
		}
		return slice.Index(i).Interface()
	},
	"add": func(a int, b int) int {
		return a + b
	},
	"subtract": func(a int, b int) int {
		return a - b
	},
	"multiply": func(a int, b int) int {
		return a * b
	},
	"divide": func(a int, b int) int {
		if b == 0 {
			panic("psssst ... little help here ... you cannot divide by 0")
		}
		return a / b
	},

	"snakeCase":                    xstrings.ToSnakeCase,
	"getProtoFile":                 getProtoFile,
	"getMessageType":               getMessageType,
	"getMessageTypeWithPackage":    getMessageTypeWithPackage,
	"getEnumValue":                 getEnumValue,
	"isFieldMessage":               isFieldMessage,
	"isFieldMessageTimeStamp":      isFieldMessageTimeStamp,
	"isFieldRepeated":              isFieldRepeated,
	"haskellType":                  haskellType,
	"goType":                       goType,
	"goZeroValue":                  goZeroValue,
	"goTypeWithPackage":            goTypeWithPackage,
	"goTypeWithGoPackage":          goTypeWithGoPackage,
	"jsType":                       jsType,
	"jsSuffixReserved":             jsSuffixReservedKeyword,
	"namespacedFlowType":           namespacedFlowType,
	"httpVerb":                     httpVerb,
	"httpPath":                     httpPath,
	"httpPathsAdditionalBindings":  httpPathsAdditionalBindings,
	"httpBody":                     httpBody,
	"shortType":                    shortType,
	"urlHasVarsFromMessage":        urlHasVarsFromMessage,
	"lowerGoNormalize":             lowerGoNormalize,
	"goNormalize":                  goNormalize,
	"leadingComment":               leadingComment,
	"trailingComment":              trailingComment,
	"leadingDetachedComments":      leadingDetachedComments,
	"stringFileOptionsExtension":   stringFileOptionsExtension,
	"stringMessageExtension":       stringMessageExtension,
	"stringFieldExtension":         stringFieldExtension,
	"int64FieldExtension":          int64FieldExtension,
	"int64MessageExtension":        int64MessageExtension,
	"stringMethodOptionsExtension": stringMethodOptionsExtension,
	"boolMethodOptionsExtension":   boolMethodOptionsExtension,
	"boolMessageExtension":         boolMessageExtension,
	"boolFieldExtension":           boolFieldExtension,
	"isFieldMap":                   isFieldMap,
	"fieldMapKeyType":              fieldMapKeyType,
	"fieldMapValueType":            fieldMapValueType,
	"replaceDict":                  replaceDict,
	"setStore":                     setStore,
	"getStore":                     getStore,
	"goPkg":                        goPkg,
	"goPkgLastElement":             goPkgLastElement,
	"cppType":                      cppType,
	"cppTypeWithPackage":           cppTypeWithPackage,
	"rustType":                     rustType,
	"rustTypeWithPackage":          rustTypeWithPackage,
}

Functions

func LoadComments added in v1.13.0

func LoadComments(file *descriptor.FileDescriptorProto)

func SetRegistry

func SetRegistry(reg *Registry)

Types

type Ast

type Ast struct {
	BuildDate      time.Time                          `json:"build-date"`
	BuildHostname  string                             `json:"build-hostname"`
	BuildUser      string                             `json:"build-user"`
	GoPWD          string                             `json:"go-pwd,omitempty"`
	PWD            string                             `json:"pwd"`
	Debug          bool                               `json:"debug"`
	DestinationDir string                             `json:"destination-dir"`
	File           *descriptor.FileDescriptorProto    `json:"file"`
	RawFilename    string                             `json:"raw-filename"`
	Filename       string                             `json:"filename"`
	TemplateDir    string                             `json:"template-dir"`
	Service        *descriptor.ServiceDescriptorProto `json:"service"`
	Enum           []*descriptor.EnumDescriptorProto  `json:"enum"`
	Index          int                                `json:"index"`
}

type CommentDirective added in v1.13.0

type CommentDirective struct {
	Directive string
	Params    string
	Value     string
	Type      string
}

type Enum

type Enum struct {
	// File is the file where the enum is defined
	File *File
	// Outers is a list of outer messages if this enum is a nested type.
	Outers []string
	*descriptor.EnumDescriptorProto

	Index int
}

Enum describes a protocol buffer enum types

func (*Enum) FQEN

func (e *Enum) FQEN() string

FQEN returns a fully qualified enum name of this enum.

func (*Enum) GoType

func (e *Enum) GoType(currentPackage string) string

GoType returns a go type name for the enum type. It prefixes the type name with the package alias if its belonging package is not "currentPackage".

type Field

type Field struct {
	// Message is the message type which this field belongs to.
	Message *Message
	// FieldMessage is the message type of the field.
	FieldMessage *Message
	*descriptor.FieldDescriptorProto
}

Field wraps descriptor.FieldDescriptorProto for richer features.

type FieldPath

type FieldPath []FieldPathComponent

FieldPath is a path to a field from a request message.

func (FieldPath) AssignableExpr

func (p FieldPath) AssignableExpr(msgExpr string) string

AssignableExpr is an assignable expression in Go to be used to assign a value to the target field. It starts with "msgExpr", which is the go expression of the method request object.

func (FieldPath) IsNestedProto3

func (p FieldPath) IsNestedProto3() bool

IsNestedProto3 indicates whether the FieldPath is a nested Proto3 path.

func (FieldPath) String

func (p FieldPath) String() string

String returns a string representation of the field path.

type FieldPathComponent

type FieldPathComponent struct {
	// Name is a name of the proto field which this component corresponds to.
	// TODO(yugui) is this necessary?
	Name string
	// Target is the proto field which this component corresponds to.
	Target *Field
}

FieldPathComponent is a path component in FieldPath

func (FieldPathComponent) AssignableExpr

func (c FieldPathComponent) AssignableExpr() string

AssignableExpr returns an assignable expression in go for this field.

func (FieldPathComponent) ValueExpr

func (c FieldPathComponent) ValueExpr() string

ValueExpr returns an expression in go for this field.

type File

type File struct {
	*descriptor.FileDescriptorProto
	// GoPkg is the go package of the go file generated from this file..
	GoPkg GoPackage
	// Messages is the list of messages defined in this file.
	Messages []*Message
	// Enums is the list of enums defined in this file.
	Enums []*Enum
	// Services is the list of services defined in this file.
	Services []*Service
	// Directives is the mappings of elements to comment-directives in this file
	Directives map[interface{}][]CommentDirective
}

File wraps descriptor.FileDescriptorProto for richer features.

type GenericTemplateBasedEncoder

type GenericTemplateBasedEncoder struct {
	// contains filtered or unexported fields
}

func NewGenericServiceTemplateBasedEncoder

func NewGenericServiceTemplateBasedEncoder(templateDir string, service *descriptor.ServiceDescriptorProto, file *descriptor.FileDescriptorProto, debug bool, destinationDir string, index int) (e *GenericTemplateBasedEncoder)

func NewGenericTemplateBasedEncoder

func NewGenericTemplateBasedEncoder(templateDir string, file *descriptor.FileDescriptorProto, debug bool, destinationDir string, index int) (e *GenericTemplateBasedEncoder)

func (*GenericTemplateBasedEncoder) Files

type GoImportPath added in v1.12.2

type GoImportPath string

A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf".

func (GoImportPath) String added in v1.12.2

func (p GoImportPath) String() string

type GoPackage

type GoPackage struct {
	// Path is the package path to the package.
	Path string
	// Name is the package name of the package
	Name string
	// Alias is an alias of the package unique within the current invokation of grpc-gateway generator.
	Alias string
}

GoPackage represents a golang package

func (GoPackage) Standard

func (p GoPackage) Standard() bool

Standard returns whether the import is a golang standard package.

func (GoPackage) String

func (p GoPackage) String() string

String returns a string representation of this package in the form of import line in golang.

type GoPackageName added in v1.12.2

type GoPackageName string

A GoPackageName is the name of a Go package. e.g., "protobuf".

type Message

type Message struct {
	// File is the file where the message is defined
	File *File
	// Outers is a list of outer messages if this message is a nested type.
	Outers []string
	*descriptor.DescriptorProto
	Fields []*Field

	// Index is proto path index of this message in File.
	Index int
}

Message describes a protocol buffer message types

func (*Message) FQMN

func (m *Message) FQMN() string

FQMN returns a fully qualified message name of this message.

func (*Message) GoType

func (m *Message) GoType(currentPackage string) string

GoType returns a go type name for the message type. It prefixes the type name with the package alias if its belonging package is not "currentPackage".

type Method

type Method struct {
	// Service is the service which this method belongs to.
	Service *Service
	*descriptor.MethodDescriptorProto

	// RequestType is the message type of requests to this method.
	RequestType *Message
	// ResponseType is the message type of responses from this method.
	ResponseType *Message
}

Method wraps descriptor.MethodDescriptorProto for richer features.

func (*Method) FQMN

func (m *Method) FQMN() string

FQMN returns a fully qualified rpc method name of this method.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is a registry of information extracted from plugin.CodeGeneratorRequest.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns a new Registry.

func (*Registry) AddPkgMap

func (r *Registry) AddPkgMap(file, protoPkg string)

AddPkgMap adds a mapping from a .proto file to proto package name.

func (*Registry) GetAllFQENs

func (r *Registry) GetAllFQENs() []string

GetAllFQENs returns a list of all FQENs

func (*Registry) GetAllFQMNs

func (r *Registry) GetAllFQMNs() []string

GetAllFQMNs returns a list of all FQMNs

func (*Registry) IsIncludePackageInTags

func (r *Registry) IsIncludePackageInTags() bool

IsIncludePackageInTags checks whether the package name defined in the `package` directive in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation.

func (*Registry) Load

func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error

Load loads definitions of services, methods, messages, enumerations and fields from "req".

func (*Registry) LookupEnum

func (r *Registry) LookupEnum(location, name string) (*Enum, error)

LookupEnum looks up a enum type by "name". It tries to resolve "name" from "location" if "name" is a relative enum name.

func (*Registry) LookupFile

func (r *Registry) LookupFile(name string) (*File, error)

LookupFile looks up a file by name.

func (*Registry) LookupMsg

func (r *Registry) LookupMsg(location, name string) (*Message, error)

LookupMsg looks up a message type by "name". It tries to resolve "name" from "location" if "name" is a relative message name.

func (*Registry) ReserveGoPackageAlias

func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error

ReserveGoPackageAlias reserves the unique alias of go package. If succeeded, the alias will be never used for other packages in generated go files. If failed, the alias is already taken by another package, so you need to use another alias for the package in your go files.

func (*Registry) SetImportPath

func (r *Registry) SetImportPath(importPath string)

SetImportPath registers the importPath which is used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored.

func (*Registry) SetIncludePackageInTags

func (r *Registry) SetIncludePackageInTags(allow bool)

SetIncludePackageInTags controls whether the package name defined in the `package` directive in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation.

func (*Registry) SetPrefix

func (r *Registry) SetPrefix(prefix string)

SetPrefix registers the prefix to be added to go package paths generated from proto package names.

type RequestFileSorter added in v1.12.3

type RequestFileSorter struct {
	Request *plugingo.CodeGeneratorRequest
}

func (RequestFileSorter) Len added in v1.12.3

func (r RequestFileSorter) Len() int

func (RequestFileSorter) Less added in v1.12.3

func (r RequestFileSorter) Less(i, j int) bool

func (RequestFileSorter) Swap added in v1.12.3

func (r RequestFileSorter) Swap(i, j int)

type ResponseSorter added in v1.12.3

type ResponseSorter []*plugingo.CodeGeneratorResponse_File

func (ResponseSorter) Len added in v1.12.3

func (a ResponseSorter) Len() int

func (ResponseSorter) Less added in v1.12.3

func (a ResponseSorter) Less(i, j int) bool

func (ResponseSorter) Swap added in v1.12.3

func (a ResponseSorter) Swap(i, j int)

type Service

type Service struct {
	// File is the file where this service is defined.
	File *File
	*descriptor.ServiceDescriptorProto
	// Methods is the list of methods defined in this service.
	Methods []*Method
}

Service wraps descriptor.ServiceDescriptorProto for richer features.

func (*Service) FQSN

func (s *Service) FQSN() string

FQSN returns the fully qualified service name of this service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL