protoc

package
v0.0.0-...-5428336 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2024 License: Apache-2.0 Imports: 25 Imported by: 1

Documentation

Index

Examples

Constants

View Source
const (
	ResolverLangName = "protobuf"
	// ResolverImpLangPrivateKey stores the implementation language override.
	ResolverImpLangPrivateKey = "_protobuf_imp_lang"
	UnresolvedDepsPrivateKey  = "_unresolved_deps"
)
View Source
const (
	// RuleDirective is the directive for toggling rule generation.
	RuleDirective = "proto_rule"
	// LanguageDirective tells gazelle which languages a package should
	// produce and how it is configured.
	LanguageDirective = "proto_language"
	// PluginDirective created an association between proto_lang
	// and the label of a proto_plugin.
	PluginDirective = "proto_plugin"
)
View Source
const (
	// ProtoLibraryKey stores the ProtoLibrary implementation for a rule.
	ProtoLibraryKey = "_proto_library"
)
View Source
const (
	// ResolveProvidesKey is the key expected to store a string slice that
	// informs what imports a rule provides.
	ResolveProvidesKey = "_resolve_provides"
)

Variables

View Source
var (
	ErrNoLabel = errors.New("no label")
)
View Source
var ErrUnknownPlugin = errors.New("unknown plugin")

ErrUnknownPlugin is the error returned when a plugin is not known.

View Source
var ErrUnknownRule = errors.New("unknown rule")

ErrUnknownRule is the error returned when a rule is not known.

Functions

func Always

func Always(file *File) bool

Always is a file predicate function that always returns true.

func DeduplicateAndSort

func DeduplicateAndSort(in []string) (out []string)

DeduplicateAndSort removes duplicate entries and sorts the list

func FlatMapFiles

func FlatMapFiles(apply func(file *File) []string, filter func(file *File) bool, files ...*File) []string

FlatMapFiles is a utility function intended for use in computing a list of output files for a given proto_library. The given apply function is executed foreach file that passes the filter function, and flattens the strings into a single list.

func ForIntent

func ForIntent(in map[string]bool, want bool) []string

ForIntent reduces a dict to a list by the given intent.

func GetKeptFileRuleAttrString

func GetKeptFileRuleAttrString(file *rule.File, r *rule.Rule, name string) string

GetKeptFileRuleAttrString returns the value of the rule attribute IFF the backing File rule attribute has a '# keep' comment on it.

func GetNamedOption

func GetNamedOption(options []proto.Option, name string) (string, bool)

GetNamedOption returns the value of an option. If the option is not found, the bool return value is false.

func GetPluginLabels

func GetPluginLabels(plugins []*PluginConfiguration) []string

GetPluginLabels returns the list of labels strings for a list of plugins.

func GetPluginOptions

func GetPluginOptions(plugins []*PluginConfiguration, r *rule.Rule, from label.Label) map[string][]string

GetPluginOptions returns the list of options by plugin.

func GetPluginOuts

func GetPluginOuts(plugins []*PluginConfiguration) map[string]string

GetPluginOuts returns the output location by plugin.

func GoPackageOption

func GoPackageOption(options []proto.Option) (string, string, bool)

GoPackageOption is a utility function to seek for the go_package option and split it. If present the return values will be populated with the importpath and alias (e.g. github.com/foo/bar/v1;bar -> "github.com/foo/bar/v1", "bar"). If the option was not found the bool return argument is false.

func GoPackagePath

func GoPackagePath(pkg string) string

GoPackagePath replaces dots with forward slashes.

func HasMessageOrEnum

func HasMessageOrEnum(file *File) bool

HasMessageOrEnum is a file predicate function checks if any of the given file has a message or an enum.

func HasMessagesOrEnums

func HasMessagesOrEnums(files ...*File) bool

HasMessagesOrEnums checks if any of the given files has a message or an enum.

func HasService

func HasService(file *File) bool

HasService is a file predicate function that tests if any of the given file has a message or an enum.

func HasServices

func HasServices(files ...*File) bool

HasServices checks if any of the given files has a service.

func ImportPrefixRelativeFileNameWithExtensions

func ImportPrefixRelativeFileNameWithExtensions(stripImportPrefix, reldir string, exts ...string) func(f *File) []string

ImportPrefixRelativeFileNameWithExtensions returns a function that computes the name of a predicted generated file. In this case, first RelativeFileNameWithExtensions is applied, then stripImportPrefix is removed from the predicted filename.

func IsProtoFile

func IsProtoFile(filename string) bool

IsProtoFile returns true if the file extension looks like it should contain protobuf definitions.

func LoadYConfigFile

func LoadYConfigFile(c *config.Config, cfg *PackageConfig, filename string) error

func MakeStringDict

func MakeStringDict(in map[string]string) build.Expr

func MakeStringListDict

func MakeStringListDict(in map[string][]string) build.Expr

func PackageFileNameWithExtensions

func PackageFileNameWithExtensions(exts ...string) func(f *File) []string

PackageFileNameWithExtensions returns a function that computes the name of a predicted generated file having the given extension(s). If the proto package is defined, the output file will be in the corresponding directory.

func ProtoFilesImportSpecsForKind

func ProtoFilesImportSpecsForKind(kind string, files []*File) []resolve.ImportSpec

ProtoLibraryImportSpecsForKind generates an ImportSpec for each file in the set of given proto_library.

func ProtoLibraryImportSpecsForKind

func ProtoLibraryImportSpecsForKind(kind string, libs ...ProtoLibrary) []resolve.ImportSpec

ProtoLibraryImportSpecsForKind generates an ImportSpec for each file in the set of given proto_library.

func RegisterStarlarkPlugin

func RegisterStarlarkPlugin(c *config.Config, starlarkPlugin string) error

func RegisterStarlarkRule

func RegisterStarlarkRule(c *config.Config, starlarkRule string) error

func RelativeFileNameWithExtensions

func RelativeFileNameWithExtensions(reldir string, exts ...string) func(f *File) []string

RelativeFileNameWithExtensions returns a function that computes the name of a predicted generated file having the given extension(s) relative to the given dir.

func ResolveFileRewrites

func ResolveFileRewrites(rewrites []Rewrite, file *File) []string

ResolveFileRewrites takes a proto File object and returns a list of matching rewrites of the import statements. The list if neither sorted or deduplicated.

func ResolveImports

func ResolveImports(resolver ImportResolver, lang, impLang string, imports []string) []label.Label

ResolveImports is a utility function that returns a matching list of labels for the given import list.

func ResolveImportsString

func ResolveImportsString(resolver ImportResolver, rel, kind, impLang string, imports []string) []string

ResolveImportsString is a utility function that returns a matching list of labels for the given import list.

func ResolveLibraryRewrites

func ResolveLibraryRewrites(rewrites []Rewrite, library ProtoLibrary) []string

ResolveLibraryRewrites takes a proto_library object and returns a list of matching rewrites of all the the transitive import statements.

func ResolveRewrites

func ResolveRewrites(rewrites []Rewrite, in string) string

ResolveRewrites takes a list of rewrite rules and returns the first match of the given input string.

func StripRel

func StripRel(rel string, filename string) string

StripRel removes the rel prefix from a filename (if has matching prefix)

func ToPascalCase

func ToPascalCase(s string) string

ToPascalCase converts a string to PascalCase.

Splits on '-', '_', ' ', '\t', '\n', '\r'. Uppercase letters will stay uppercase,

Types

type DepsResolver

type DepsResolver func(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imports []string, from label.Label)

func ResolveDepsAttr

func ResolveDepsAttr(attrName string, excludeWkt bool) DepsResolver

ResolveDepsAttr returns a function that implements the DepsResolver interface. This function resolves dependencies for a given rule attribute name (typically "deps"); if there is a non-empty list of resolved dependencies, the rule attribute will be overrwritten/modified by this function (excluding duplicates, sorting applied). The "from" argument represents the rule being resolved (whose state is the *rule.Rule argument). The "imports" list represents the list of imports that was originally returned by the GenerateResponse.Imports (typically in via a private attr GazelleImportsKey), and holds the values of all the import statements (e.g. "google/protobuf/descriptor.proto") of the ProtoLibrary used to generate the rule. Special handling is provided for well-known types, which can be excluded using the `excludeWkt` argument. Actual resolution for an individual import is delegated to the `resolveAnyKind` function.

type File

type File struct {
	Dir      string // e.g. "path/to/package/"
	Basename string // e.g. "foo.proto"
	Name     string // e.g. "foo"
	// contains filtered or unexported fields
}

File represents a proto file that is discovered in a package.

func NewFile

func NewFile(dir, basename string) *File

NewFile takes the package directory and base name of the file (e.g. 'foo.proto') and constructs File

func (*File) EnumOptions

func (f *File) EnumOptions() []proto.Option

EnumOptions returns the list of EnumOptions defined in the proto file.

func (*File) Enums

func (f *File) Enums() []proto.Enum

Enums returns the list of Enums defined in the proto file.

func (*File) HasEnumOption

func (f *File) HasEnumOption(name string) bool

HasEnumOption returns true if the proto file has at least one enum or enum field annotated with the given named field extension.

func (*File) HasEnums

func (f *File) HasEnums() bool

HasEnums returns true if the proto file has at least one enum.

func (*File) HasMessages

func (f *File) HasMessages() bool

HasMessages returns true if the proto file has at least one message.

func (*File) HasRPCOption

func (f *File) HasRPCOption(name string) bool

HasRPCOption returns true if the proto file has at least one rpc annotated with the given named field extension.

func (*File) HasRPCs

func (f *File) HasRPCs() bool

HasRPCs returns true if the proto file has at least one service.

func (*File) HasServices

func (f *File) HasServices() bool

HasServices returns true if the proto file has at least one service.

func (*File) Imports

func (f *File) Imports() []proto.Import

Imports returns the list of Imports defined in the proto file.

func (*File) Messages

func (f *File) Messages() []proto.Message

Messages returns the list of Messages defined in the proto file.

func (*File) Options

func (f *File) Options() []proto.Option

Options returns the list of top-level options defined in the proto file.

func (*File) Package

func (f *File) Package() proto.Package

Package returns the defined package or the empty value.

func (*File) Parse

func (f *File) Parse() error

Parse reads the proto file and parses the source.

func (*File) ParseReader

func (f *File) ParseReader(in io.Reader) error

ParseReader parses the reader and walks statements in the file.

func (*File) Relname

func (f *File) Relname() string

Relname returns the relative path of the proto file.

func (*File) Services

func (f *File) Services() []proto.Service

Services returns the list of Services defined in the proto file.

type FileVisitor

type FileVisitor interface {
	VisitFile(*rule.File) *rule.File
}

FileVisitor is an optional interface for RuleProvider implementations. It will get called back with the rule.File of the package being visited by gazelle (it may be nil if no build file already exists). This exists to allow RuleProvider implementations to modify the file directly (e.g. adding additional load statements).

type ImportCrossResolver

type ImportCrossResolver interface {
	resolve.CrossResolver
	ImportResolver
	ImportProvider

	// LoadFile loads csv file to populate the resolver
	LoadFile(filename string) error
	// SaveFile writes a csv file
	SaveFile(filename, repoName string) error
	// Install adds configured resolve entries into the resolve config.
	Install(c *config.Config)
}

ImportCrossResolver handles dependency resolution.

func GlobalResolver

func GlobalResolver() ImportCrossResolver

GlobalResolver returns a reference to the global ImportResolver

type ImportProvider

type ImportProvider interface {
	// Provided returns all known provided symbols, by label
	Provided(lang, impLang string) map[label.Label][]string
}

ImportProvider is an entity that can be queried for imported symbols by language name.

type ImportResolver

type ImportResolver interface {
	// Resolve returns any previously provided labels associated with the given
	// kind and import.
	Resolve(lang, impLang, imp string) []resolve.FindResult
	// Provide records the association between a rule kind+attr, the value of
	// the attr, and the label that provides the value.
	Provide(lang string, impLang, imp string, location label.Label)
	// Imports takes a callback and iterates all known imports for the given
	// lang/impLang. True should be returned to continue iteration.
	Imports(lang, impLang string, visitor func(imp string, location []label.Label) bool)
}

func NewImportResolver

func NewImportResolver(options *ImportResolverOptions) ImportResolver

type ImportResolverOptions

type ImportResolverOptions struct {
	Printf func(format string, args ...interface{})
	Debug  bool
}

type LanguageConfig

type LanguageConfig struct {
	Name    string
	Protoc  string
	Enabled bool
	Plugins map[string]bool
	Rules   map[string]bool
}

LanguageConfig carries a set of configured Plugins and Rules that will contribute to a protoc invocation.

func (*LanguageConfig) GetRulesByIntent

func (c *LanguageConfig) GetRulesByIntent(intent bool) []string

GetEnabledRules filters the list of enabled Rules in a sorted manner.

type LanguagePluginConfig

type LanguagePluginConfig struct {
	// Name is the identifier for the configuration object
	Name string
	// Implementation is the identifier for the implementation
	Implementation string
	// Label is the bazel label of the PluginInfo provider
	Label label.Label
	// Options is a set of option strings.
	Options map[string]bool
	// Flags is a set of flag strings.
	Flags map[string]bool
	// Deps is a set of dep labels.  For example, consider a plugin config for
	// 'protoc-gen-go'.  That plugin produces .go files.  The 'Deps' field can
	// be used by downstream Rule implementations to gather necessary
	// dependencies for the .go files produced by that plugin.
	Deps map[string]bool
	// Enabled flag
	Enabled bool
}

LanguagePluginConfig associates metadata with a plugin implementation.

func (*LanguagePluginConfig) GetDeps

func (c *LanguagePluginConfig) GetDeps() []string

GetDeps returns the sorted list of deps with positive intent.

func (*LanguagePluginConfig) GetFlags

func (c *LanguagePluginConfig) GetFlags() []string

GetFlags returns the list of Flags configured for the plugin.

func (*LanguagePluginConfig) GetOptions

func (c *LanguagePluginConfig) GetOptions() []string

GetOptions returns the sorted list of options with positive intent.

type LanguageRule

type LanguageRule interface {
	// Name returns the name of the rule
	Name() string
	// LoadInfo returns the gazelle LoadInfo.
	LoadInfo() rule.LoadInfo
	// KindInfo returns the gazelle KindInfo.
	KindInfo() rule.KindInfo
	// ProvideRule takes the given configration and compilation and emits a
	// RuleProvider.  If the state of the ProtocConfiguration is such that the
	// rule should not be emitted, implementation should return nil.
	ProvideRule(rc *LanguageRuleConfig, pc *ProtocConfiguration) RuleProvider
}

LanguageRule is capable of taking a compilation and deriving another rule based on it. For example, a java_proto_library LanguageRule implementation might collect all the emitted *.srcjar files from the protoc configuration and wrap it with a java_library.

func LoadStarlarkLanguageRuleFromFile

func LoadStarlarkLanguageRuleFromFile(workDir, filename, name string, reporter func(msg string), errorReporter func(err error)) (LanguageRule, error)

type LanguageRuleConfig

type LanguageRuleConfig struct {
	// Config is the parent gazelle Config
	Config *config.Config
	// Deps is a mapping from label to +/- intent.
	Deps map[string]bool
	// Attr is a mapping from string to intent map.
	Attrs map[string]map[string]bool
	// Options is a generic key -> value string mapping.  Various rule
	// implementations are free to document/interpret options in an
	// implementation-dependent manner.  TODO: deprecate this and rename to 'Flags'
	Options map[string]bool
	// Resolves is a mapping from resolve mapping spec to rewrite.  Negative
	// intent is represented by the empty rewrite value.
	Resolves []Rewrite
	// Enabled is a flag that marks language generation as enabled or not
	Enabled bool
	// Implementation is the registry identifier for the Rule
	Implementation string
	// Impl is the actual implementation
	Impl LanguageRule
	// Name is the name of the Rule config
	Name string
	// Deps is a mapping from visibility label to +/- intent.
	Visibility map[string]bool
}

LanguageRuleConfig carries metadata about a rule and its dependencies.

func NewLanguageRuleConfig

func NewLanguageRuleConfig(config *config.Config, name string) *LanguageRuleConfig

NewLanguageRuleConfig returns a pointer to a new LanguageRule config with the 'Enabled' bit set to true.

func (*LanguageRuleConfig) GetAttr

func (c *LanguageRuleConfig) GetAttr(name string) []string

GetAttr returns the positive-intent attr values under the given key.

func (*LanguageRuleConfig) GetAttrNames

func (c *LanguageRuleConfig) GetAttrNames() []string

GetAttrNames returns the names of attributes that have configuration.

func (*LanguageRuleConfig) GetDeps

func (c *LanguageRuleConfig) GetDeps() []string

GetDeps returns the sorted list of dependencies

func (*LanguageRuleConfig) GetOptions

func (c *LanguageRuleConfig) GetOptions() []string

GetOptions returns the rule options having positive intent.

func (*LanguageRuleConfig) GetRewrites

func (c *LanguageRuleConfig) GetRewrites() []Rewrite

GetRewrites returns a copy of the resolve mappings

func (*LanguageRuleConfig) GetVisibility

func (c *LanguageRuleConfig) GetVisibility() []string

GetVisibility returns the sorted list of visibility attrs

type OtherProtoLibrary

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

OtherProtoLibrary implements the ProtoLibrary interface from an existing ProtoLibrary rule generated by an other extension (typically the bazel-gazelle/proto extension).

func NewOtherProtoLibrary

func NewOtherProtoLibrary(source *rule.File, rule *rule.Rule, files ...*File) *OtherProtoLibrary

NewOtherProtoLibrary constructs a new ProtoLibrary implementation.

func (*OtherProtoLibrary) BaseName

func (s *OtherProtoLibrary) BaseName() string

BaseName implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Deps

func (s *OtherProtoLibrary) Deps() []string

Deps implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Files

func (s *OtherProtoLibrary) Files() []*File

Files implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Imports

func (s *OtherProtoLibrary) Imports() []string

Imports implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Name

func (s *OtherProtoLibrary) Name() string

Name implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Rule

func (s *OtherProtoLibrary) Rule() *rule.Rule

Rule implements part of the ProtoLibrary interface

func (*OtherProtoLibrary) Srcs

func (s *OtherProtoLibrary) Srcs() []string

Srcs returns the srcs attribute

func (*OtherProtoLibrary) StripImportPrefix

func (s *OtherProtoLibrary) StripImportPrefix() string

StripImportPrefix implements part of the ProtoLibrary interface

type Package

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

Package provides a set of proto_library derived rules for the package.

Example
package main

import (
	"fmt"

	"github.com/bazelbuild/bazel-gazelle/config"
	"github.com/bazelbuild/bazel-gazelle/rule"
	"github.com/emicklei/proto"
)

const exampleDir = "proto/test"

func exampleFile() *File {
	file := NewFile(exampleDir, "test.proto")
	file.pkg = proto.Package{
		Name: "proto.test",
	}
	file.messages = append(file.messages, proto.Message{
		Name: "Foo",
	})
	file.imports = append(file.imports,
		proto.Import{Filename: "google/protobuf/any.proto"},
		proto.Import{Filename: "foo/foo.proto"},
	)
	return file
}

func exampleProtoLibraryRule() *rule.Rule {
	rule := rule.NewRule("proto_library", "test_proto")
	rule.SetAttr("deps", []string{"//foo:foo_proto"})
	return rule
}

func exampleProtoLibrary() ProtoLibrary {
	return NewOtherProtoLibrary(nil, exampleProtoLibraryRule(), exampleFile())
}

func examplePackageConfig() *PackageConfig {
	emptyConfig := &config.Config{}
	c := NewPackageConfig(emptyConfig)
	if err := c.ParseDirectives(exampleDir, withDirectives(
		"proto_rule", "proto_compile implementation stackb:rules_proto:proto_compile",
		"proto_plugin", "fake_proto implementation protoc:fake",
		"proto_plugin", "fake_proto enabled true",
		"proto_language", "fake plugin fake_proto",
		"proto_language", "fake enabled true",
		"proto_language", "fake rule proto_compile",
	)); err != nil {
		panic("bad config: " + err.Error())
	}
	return c
}

func examplePackage() *Package {
	return NewPackage(
		exampleDir,
		examplePackageConfig(),
		exampleProtoLibrary(),
	)
}

func main() {
	printRules(examplePackage().Rules())
}

func printRules(rules []*rule.Rule) {
	file := rule.EmptyFile(exampleDir, "")
	for _, r := range rules {
		r.Insert(file)
	}
	fmt.Println(string(file.Format()))
}
Output:

proto_compile(
    name = "test_fake_compile",
    outputs = ["test_fake.pb.go"],
    plugins = ["@build_stack_rules_proto//plugin/builtin:fake"],
    proto = "test_proto",
)

func NewPackage

func NewPackage(rel string, cfg *PackageConfig, libs ...ProtoLibrary) *Package

NewPackage constructs a Package given a list of proto_library rules in the package.

func (*Package) Empty

func (s *Package) Empty() []*rule.Rule

Empty names the rules that can be deleted.

func (*Package) RuleProvider

func (s *Package) RuleProvider(r *rule.Rule) RuleProvider

RuleProvider returns the provider of a rule or nil if not known.

func (*Package) Rules

func (s *Package) Rules() []*rule.Rule

Rules provides the aggregated rule list for the package.

type PackageConfig

type PackageConfig struct {
	// config is the parent gazelle config.
	Config *config.Config
	// contains filtered or unexported fields
}

PackageConfig represents the config extension for the protobuf language.

func GetPackageConfig

func GetPackageConfig(config *config.Config) *PackageConfig

GetPackageConfig returns the associated package config.

func NewPackageConfig

func NewPackageConfig(config *config.Config) *PackageConfig

NewPackageConfig initializes a new PackageConfig.

func (*PackageConfig) Clone

func (c *PackageConfig) Clone() *PackageConfig

Clone copies this config to a new one.

func (*PackageConfig) LoadYConfig

func (c *PackageConfig) LoadYConfig(y *YConfig) error

func (*PackageConfig) ParseDirectives

func (c *PackageConfig) ParseDirectives(rel string, directives []rule.Directive) (err error)

ParseDirectives is called in each directory visited by gazelle. The relative directory name is given by 'rel' and the list of directives in the BUILD file are specified by 'directives'.

func (*PackageConfig) Plugin

func (c *PackageConfig) Plugin(name string) (LanguagePluginConfig, bool)

Plugin returns a readonly copy of the plugin configuration having the given name. If the plugin is not known the bool return arg is false.

type Plugin

type Plugin interface {
	// Name is the name of the plugin and its associated configuration.
	Name() string
	// Configure creates the plugin configuration.  If nil is returned, the
	// plugin should be skipped for the current package/library.
	Configure(ctx *PluginContext) *PluginConfiguration
}

Plugin implementations are capable of predicting the sources that are generated by a particular protoc plugin.

func LoadStarlarkPluginFromFile

func LoadStarlarkPluginFromFile(workDir, filename, name string, reporter func(msg string), errorReporter func(err error)) (Plugin, error)

type PluginConfiguration

type PluginConfiguration struct {
	// Config is the associated plugin configuration.
	Config *LanguagePluginConfig
	// Label is the bazel label for the corresponding proto_plugin rule.
	Label label.Label
	// Mappings is a dictionary that maps filenames listed in Outputs to
	// 'Out'-relative filepaths.  This is used when the plugin writes to a
	// location outside the bazel package and needs to be relocated (copied) to
	// the Output location.
	Mappings map[string]string
	// Options is the list of options that the plugin expects
	Options []string
	// Out is the output directory the plugin is predicted to write to
	Out string
	// Outputs is the list of output files the plugin generates
	Outputs []string
	// Plugin the Plugin implementation that created the configuration.
	Plugin Plugin
}

PluginConfiguration represents the configuration of a protoc plugin and the sources & source mappings that are expected to be produced.

type PluginContext

type PluginContext struct {
	// Rel is the relative path of the package.
	Rel string
	// ProtoLibrary is the proto_library under observation.
	ProtoLibrary ProtoLibrary
	// PackageConfig is the configuration for the package.
	PackageConfig PackageConfig
	// PluginConfig is the configuration object associated with the plugin.
	PluginConfig LanguagePluginConfig
	// Plugin is a reference to the plugin implementation
	Plugin Plugin
}

PluginContext represents the environment available to the plugin when invoked.

type PluginOptionsResolver

type PluginOptionsResolver interface {
	ResolvePluginOptions(ctx *PluginConfiguration, r *rule.Rule, from label.Label) []string
}

PluginOptionsResolver is an optional interface that a plugin can implement. This works in conjunction with proto_compile for plugins that need to do late determination of options. Rule is the rule being generated, and from is the label for that rule.

type PluginRegistry

type PluginRegistry interface {
	// PluginNames returns a sorted list of plugin names.
	PluginNames() []string
	// LookupPlugin returns the implementation under the given name.  If the
	// plugin is not found, ErrUnknownPlugin is returned.
	LookupPlugin(name string) (Plugin, error)
	// MustRegisterPlugin installs a Plugin implementation under the given name
	// in the global plugin registry.  Panic will occur if the same plugin is
	// registered multiple times.
	MustRegisterPlugin(plugin Plugin) PluginRegistry
	// RegisterPlugin installs a Plugin implementation under the given name.
	// Panic will occur if the same plugin is registered multiple times.  The
	// original PluginRegistry API had only the `MustRegisterPlugin` function
	// that always used the plugin.Name(), the newer `RegisterPlugin` allows one
	// to customize the name.
	RegisterPlugin(name string, plugin Plugin) PluginRegistry
}

PluginRegistry represents a library of plugin implementations.

func Plugins

func Plugins() PluginRegistry

Plugins returns a reference to the global PluginRegistry

type ProtoLibrary

type ProtoLibrary interface {
	// Name returns the name of the rule (e.g. foo_proto)
	Name() string
	// BaseName returns the name of the rule (e.g. foo).  This is typically
	// derived from the proto file package or name.
	BaseName() string
	// Rule returns the underlying rule
	Rule() *rule.Rule
	// Srcs() returns the relative path of srcs, including args.Rel
	Srcs() []string
	// Deps lists all direct library dependencies.
	Deps() []string
	// Imports lists all direct library proto import filenames.
	Imports() []string
	// StripImportPrefix returns the strip_import_prefix or the empty string.
	StripImportPrefix() string
	// Files returns the list of proto files in the rule.
	Files() []*File
}

ProtoLibrary represents a proto_library target and its associated parsed .proto files.

type ProtocConfiguration

type ProtocConfiguration struct {
	// PackageConfig parent
	PackageConfig *PackageConfig
	// The config for the p
	LanguageConfig *LanguageConfig
	// the workspace relative path of the BUILD file where this rule is being
	// generated.
	Rel string
	// the prefix for the rule (e.g. 'java')
	Prefix string
	// the library thar holds the proto files
	Library ProtoLibrary
	// the configuration for the plugins
	Plugins []*PluginConfiguration
	// The merged set of Source files for the compilations
	Outputs []string
	// The merged set of imports for the compilations
	Imports []string
	// The generated source mappings
	Mappings map[string]string
}

ProtocConfiguration represents the complete configuration and source mappings.

func (*ProtocConfiguration) GetPluginConfiguration

func (c *ProtocConfiguration) GetPluginConfiguration(implementationName string) *PluginConfiguration

func (*ProtocConfiguration) GetPluginOutputs

func (c *ProtocConfiguration) GetPluginOutputs(implementationName string) []string

type Rewrite

type Rewrite struct {
	Match   *regexp.Regexp
	Replace string
}

Rewrite is a replacement specification

func ParseRewrite

func ParseRewrite(spec string) (*Rewrite, error)

func (*Rewrite) ReplaceAll

func (r *Rewrite) ReplaceAll(src string) string

type RuleIndex

type RuleIndex interface {
	// Put records the association of the rule under the given label.
	Put(label.Label, *rule.Rule)
	// Get returns the rule under the given label, or nil if not known.
	Get(label.Label) *rule.Rule
}

func GlobalRuleIndex

func GlobalRuleIndex() RuleIndex

GlobalRuleIndex returns a reference to the global RuleIndex

type RuleProvider

type RuleProvider interface {
	// Kind of rule e.g. 'proto_library'
	Kind() string
	// Name provides the name of the rule.
	Name() string
	// Rule provides the gazelle rule implementation.  A list of other generating rules in
	// the package are provided.
	Rule(othergen ...*rule.Rule) *rule.Rule
	// Resolve performs deps resolution, similar to the gazelle Resolver
	// interface.  Imports here are always the proto_library file .proto
	// imports.
	Resolve(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imports []string, from label.Label)
	// Imports implements part of the Resolver interface
	Imports(c *config.Config, r *rule.Rule, file *rule.File) []resolve.ImportSpec
}

RuleProvider implementations are capable of providing a rule and import list to the gazelle GenerateArgs response.

type RuleRegistry

type RuleRegistry interface {
	// RuleNames returns a sorted list of rule names.
	RuleNames() []string
	// LookupRule returns the implementation under the given name.  If the rule
	// is not found, ErrUnknownRule is returned.
	LookupRule(name string) (LanguageRule, error)
	// MustRegisterRule installs a LanguageRule implementation under the given
	// name in the global rule registry.  Panic will occur if the same rule is
	// registered multiple times.
	MustRegisterRule(name string, rule LanguageRule) RuleRegistry
}

RuleRegistry represents a library of rule implementations.

func Rules

func Rules() RuleRegistry

Rules returns a reference to the global RuleRegistry

type Symbol

type Symbol string

Symbol is the type of a Starlark constructor symbol. It prints more favorably than a starlark.String.

func (Symbol) Freeze

func (s Symbol) Freeze()

func (Symbol) GoString

func (s Symbol) GoString() string

func (Symbol) Hash

func (s Symbol) Hash() (uint32, error)

func (Symbol) Index

func (s Symbol) Index(i int) starlark.Value

func (Symbol) Len

func (s Symbol) Len() int

func (Symbol) String

func (s Symbol) String() string

func (Symbol) Truth

func (s Symbol) Truth() starlark.Bool

func (Symbol) Type

func (s Symbol) Type() string

type YConfig

type YConfig struct {
	Plugin         []*YPlugin   `yaml:"plugins"`
	Rule           []*YRule     `yaml:"rules"`
	Language       []*YLanguage `yaml:"languages"`
	StarlarkPlugin []string     `yaml:"starlarkPlugins"`
	StarlarkRule   []string     `yaml:"starlarkRules"`
}

YConfig is used to configure a combined set of plugins, rules, and languages in a single YAML file. This is the format of the -proto_config flag.

func ParseYConfigFile

func ParseYConfigFile(filename string) (*YConfig, error)

ParseYConfigFile parses the given filename and returns a YConfig pointer or error if a file read or parse error occurs.

type YLanguage

type YLanguage struct {
	Name           string   `yaml:"name"`
	Implementation string   `yaml:"implementation"`
	Enabled        *bool    `yaml:"enabled,omitempty"`
	Plugin         []string `yaml:"plugins"`
	Rule           []string `yaml:"rules"`
}

YLanguage represents a LanguageConfig in YAML.

type YPlugin

type YPlugin struct {
	Name           string   `yaml:"name"`
	Implementation string   `yaml:"implementation"`
	Enabled        *bool    `yaml:"enabled,omitempty"`
	Option         []string `yaml:"options"`
	Flag           []string `yaml:"flags"`
	Dep            []string `yaml:"deps"`
	Label          string   `yaml:"label"`
}

YPlugin represents a LanguagePluginConfig in YAML.

type YRule

type YRule struct {
	Name           string   `yaml:"name"`
	Implementation string   `yaml:"implementation"`
	Enabled        *bool    `yaml:"enabled,omitempty"`
	Deps           []string `yaml:"deps"`
	Resolves       []string `yaml:"resolves"`
	Option         []string `yaml:"options"`
	Visibility     []string `yaml:"visibility"`
}

YRule represents a LanguageRuleConfig in YAML.

Jump to

Keyboard shortcuts

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