Documentation ¶
Overview ¶
Package rule provides tools for editing Bazel build files. It is intended to be a more powerful replacement for github.com/bazelbuild/buildtools/build.Rule, adapted for Gazelle's usage. It is language agnostic, but it may be used for language-specific rules by providing configuration.
File is the primary interface to this package. A File represents an individual build file. It comprises a list of Rules and a list of Loads. Rules and Loads may be inserted, modified, or deleted. When all changes are done, File.Save() may be called to write changes back to a file.
Index ¶
- Variables
- func CheckInternalVisibility(rel, visibility string) string
- func ExprFromValue(val interface{}) bzl.Expr
- func FlattenExpr(e bzl.Expr) bzl.Expr
- func MapExprStrings(e bzl.Expr, f func(string) string) bzl.Expr
- func MatchBuildFileName(dir string, names []string, files []os.FileInfo) string
- func MergeRules(src, dst *Rule, mergeable map[string]bool, filename string)
- func ShouldKeep(e bzl.Expr) bool
- func SquashRules(src, dst *Rule, filename string) error
- type BzlExprValue
- type Directive
- type File
- func EmptyFile(path, pkg string) *File
- func EmptyMacroFile(path, pkg, defName string) (*File, error)
- func LoadData(path, pkg string, data []byte) (*File, error)
- func LoadFile(path, pkg string) (*File, error)
- func LoadMacroData(path, pkg, defName string, data []byte) (*File, error)
- func LoadMacroFile(path, pkg, defName string) (*File, error)
- func LoadWorkspaceData(path, pkg string, data []byte) (*File, error)
- func LoadWorkspaceFile(path, pkg string) (*File, error)
- func ScanAST(pkg string, bzlFile *bzl.File) *File
- func ScanASTBody(pkg, defName string, bzlFile *bzl.File) *File
- type GlobValue
- type KeyValue
- type KindInfo
- type Load
- func (l *Load) Add(sym string)
- func (s *Load) AddComment(token string)
- func (s *Load) Comments() []string
- func (s *Load) Delete()
- func (l *Load) Has(sym string) bool
- func (s *Load) Index() int
- func (l *Load) Insert(f *File, index int)
- func (l *Load) IsEmpty() bool
- func (l *Load) Name() string
- func (l *Load) Remove(sym string)
- func (l *Load) SymbolPairs() []struct{ ... }
- func (l *Load) Symbols() []string
- type LoadInfo
- type Platform
- type PlatformStrings
- func (ps PlatformStrings) BzlExpr() bzl.Expr
- func (ps *PlatformStrings) Flat() []string
- func (ps *PlatformStrings) HasExt(ext string) bool
- func (ps *PlatformStrings) IsEmpty() bool
- func (ps *PlatformStrings) Map(f func(s string) (string, error)) (PlatformStrings, []error)
- func (ps *PlatformStrings) MapSlice(f func([]string) ([]string, error)) (PlatformStrings, []error)
- type Rule
- func (s *Rule) AddComment(token string)
- func (r *Rule) Args() []bzl.Expr
- func (r *Rule) Attr(key string) bzl.Expr
- func (r *Rule) AttrKeys() []string
- func (r *Rule) AttrString(key string) string
- func (r *Rule) AttrStrings(key string) []string
- func (s *Rule) Comments() []string
- func (r *Rule) DelAttr(key string)
- func (s *Rule) Delete()
- func (s *Rule) Index() int
- func (r *Rule) Insert(f *File)
- func (r *Rule) InsertAt(f *File, index int)
- func (r *Rule) IsEmpty(info KindInfo) bool
- func (r *Rule) Kind() string
- func (r *Rule) Name() string
- func (r *Rule) PrivateAttr(key string) interface{}
- func (r *Rule) PrivateAttrKeys() []string
- func (r *Rule) SetAttr(key string, value interface{})
- func (r *Rule) SetKind(kind string)
- func (r *Rule) SetName(name string)
- func (r *Rule) SetPrivateAttr(key string, value interface{})
- func (r *Rule) ShouldKeep() bool
- type SelectStringListValue
Constants ¶
This section is empty.
Variables ¶
var ( // KnownOSs is the sorted list of operating systems that Go supports. KnownOSs []string // KnownOSSet is the set of operating systems that Go supports. KnownOSSet map[string]bool // KnownArchs is the sorted list of architectures that Go supports. KnownArchs []string // KnownArchSet is the set of architectures that Go supports. KnownArchSet map[string]bool // KnownOSArchs is a map from OS to the archictures they run on. KnownOSArchs map[string][]string // KnownArchOSs is a map from architectures to that OSs that run on them. KnownArchOSs map[string][]string )
var KnownPlatforms = []Platform{
{"aix", "ppc64"},
{"android", "386"},
{"android", "amd64"},
{"android", "arm"},
{"android", "arm64"},
{"darwin", "386"},
{"darwin", "amd64"},
{"darwin", "arm"},
{"darwin", "arm64"},
{"dragonfly", "amd64"},
{"freebsd", "386"},
{"freebsd", "amd64"},
{"freebsd", "arm"},
{"freebsd", "arm64"},
{"illumos", "amd64"},
{"ios", "386"},
{"ios", "amd64"},
{"ios", "arm"},
{"ios", "arm64"},
{"js", "wasm"},
{"linux", "386"},
{"linux", "amd64"},
{"linux", "arm"},
{"linux", "arm64"},
{"linux", "mips"},
{"linux", "mips64"},
{"linux", "mips64le"},
{"linux", "mipsle"},
{"linux", "ppc64"},
{"linux", "ppc64le"},
{"linux", "riscv64"},
{"linux", "s390x"},
{"nacl", "386"},
{"nacl", "amd64p32"},
{"nacl", "arm"},
{"netbsd", "386"},
{"netbsd", "amd64"},
{"netbsd", "arm"},
{"netbsd", "arm64"},
{"openbsd", "386"},
{"openbsd", "amd64"},
{"openbsd", "arm"},
{"openbsd", "arm64"},
{"plan9", "386"},
{"plan9", "amd64"},
{"plan9", "arm"},
{"solaris", "amd64"},
{"windows", "386"},
{"windows", "amd64"},
{"windows", "arm"},
}
KnownPlatforms is the set of target platforms that Go supports. Gazelle will generate multi-platform build files using these tags. rules_go and Bazel may not actually support all of these.
DEPRECATED: do not use outside language/go.
var OSAliases = map[string][]string{ "android": []string{"linux"}, "ios": []string{"darwin"}, }
Functions ¶
func CheckInternalVisibility ¶ added in v0.17.0
CheckInternalVisibility overrides the given visibility if the package is internal.
func ExprFromValue ¶
ExprFromValue converts a value into an expression that can be written into a Bazel build file. The following types of values can be converted:
- bools, integers, floats, strings.
- slices, arrays (converted to lists).
- maps (converted to select expressions; keys must be rules in @io_bazel_rules_go//go/platform).
- GlobValue (converted to glob expressions).
- PlatformStrings (converted to a concatenation of a list and selects).
Converting unsupported types will cause a panic.
func FlattenExpr ¶
FlattenExpr takes an expression that may have been generated from PlatformStrings and returns its values in a flat, sorted, de-duplicated list. Comments are accumulated and de-duplicated across duplicate expressions. If the expression could not have been generted by PlatformStrings, the expression will be returned unmodified.
func MapExprStrings ¶
MapExprStrings applies a function to string sub-expressions within e. An expression containing the results with the same structure as e is returned.
func MatchBuildFileName ¶
MatchBuildFileName looks for a file in files that has a name from names. If there is at least one matching file, a path will be returned by joining dir and the first matching name. If there are no matching files, the empty string is returned.
func MergeRules ¶
MergeRules copies information from src into dst, usually discarding information in dst when they have the same attributes.
If dst is marked with a "# keep" comment, either above the rule or as a suffix, nothing will be changed.
If src has an attribute that is not in dst, it will be copied into dst.
If src and dst have the same attribute and the attribute is mergeable and the attribute in dst is not marked with a "# keep" comment, values in the dst attribute not marked with a "# keep" comment will be dropped, and values from src will be copied in.
If dst has an attribute not in src, and the attribute is mergeable and not marked with a "# keep" comment, values in the attribute not marked with a "# keep" comment will be dropped. If the attribute is empty afterward, it will be deleted.
func ShouldKeep ¶
ShouldKeep returns whether e is marked with a "# keep" comment. Kept expressions should not be removed or modified.
func SquashRules ¶
SquashRules copies information from src into dst without discarding information in dst. SquashRules detects duplicate elements in lists and dictionaries, but it doesn't sort elements after squashing. If squashing fails because the expression is not understood, an error is returned, and neither rule is modified.
Types ¶
type BzlExprValue ¶ added in v0.19.0
BzlExprValue is implemented by types that have custom translations to Starlark values.
type Directive ¶
type Directive struct {
Key, Value string
}
Directive is a key-value pair extracted from a top-level comment in a build file. Directives have the following format:
# gazelle:key value
Keys may not contain spaces. Values may be empty and may contain spaces, but surrounding space is trimmed.
func ParseDirectives ¶
ParseDirectives scans f for Gazelle directives. The full list of directives is returned. Errors are reported for unrecognized directives and directives out of place (after the first statement).
func ParseDirectivesFromMacro ¶ added in v0.19.0
ParseDirectivesFromMacro scans a macro body for Gazelle directives. The full list of directives is returned. Errors are reported for unrecognized directives and directives out of place (after the first statement).
type File ¶
type File struct { // File is the underlying build file syntax tree. Some editing operations // may modify this, but editing is not complete until Sync() is called. File *bzl.File // Pkg is the Bazel package this build file defines. Pkg string // Path is the file system path to the build file (same as File.Path). Path string // DefName is the name of the function definition this File refers to // if loaded with LoadMacroFile or a similar function. Normally empty. DefName string // Directives is a list of configuration directives found in top-level // comments in the file. This should not be modified after the file is read. Directives []Directive // Loads is a list of load statements within the file. This should not // be modified directly; use Load methods instead. Loads []*Load // Rules is a list of rules within the file (or function calls that look like // rules). This should not be modified directly; use Rule methods instead. Rules []*Rule // Content is the file's underlying disk content, which is recorded when the // file is initially loaded and whenever it is saved back to disk. If the file // is modified outside of Rule methods, Content must be manually updated in // order to keep it in sync. Content []byte // contains filtered or unexported fields }
File provides editing functionality for a build file. You can create a new file with EmptyFile or load an existing file with LoadFile. After changes have been made, call Save to write changes back to a file.
func EmptyMacroFile ¶ added in v0.18.0
EmptyMacroFile creates a bzl file at the given path and within the file creates a Starlark function with the provided name. The function can then be modified by Sync and Save calls.
func LoadData ¶
LoadData parses a build file from a byte slice and scans it for rules and load statements. The syntax tree within the returned File will be modified by editing methods.
func LoadFile ¶
LoadFile loads a build file from disk, parses it, and scans for rules and load statements. The syntax tree within the returned File will be modified by editing methods.
This function returns I/O and parse errors without modification. It's safe to use os.IsNotExist and similar predicates.
func LoadMacroData ¶ added in v0.18.0
LoadMacroData parses a bzl file from a byte slice and scans for the load statements and the rules called from the given Starlark function. If there is no matching function name, then a new function will be created, and added to the File the next time Sync is called. The function's syntax tree will be returned within File and can be modified by Sync and Save calls.
func LoadMacroFile ¶ added in v0.18.0
LoadMacroFile loads a bzl file from disk, parses it, then scans for the load statements and the rules called from the given Starlark function. If there is no matching function name, then a new function with that name will be created. The function's syntax tree will be returned within File and can be modified by Sync and Save calls.
func LoadWorkspaceData ¶ added in v0.17.0
LoadWorkspaceData is similar to LoadData but parses the data as a WORKSPACE file.
func LoadWorkspaceFile ¶ added in v0.17.0
LoadWorkspaceFile is similar to LoadFile but parses the file as a WORKSPACE file.
func ScanAST ¶
ScanAST creates a File wrapped around the given syntax tree. This tree will be modified by editing methods.
func ScanASTBody ¶ added in v0.18.0
ScanASTBody creates a File wrapped around the given syntax tree. It will also scan the AST for a function matching the given defName, and if the function does not exist it will create a new one and mark it to be added to the File the next time Sync is called.
func (*File) Format ¶
Format formats the build file in a form that can be written to disk. This method calls Sync internally.
func (*File) HasDefaultVisibility ¶ added in v0.17.0
HasDefaultVisibility returns whether the File contains a "package" rule with a "default_visibility" attribute. Rules generated by Gazelle should not have their own visibility attributes if this is the case.
func (*File) MacroName ¶ added in v0.18.0
MacroName returns the name of the macro function that this file is editing, or an empty string if a macro function is not being edited.
func (*File) SortMacro ¶ added in v0.22.0
func (f *File) SortMacro()
SortMacro sorts rules in the macro of this File. It doesn't sort the rules if this File does not have a macro, e.g., WORKSPACE. This method calls Sync internally.
func (*File) Sync ¶
func (f *File) Sync()
Sync writes all changes back to the wrapped syntax tree. This should be called after editing operations, before reading the syntax tree again.
func (*File) SyncMacroFile ¶ added in v0.18.0
SyncMacroFile syncs the file's syntax tree with another file's. This is useful for keeping multiple macro definitions from the same .bzl file in sync.
type KeyValue ¶
type KeyValue struct { Key string Value interface{} }
KeyValue represents a key-value pair. This gets converted into a rule attribute, i.e., a Skylark keyword argument.
type KindInfo ¶
type KindInfo struct { // MatchAny is true if a rule of this kind may be matched with any rule // of the same kind, regardless of attributes, if exactly one rule is // present a build file. MatchAny bool // MatchAttrs is a list of attributes used in matching. For example, // for go_library, this list contains "importpath". Attributes are matched // in order. MatchAttrs []string // NonEmptyAttrs is a set of attributes that, if present, disqualify a rule // from being deleted after merge. NonEmptyAttrs map[string]bool // SubstituteAttrs is a set of attributes that should be substituted // after matching and before merging. For example, suppose generated rule A // references B via an "embed" attribute, and B matches against rule C. // The label for B in A's "embed" must be substituted with a label for C. // "embed" would need to be in this set. SubstituteAttrs map[string]bool // MergeableAttrs is a set of attributes that should be merged before // dependency resolution. See rule.Merge. MergeableAttrs map[string]bool // ResolveAttrs is a set of attributes that should be merged after // dependency resolution. See rule.Merge. ResolveAttrs map[string]bool }
KindInfo stores metadata for a kind of rule, for example, "go_library".
type Load ¶
type Load struct {
// contains filtered or unexported fields
}
Load represents a load statement within a build file.
func (*Load) Add ¶
Add inserts a new symbol into the load statement. This has no effect if the symbol is already loaded. Symbols will be sorted, so the order doesn't matter.
func (*Load) AddComment ¶ added in v0.22.0
func (s *Load) AddComment(token string)
AddComment adds a new comment above the statement, after other comments. The new comment must start with "#".
func (*Load) Comments ¶ added in v0.22.0
func (s *Load) Comments() []string
Comments returns the text of the comments that appear before the statement. Each comment includes the leading "#".
func (*Load) Delete ¶
func (s *Load) Delete()
Delete marks this statement for deletion. It will be removed from the syntax tree when File.Sync is called.
func (*Load) Index ¶
func (s *Load) Index() int
Index returns the index for this statement within the build file. For inserted rules, this is where the rule will be inserted (rules with the same index will be inserted in the order Insert was called). For existing rules, this is the index of the original statement.
func (*Load) Insert ¶
Insert marks this statement for insertion at the given index. If multiple statements are inserted at the same index, they will be inserted in the order Insert is called.
func (*Load) Remove ¶
Remove deletes a symbol from the load statement. This has no effect if the symbol is not loaded.
func (*Load) SymbolPairs ¶ added in v0.22.0
SymbolPairs returns a list of symbol pairs loaded by this statement. Each pair contains the symbol defined in the loaded module (From) and the symbol declared in the loading module (To). The pairs are sorted by To (same order as Symbols).
type Platform ¶
type Platform struct {
OS, Arch string
}
Platform represents a GOOS/GOARCH pair. When Platform is used to describe sources, dependencies, or flags, either OS or Arch may be empty.
DEPRECATED: do not use outside language/go. This type is Go-specific and should be moved to the Go extension.
type PlatformStrings ¶
type PlatformStrings struct { // Generic is a list of strings not specific to any platform. Generic []string // OS is a map from OS name (anything in KnownOSs) to // OS-specific strings. OS map[string][]string // Arch is a map from architecture name (anything in KnownArchs) to // architecture-specific strings. Arch map[string][]string // Platform is a map from platforms to OS and architecture-specific strings. Platform map[Platform][]string }
PlatformStrings contains a set of strings associated with a buildable target in a package. This is used to store source file names, import paths, and flags.
Strings are stored in four sets: generic strings, OS-specific strings, arch-specific strings, and OS-and-arch-specific strings. A string may not be duplicated within a list or across sets; however, a string may appear in more than one list within a set (e.g., in "linux" and "windows" within the OS set). Strings within each list should be sorted, though this may not be relied upon.
DEPRECATED: do not use outside language/go. This type is Go-specific and should be moved to the Go extension.
func (PlatformStrings) BzlExpr ¶ added in v0.19.0
func (ps PlatformStrings) BzlExpr() bzl.Expr
func (*PlatformStrings) Flat ¶
func (ps *PlatformStrings) Flat() []string
Flat returns all the strings in the set, sorted and de-duplicated.
func (*PlatformStrings) HasExt ¶
func (ps *PlatformStrings) HasExt(ext string) bool
HasExt returns whether this set contains a file with the given extension.
func (*PlatformStrings) IsEmpty ¶
func (ps *PlatformStrings) IsEmpty() bool
func (*PlatformStrings) Map ¶
func (ps *PlatformStrings) Map(f func(s string) (string, error)) (PlatformStrings, []error)
Map applies a function that processes individual strings to the strings in "ps" and returns a new PlatformStrings with the result. Empty strings returned by the function are dropped.
func (*PlatformStrings) MapSlice ¶
func (ps *PlatformStrings) MapSlice(f func([]string) ([]string, error)) (PlatformStrings, []error)
MapSlice applies a function that processes slices of strings to the strings in "ps" and returns a new PlatformStrings with the results.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
Rule represents a rule statement within a build file.
func (*Rule) AddComment ¶ added in v0.22.0
func (s *Rule) AddComment(token string)
AddComment adds a new comment above the statement, after other comments. The new comment must start with "#".
func (*Rule) Attr ¶
Attr returns the value of the named attribute. nil is returned when the attribute is not set.
func (*Rule) AttrString ¶
AttrString returns the value of the named attribute if it is a scalar string. "" is returned if the attribute is not set or is not a string.
func (*Rule) AttrStrings ¶
AttrStrings returns the string values of an attribute if it is a list. nil is returned if the attribute is not set or is not a list. Non-string values within the list won't be returned.
func (*Rule) Comments ¶ added in v0.22.0
func (s *Rule) Comments() []string
Comments returns the text of the comments that appear before the statement. Each comment includes the leading "#".
func (*Rule) Delete ¶
func (s *Rule) Delete()
Delete marks this statement for deletion. It will be removed from the syntax tree when File.Sync is called.
func (*Rule) Index ¶
func (s *Rule) Index() int
Index returns the index for this statement within the build file. For inserted rules, this is where the rule will be inserted (rules with the same index will be inserted in the order Insert was called). For existing rules, this is the index of the original statement.
func (*Rule) Insert ¶
Insert marks this statement for insertion at the end of the file. Multiple statements will be inserted in the order Insert is called.
func (*Rule) InsertAt ¶ added in v0.22.0
InsertAt marks this statement for insertion before the statement at index. Multiple rules inserted at the same index will be inserted in the order Insert is called. Loads inserted at the same index will be inserted first.
func (*Rule) IsEmpty ¶
IsEmpty returns true when the rule contains none of the attributes in attrs for its kind. attrs should contain attributes that make the rule buildable like srcs or deps and not descriptive attributes like name or visibility.
func (*Rule) Name ¶
Name returns the value of the rule's "name" attribute if it is a string or "" if the attribute does not exist or is not a string.
func (*Rule) PrivateAttr ¶
PrivateAttr return the private value associated with a key.
func (*Rule) PrivateAttrKeys ¶
PrivateAttrKeys returns a sorted list of private attribute names.
func (*Rule) SetAttr ¶
SetAttr adds or replaces the named attribute with an expression produced by ExprFromValue.
func (*Rule) SetPrivateAttr ¶
SetPrivateAttr associates a value with a key. Unlike SetAttr, this value is not converted to a build syntax tree and will not be written to a build file.
func (*Rule) ShouldKeep ¶
ShouldKeep returns whether the rule is marked with a "# keep" comment. Rules that are kept should not be modified. This does not check whether subexpressions within the rule should be kept.
type SelectStringListValue ¶ added in v0.19.0
SelectStringListValue is a value that can be translated to a Bazel select expression that picks a string list based on a string condition.
func (SelectStringListValue) BzlExpr ¶ added in v0.19.0
func (s SelectStringListValue) BzlExpr() bzl.Expr