Documentation ¶
Overview ¶
Package edit provides high-level auxiliary functions for AST manipulation on BUILD files.
Index ¶
- Variables
- func AddValueToList(oldList build.Expr, pkg string, item build.Expr, sorted bool) build.Expr
- func AddValueToListAttribute(r *build.Rule, name string, pkg string, item build.Expr, ...)
- func AllLists(e build.Expr) []*build.ListExpr
- func AllSelects(e build.Expr) []*build.CallExpr
- func AllStrings(e build.Expr) []*build.StringExpr
- func AppendToLoad(load *build.LoadStmt, from, to []string) bool
- func Buildozer(opts *Options, args []string) int
- func ComputeIntersection(list1, list2 []build.Expr) []build.Expr
- func ContainsComments(expr build.Expr, str string) bool
- func ContainsLabels(kind, attr string) bool
- func DeleteRule(f *build.File, rule *build.Rule) *build.File
- func DeleteRuleByKind(f *build.File, kind string) *build.File
- func DeleteRuleByName(f *build.File, name string) *build.File
- func DictionaryDelete(dict *build.DictExpr, key string) (deleted build.Expr)
- func DictionaryGet(dict *build.DictExpr, key string) build.Expr
- func DictionarySet(dict *build.DictExpr, key string, value build.Expr) build.Expr
- func EditFunction(v build.Expr, name string, ...) build.Expr
- func ExistingPackageDeclaration(f *build.File) *build.Rule
- func ExprToRule(expr build.Expr, kind string) (*build.Rule, bool)
- func FindExportedFile(f *build.File, name string) *build.Rule
- func FindRuleByName(f *build.File, name string) *build.Rule
- func FirstList(e build.Expr) *build.ListExpr
- func FixFile(f *build.File, pkg string, fixes []string) *build.File
- func FixRule(f *build.File, pkg string, rule *build.Rule, fixes []string) *build.File
- func IndexOfLast(stmt []build.Expr, Kind string) int
- func IndexOfRuleByName(f *build.File, name string) (int, *build.Rule)
- func InsertAfter(i int, stmt []build.Expr, expr build.Expr) []build.Expr
- func InsertAfterLastOfSameKind(stmt []build.Expr, expr *build.CallExpr) []build.Expr
- func InsertAtEnd(stmt []build.Expr, expr build.Expr) []build.Expr
- func InsertLoad(stmts []build.Expr, location string, from, to []string) []build.Expr
- func InterpretLabel(target string) (buildFile string, pkg string, rule string)
- func InterpretLabelForWorkspaceLocation(root string, target string) (buildFile string, pkg string, rule string)
- func IsIntList(attr string) bool
- func IsList(attr string) bool
- func IsString(attr string) bool
- func IsStringDict(attr string) bool
- func LabelsEqual(label1, label2, pkg string) bool
- func ListAttributeDelete(rule *build.Rule, attr, item, pkg string) *build.StringExpr
- func ListDelete(e build.Expr, item, pkg string) (deleted *build.StringExpr)
- func ListFind(e build.Expr, item string, pkg string) *build.StringExpr
- func ListReplace(e build.Expr, old, value, pkg string) bool
- func ListSubstitute(e build.Expr, oldRegexp *regexp.Regexp, newTemplate string) bool
- func MoveAllListAttributeValues(rule *build.Rule, oldAttr, newAttr, pkg string, ...) error
- func NewLoad(location string, from, to []string) *build.LoadStmt
- func PackageDeclaration(f *build.File) *build.Rule
- func ParseLabel(target string) (string, string, string)
- func RemoveEmptyPackage(f *build.File) *build.File
- func RemoveEmptySelectsAndConcatLists(e build.Expr) build.Expr
- func RemoveFromList(li *build.ListExpr, item, pkg string, deleted **build.StringExpr)
- func RenameAttribute(r *build.Rule, oldName, newName string) error
- func ReplaceLoad(stmts []build.Expr, location string, from, to []string) []build.Expr
- func ResolveAttr(r *build.Rule, attr, pkg string)
- func SelectDelete(e build.Expr, item, pkg string, deleted **build.StringExpr)
- func SelectListsIntersection(sel *build.CallExpr, pkg string) (intersection []build.Expr)
- func ShortenLabel(label, pkg string) string
- func SplitOnSpaces(input string) []string
- func UsedSymbols(stmt build.Expr) map[string]bool
- type CmdEnvironment
- type CommandInfo
- type Options
Constants ¶
This section is empty.
Variables ¶
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 )
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.
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.
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.
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.
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.
var Usage = func() {}
Usage is a user-overridden func to print the program usage.
Functions ¶
func AddValueToList ¶
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 ¶
AllLists returns all the lists concatenated in an expression. For example, in: glob(["*.go"]) + [":rule"] the function will return [[":rule"]].
func AllSelects ¶
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 ¶
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 ComputeIntersection ¶
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 ¶
ContainsComments returns whether the expr has a comment that includes str.
func ContainsLabels ¶
ContainsLabels returns true for all attributes whose type is a label or a label list.
func DeleteRule ¶
DeleteRule returns the AST without the specified rule
func DeleteRuleByKind ¶
DeleteRuleByKind removes the rules of the specified kind from the AST. Returns an updated copy of f.
func DeleteRuleByName ¶
DeleteRuleByName returns the AST without the rules that have the given name.
func DictionaryDelete ¶
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 ¶
DictionaryGet looks for the key in the dictionary expression, and returns the current value. If it is unset, it returns nil.
func DictionarySet ¶
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 ¶
ExistingPackageDeclaration returns the package declaration, or nil if there is none.
func ExprToRule ¶
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 ¶
FindExportedFile returns the first exports_files call which contains the file 'name', or nil if not found
func FindRuleByName ¶
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 ¶
FirstList works in the same way as AllLists, except that it returns only one list, or nil.
func FixRule ¶
FixRule aims to fix errors in BUILD files, remove deprecated features, and simplify the code.
func IndexOfLast ¶
IndexOfLast finds the index of the last expression of a specific kind.
func IndexOfRuleByName ¶
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 ¶
InsertAfter inserts an expression after index i.
func InsertAfterLastOfSameKind ¶
InsertAfterLastOfSameKind inserts an expression after the last expression of the same kind.
func InsertAtEnd ¶
InsertAtEnd inserts an expression at the end of a list, before trailing comments.
func InsertLoad ¶
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 ¶
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 IsStringDict ¶
IsStringDict returns true for all attributes whose type is a string dictionary.
func LabelsEqual ¶
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 ¶
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 ¶
ListReplace replaces old with value in all lists in e and returns a Boolean to indicate whether the replacement was successful.
func ListSubstitute ¶
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 PackageDeclaration ¶
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 ¶
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 ¶
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 ¶
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 ¶
RenameAttribute renames an attribute in a rule.
func ReplaceLoad ¶
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 ¶
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 ¶
SelectListsIntersection returns the intersection of the lists of strings inside the dictionary argument of the select expression given as a parameter
func ShortenLabel ¶
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 ¶
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"]
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.