edit

package
v0.0.0-...-fb3792a Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2020 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package edit provides high-level auxiliary functions for AST manipulation on BUILD files.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ShortenLabelsFlag if true converts added labels to short form , e.g. //foo:bar => :bar
	ShortenLabelsFlag = true
	// DeleteWithComments if true a list attribute will be be deleted in ListDelete, even if there is a comment attached to it
	DeleteWithComments = true
)
View Source
var AllCommands = map[string]CommandInfo{
	"add":               {cmdAdd, true, 2, -1, "<attr> <value(s)>"},
	"new_load":          {cmdNewLoad, false, 1, -1, "<path> <[to=]from(s)>"},
	"replace_load":      {cmdReplaceLoad, false, 1, -1, "<path> <[to=]symbol(s)>"},
	"substitute_load":   {cmdSubstituteLoad, false, 2, 2, "<old_regexp> <new_template>"},
	"comment":           {cmdComment, true, 1, 3, "<attr>? <value>? <comment>"},
	"print_comment":     {cmdPrintComment, true, 0, 2, "<attr>? <value>?"},
	"delete":            {cmdDelete, true, 0, 0, ""},
	"fix":               {cmdFix, true, 0, -1, "<fix(es)>?"},
	"move":              {cmdMove, true, 3, -1, "<old_attr> <new_attr> <value(s)>"},
	"new":               {cmdNew, false, 2, 4, "<rule_kind> <rule_name> [(before|after) <relative_rule_name>]"},
	"print":             {cmdPrint, true, 0, -1, "<attribute(s)>"},
	"remove":            {cmdRemove, true, 1, -1, "<attr> <value(s)>"},
	"remove_comment":    {cmdRemoveComment, true, 0, 2, "<attr>? <value>?"},
	"rename":            {cmdRename, true, 2, 2, "<old_attr> <new_attr>"},
	"replace":           {cmdReplace, true, 3, 3, "<attr> <old_value> <new_value>"},
	"substitute":        {cmdSubstitute, true, 3, 3, "<attr> <old_regexp> <new_template>"},
	"set":               {cmdSet, true, 1, -1, "<attr> <value(s)>"},
	"set_if_absent":     {cmdSetIfAbsent, true, 1, -1, "<attr> <value(s)>"},
	"copy":              {cmdCopy, true, 2, 2, "<attr> <from_rule>"},
	"copy_no_overwrite": {cmdCopyNoOverwrite, true, 2, 2, "<attr> <from_rule>"},
	"dict_add":          {cmdDictAdd, true, 2, -1, "<attr> <(key:value)(s)>"},
	"dict_set":          {cmdDictSet, true, 2, -1, "<attr> <(key:value)(s)>"},
	"dict_remove":       {cmdDictRemove, true, 2, -1, "<attr> <key(s)>"},
	"dict_list_add":     {cmdDictListAdd, true, 3, -1, "<attr> <key> <value(s)>"},
}

AllCommands associates the command names with their function and number of arguments.

View Source
var AllRuleFixes = []struct {
	Name    string
	Fn      func(file *build.File, rule *build.Rule, pkg string) bool
	Message string
}{
	{"sortGlob", sortGlob,
		"Sort the list in a call to glob"},
	{"splitOptions", splitOptionsWithSpaces,
		"Each option should be given separately in the list"},
	{"shortenLabels", shortenLabels,
		"Style: Use the canonical label notation"},
	{"removeVisibility", removeVisibility,
		"This visibility attribute is useless (it corresponds to the default value)"},
	{"removeTestOnly", removeTestOnly,
		"This testonly attribute is useless (it corresponds to the default value)"},
	{"genruleRenameDepsTools", genruleRenameDepsTools,
		"'deps' attribute in genrule has been renamed 'tools'"},
	{"genruleFixHeuristicLabels", genruleFixHeuristicLabels,
		"$(location) should be called explicitely"},
	{"sortExportsFiles", sortExportsFiles,
		"Files in exports_files should be sorted"},
	{"varref", removeVarref,
		"All varref('foo') should be replaced with '$foo'"},
	{"mergeLiteralLists", mergeLiteralLists,
		"Remove useless list concatenation"},
}

AllRuleFixes is a list of all Buildozer fixes that can be applied on a rule.

View Source
var BuildFileNames = [...]string{"BUILD.bazel", "BUILD", "BUCK"}

BuildFileNames is exported so that users that want to override it in scripts are free to do so.

View Source
var EditFile = func(fi os.FileInfo, name string) error {
	return nil
}

EditFile is a function that does any prework needed before editing a file. e.g. "checking out for write" from a locking source control repo.

View Source
var FileLevelFixes = []struct {
	Name    string
	Fn      func(file *build.File) bool
	Message string
}{
	{"movePackageToTop", movePackageDeclarationToTheTop,
		"The package declaration should be the first rule in a file"},
	{"usePlusEqual", usePlusEqual,
		"Prefer '+=' over 'extend' or 'append'"},
	{"unusedLoads", cleanUnusedLoads,
		"Remove unused symbols from load statements"},
	{"moveLicensesAndDistribs", moveLicensesAndDistribs,
		"Move licenses and distribs to the package function"},
}

FileLevelFixes is a list of all Buildozer fixes that apply on the whole file.

View Source
var Usage = func() {}

Usage is a user-overridden func to print the program usage.

Functions

func AddValueToList

func AddValueToList(oldList build.Expr, pkg string, item build.Expr, sorted bool) build.Expr

AddValueToList adds a value to a list. If the expression is not a list, a list with a single element is appended to the original expression.

func AddValueToListAttribute

func AddValueToListAttribute(r *build.Rule, name string, pkg string, item build.Expr, vars *map[string]*build.AssignExpr)

AddValueToListAttribute adds the given item to the list attribute identified by name and pkg.

func AllLists

func AllLists(e build.Expr) []*build.ListExpr

AllLists returns all the lists concatenated in an expression. For example, in: glob(["*.go"]) + [":rule"] the function will return [[":rule"]].

func AllSelects

func AllSelects(e build.Expr) []*build.CallExpr

AllSelects returns all the selects concatenated in an expression.

func AllStrings

func AllStrings(e build.Expr) []*build.StringExpr

AllStrings returns all the string literals concatenated in an expression. For example, in: "foo" + x + "bar" the function will return ["foo", "bar"].

func AppendToLoad

func AppendToLoad(load *build.LoadStmt, from, to []string) bool

AppendToLoad appends symbols to an existing load statement Returns true if the statement was acually edited (if the required symbols haven't been loaded yet)

func Buildozer

func Buildozer(opts *Options, args []string) int

Buildozer loops over all arguments on the command line fixing BUILD files.

func ComputeIntersection

func ComputeIntersection(list1, list2 []build.Expr) []build.Expr

ComputeIntersection returns the intersection of the two lists given as parameters; if the containing elements are not build.StringExpr, the result will be nil.

func ContainsComments

func ContainsComments(expr build.Expr, str string) bool

ContainsComments returns whether the expr has a comment that includes str.

func ContainsLabels

func ContainsLabels(kind, attr string) bool

ContainsLabels returns true for all attributes whose type is a label or a label list.

func DeleteRule

func DeleteRule(f *build.File, rule *build.Rule) *build.File

DeleteRule returns the AST without the specified rule

func DeleteRuleByKind

func DeleteRuleByKind(f *build.File, kind string) *build.File

DeleteRuleByKind removes the rules of the specified kind from the AST. Returns an updated copy of f.

func DeleteRuleByName

func DeleteRuleByName(f *build.File, name string) *build.File

DeleteRuleByName returns the AST without the rules that have the given name.

func DictionaryDelete

func DictionaryDelete(dict *build.DictExpr, key string) (deleted build.Expr)

DictionaryDelete looks for the key in the dictionary expression. If the key exists, it removes the key-value pair and returns it. Otherwise it returns nil.

func DictionaryGet

func DictionaryGet(dict *build.DictExpr, key string) build.Expr

DictionaryGet looks for the key in the dictionary expression, and returns the current value. If it is unset, it returns nil.

func DictionarySet

func DictionarySet(dict *build.DictExpr, key string, value build.Expr) build.Expr

DictionarySet looks for the key in the dictionary expression. If value is not nil, it replaces the current value with it. In all cases, it returns the current value.

func EditFunction

func EditFunction(v build.Expr, name string, f func(x *build.CallExpr, stk []build.Expr) build.Expr) build.Expr

EditFunction is a wrapper around build.Edit. The callback is called only on functions 'name'.

func ExistingPackageDeclaration

func ExistingPackageDeclaration(f *build.File) *build.Rule

ExistingPackageDeclaration returns the package declaration, or nil if there is none.

func ExprToRule

func ExprToRule(expr build.Expr, kind string) (*build.Rule, bool)

ExprToRule returns a Rule from an Expr. The boolean is false iff the Expr is not a function call, or does not have the expected kind.

func FindExportedFile

func FindExportedFile(f *build.File, name string) *build.Rule

FindExportedFile returns the first exports_files call which contains the file 'name', or nil if not found

func FindRuleByName

func FindRuleByName(f *build.File, name string) *build.Rule

FindRuleByName returns the rule in the file that has the given name. If the name is "__pkg__", it returns the global package declaration.

func FirstList

func FirstList(e build.Expr) *build.ListExpr

FirstList works in the same way as AllLists, except that it returns only one list, or nil.

func FixFile

func FixFile(f *build.File, pkg string, fixes []string) *build.File

FixFile fixes everything it can in the BUILD file.

func FixRule

func FixRule(f *build.File, pkg string, rule *build.Rule, fixes []string) *build.File

FixRule aims to fix errors in BUILD files, remove deprecated features, and simplify the code.

func IndexOfLast

func IndexOfLast(stmt []build.Expr, Kind string) int

IndexOfLast finds the index of the last expression of a specific kind.

func IndexOfRuleByName

func IndexOfRuleByName(f *build.File, name string) (int, *build.Rule)

IndexOfRuleByName returns the index (in f.Stmt) of the CallExpr which defines a rule named `name`, or -1 if it doesn't exist.

func InsertAfter

func InsertAfter(i int, stmt []build.Expr, expr build.Expr) []build.Expr

InsertAfter inserts an expression after index i.

func InsertAfterLastOfSameKind

func InsertAfterLastOfSameKind(stmt []build.Expr, expr *build.CallExpr) []build.Expr

InsertAfterLastOfSameKind inserts an expression after the last expression of the same kind.

func InsertAtEnd

func InsertAtEnd(stmt []build.Expr, expr build.Expr) []build.Expr

InsertAtEnd inserts an expression at the end of a list, before trailing comments.

func InsertLoad

func InsertLoad(stmts []build.Expr, location string, from, to []string) []build.Expr

InsertLoad inserts a load statement at the top of the list of statements. The load statement is constructed using a string location and two slices of from- and to-symbols. The function panics if the slices aren't of the same lentgh. Symbols that are already loaded from the given filepath are ignored. If stmts already contains a load for the location in arguments, appends the symbols to load to it.

func InterpretLabel

func InterpretLabel(target string) (buildFile string, pkg string, rule string)

InterpretLabel returns the name of the BUILD file to edit, the full package name, and the rule. It uses the pwd for resolving workspace file paths.

func InterpretLabelForWorkspaceLocation

func InterpretLabelForWorkspaceLocation(root string, target string) (buildFile string, pkg string, rule string)

InterpretLabelForWorkspaceLocation returns the name of the BUILD file to edit, the full package name, and the rule. It takes a workspace-rooted directory to use.

func IsIntList

func IsIntList(attr string) bool

IsIntList returns true for all attributes whose type is an int list.

func IsList

func IsList(attr string) bool

IsList returns true for all attributes whose type is a list.

func IsString

func IsString(attr string) bool

IsString returns true for all attributes whose type is a string or a label.

func IsStringDict

func IsStringDict(attr string) bool

IsStringDict returns true for all attributes whose type is a string dictionary.

func LabelsEqual

func LabelsEqual(label1, label2, pkg string) bool

LabelsEqual returns true if label1 and label2 are equal. Deprecated; use `labels.Equal` instead

func ListAttributeDelete

func ListAttributeDelete(rule *build.Rule, attr, item, pkg string) *build.StringExpr

ListAttributeDelete deletes string item from list attribute attr, deletes attr if empty, and returns the StringExpr deleted, or nil otherwise.

func ListDelete

func ListDelete(e build.Expr, item, pkg string) (deleted *build.StringExpr)

ListDelete deletes the item from a list expression in e and returns the StringExpr deleted, or nil otherwise.

func ListFind

func ListFind(e build.Expr, item string, pkg string) *build.StringExpr

ListFind looks for a string in the list expression (which may be a concatenation of lists). It returns the element if it is found. nil otherwise.

func ListReplace

func ListReplace(e build.Expr, old, value, pkg string) bool

ListReplace replaces old with value in all lists in e and returns a Boolean to indicate whether the replacement was successful.

func ListSubstitute

func ListSubstitute(e build.Expr, oldRegexp *regexp.Regexp, newTemplate string) bool

ListSubstitute replaces strings matching a regular expression in all lists in e and returns a Boolean to indicate whether the replacement was successful.

func MoveAllListAttributeValues

func MoveAllListAttributeValues(rule *build.Rule, oldAttr, newAttr, pkg string, vars *map[string]*build.AssignExpr) error

MoveAllListAttributeValues moves all values from list attribute oldAttr to newAttr, and deletes oldAttr.

func NewLoad

func NewLoad(location string, from, to []string) *build.LoadStmt

NewLoad creates a new LoadStmt node

func PackageDeclaration

func PackageDeclaration(f *build.File) *build.Rule

PackageDeclaration returns the package declaration. If it doesn't exist, it is created at the top of the BUILD file, after optional docstring, comments, and load statements.

func ParseLabel

func ParseLabel(target string) (string, string, string)

ParseLabel parses a Blaze label (eg. //devtools/buildozer:rule), and returns the repo name ("" for the main repo), package (with leading slashes trimmed) and rule name (e.g. ["", "devtools/buildozer", "rule"]). Deprecated; use `labels.Parse` instead

func RemoveEmptyPackage

func RemoveEmptyPackage(f *build.File) *build.File

RemoveEmptyPackage removes empty package declarations from the file, i.e.:

package()

This might appear because of a buildozer transformation (e.g. when removing a package attribute). Removing it is required for the file to be valid.

func RemoveEmptySelectsAndConcatLists

func RemoveEmptySelectsAndConcatLists(e build.Expr) build.Expr

RemoveEmptySelectsAndConcatLists iterates the tree in order to turn empty selects into empty lists and adjacent lists are concatenated

func RemoveFromList

func RemoveFromList(li *build.ListExpr, item, pkg string, deleted **build.StringExpr)

RemoveFromList removes one element from a ListExpr and stores the deleted StringExpr at the address pointed by the last parameter

func RenameAttribute

func RenameAttribute(r *build.Rule, oldName, newName string) error

RenameAttribute renames an attribute in a rule.

func ReplaceLoad

func ReplaceLoad(stmts []build.Expr, location string, from, to []string) []build.Expr

ReplaceLoad removes load statements for passed to-symbols and replaces them with a new load at the top of the list of statements. The new load statement is constructed using a string location and two slices of from- and to-symbols. If stmts already contains a load for the location in arguments, appends the symbols to load to it. The function panics if the slices aren't of the same lentgh.

func ResolveAttr

func ResolveAttr(r *build.Rule, attr, pkg string)

ResolveAttr extracts common elements of the lists inside select dictionaries and adds them at attribute level rather than select level, as well as turns empty selects into empty lists and concatenates adjacent lists

func SelectDelete

func SelectDelete(e build.Expr, item, pkg string, deleted **build.StringExpr)

SelectDelete removes the item from all the lists which are values in the dictionary of every select

func SelectListsIntersection

func SelectListsIntersection(sel *build.CallExpr, pkg string) (intersection []build.Expr)

SelectListsIntersection returns the intersection of the lists of strings inside the dictionary argument of the select expression given as a parameter

func ShortenLabel

func ShortenLabel(label, pkg string) string

ShortenLabel rewrites labels to use the canonical form (the form recommended by build-style). Doesn't do anything if `--shorten_label=false` flag is provided. Use `labels.Shorten` to shorten labels unconditionally.

func SplitOnSpaces

func SplitOnSpaces(input string) []string

SplitOnSpaces behaves like strings.Fields, except that spaces can be escaped. Also splits on linebreaks unless they are escaped too. " some dummy\\ string" -> ["some", "dummy string"]

func UsedSymbols

func UsedSymbols(stmt build.Expr) map[string]bool

UsedSymbols returns the set of symbols used in the BUILD file (variables, function names).

Types

type CmdEnvironment

type CmdEnvironment struct {
	File *build.File                  // the AST
	Rule *build.Rule                  // the rule to modify
	Vars map[string]*build.AssignExpr // global variables set in the build file
	Pkg  string                       // the full package name
	Args []string                     // the command-line arguments
	// contains filtered or unexported fields
}

CmdEnvironment stores the information the commands below have access to.

type CommandInfo

type CommandInfo struct {
	Fn       func(*Options, CmdEnvironment) (*build.File, error)
	PerRule  bool
	MinArg   int
	MaxArg   int
	Template string
}

CommandInfo provides a command function and info on incoming arguments.

type Options

type Options struct {
	Stdout            bool     // write changed BUILD file to stdout
	Buildifier        string   // path to buildifier binary
	Parallelism       int      // number of cores to use for concurrent actions
	NumIO             int      // number of concurrent actions
	CommandsFile      string   // file name to read commands from, use '-' for stdin (format:|-separated command line arguments to buildozer, excluding flags
	KeepGoing         bool     // apply all commands, even if there are failures
	FilterRuleTypes   []string // list of rule types to change, empty means all
	PreferEOLComments bool     // when adding a new comment, put it on the same line if possible
	RootDir           string   // If present, use this folder rather than $PWD to find the root dir
	Quiet             bool     // suppress informational messages.
	EditVariables     bool     // for attributes that simply assign a variable (e.g. hdrs = LIB_HDRS), edit the build variable instead of appending to the attribute.
	IsPrintingProto   bool     // output serialized devtools.buildozer.Output protos instead of human-readable strings
}

Options represents choices about how buildozer should behave.

func NewOpts

func NewOpts() *Options

NewOpts returns a new Options struct with some defaults set.

Jump to

Keyboard shortcuts

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