rule

package
v0.22.1 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2020 License: Apache-2.0 Imports: 13 Imported by: 82

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

Constants

This section is empty.

Variables

View Source
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
)
View Source
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.

View Source
var OSAliases = map[string][]string{
	"android": []string{"linux"},
	"ios":     []string{"darwin"},
}

Functions

func CheckInternalVisibility added in v0.17.0

func CheckInternalVisibility(rel, visibility string) string

CheckInternalVisibility overrides the given visibility if the package is internal.

func ExprFromValue

func ExprFromValue(val interface{}) bzl.Expr

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

func FlattenExpr(e bzl.Expr) bzl.Expr

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

func MapExprStrings(e bzl.Expr, f func(string) string) bzl.Expr

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

func MatchBuildFileName(dir string, names []string, files []os.FileInfo) string

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

func MergeRules(src, dst *Rule, mergeable map[string]bool, filename string)

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

func ShouldKeep(e bzl.Expr) bool

ShouldKeep returns whether e is marked with a "# keep" comment. Kept expressions should not be removed or modified.

func SquashRules

func SquashRules(src, dst *Rule, filename string) error

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

type BzlExprValue interface {
	BzlExpr() bzl.Expr
}

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

func ParseDirectives(f *bzl.File) []Directive

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

func ParseDirectivesFromMacro(f *bzl.DefStmt) []Directive

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 EmptyFile

func EmptyFile(path, pkg string) *File

EmptyFile creates a File wrapped around an empty syntax tree.

func EmptyMacroFile added in v0.18.0

func EmptyMacroFile(path, pkg, defName string) (*File, error)

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

func LoadData(path, pkg string, data []byte) (*File, error)

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

func LoadFile(path, pkg string) (*File, error)

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

func LoadMacroData(path, pkg, defName string, data []byte) (*File, error)

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

func LoadMacroFile(path, pkg, defName string) (*File, error)

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

func LoadWorkspaceData(path, pkg string, data []byte) (*File, error)

LoadWorkspaceData is similar to LoadData but parses the data as a WORKSPACE file.

func LoadWorkspaceFile added in v0.17.0

func LoadWorkspaceFile(path, pkg string) (*File, error)

LoadWorkspaceFile is similar to LoadFile but parses the file as a WORKSPACE file.

func ScanAST

func ScanAST(pkg string, bzlFile *bzl.File) *File

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

func ScanASTBody(pkg, defName string, bzlFile *bzl.File) *File

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

func (f *File) Format() []byte

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

func (f *File) HasDefaultVisibility() bool

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

func (f *File) MacroName() string

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) Save

func (f *File) Save(path string) error

Save writes the build file to disk. This method calls Sync internally.

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

func (f *File) SyncMacroFile(from *File)

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 GlobValue

type GlobValue struct {
	Patterns []string
	Excludes []string
}

GlobValue represents a Bazel glob expression.

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 NewLoad

func NewLoad(name string) *Load

NewLoad creates a new, empty load statement for the given file name.

func (*Load) Add

func (l *Load) Add(sym string)

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) Has

func (l *Load) Has(sym string) bool

Has returns true if sym is loaded by this statement.

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

func (l *Load) Insert(f *File, index int)

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) IsEmpty

func (l *Load) IsEmpty() bool

IsEmpty returns whether this statement loads any symbols.

func (*Load) Name

func (l *Load) Name() string

Name returns the name of the file this statement loads.

func (*Load) Remove

func (l *Load) Remove(sym string)

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

func (l *Load) SymbolPairs() []struct{ From, To string }

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).

func (*Load) Symbols

func (l *Load) Symbols() []string

Symbols returns a sorted list of symbols this statement loads. If the symbol is loaded with a name different from its definition, the loaded name is returned, not the original name.

type LoadInfo

type LoadInfo struct {
	Name    string
	Symbols []string
	After   []string
}

LoadInfo describes a file that Gazelle knows about and the symbols it defines.

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.

func (Platform) String

func (p Platform) String() string

String returns OS, Arch, or "OS_Arch" if both are set. This must match the names of config_setting rules in @io_bazel_rules_go//go/platform.

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 NewRule

func NewRule(kind, name string) *Rule

NewRule creates a new, empty rule with the given kind and name.

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) Args

func (r *Rule) Args() []bzl.Expr

Args returns positional arguments passed to a rule.

func (*Rule) Attr

func (r *Rule) Attr(key string) bzl.Expr

Attr returns the value of the named attribute. nil is returned when the attribute is not set.

func (*Rule) AttrKeys

func (r *Rule) AttrKeys() []string

AttrKeys returns a sorted list of attribute keys used in this rule.

func (*Rule) AttrString

func (r *Rule) AttrString(key string) string

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

func (r *Rule) AttrStrings(key string) []string

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) DelAttr

func (r *Rule) DelAttr(key string)

DelAttr removes the named attribute from the rule.

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

func (r *Rule) Insert(f *File)

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

func (r *Rule) InsertAt(f *File, index int)

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

func (r *Rule) IsEmpty(info KindInfo) bool

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) Kind

func (r *Rule) Kind() string

Kind returns the kind of rule this is (for example, "go_library").

func (*Rule) Name

func (r *Rule) Name() string

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

func (r *Rule) PrivateAttr(key string) interface{}

PrivateAttr return the private value associated with a key.

func (*Rule) PrivateAttrKeys

func (r *Rule) PrivateAttrKeys() []string

PrivateAttrKeys returns a sorted list of private attribute names.

func (*Rule) SetAttr

func (r *Rule) SetAttr(key string, value interface{})

SetAttr adds or replaces the named attribute with an expression produced by ExprFromValue.

func (*Rule) SetKind

func (r *Rule) SetKind(kind string)

SetKind changes the kind of rule this is.

func (*Rule) SetName

func (r *Rule) SetName(name string)

SetName sets the value of the rule's "name" attribute.

func (*Rule) SetPrivateAttr

func (r *Rule) SetPrivateAttr(key string, value interface{})

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

func (r *Rule) ShouldKeep() bool

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

type SelectStringListValue map[string][]string

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

Jump to

Keyboard shortcuts

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