Skip to content

Commit

Permalink
Preserve loads if they're different (#1137)
Browse files Browse the repository at this point in the history
WORKSPACE files currently allow shadowing loads (see
bazelbuild/bazel#17480), i.e. the following is
valid:

```starlark
load("//:one.bzl", "fn")

fn()

load("//:two.bzl", "fn")

fn()
```

Currently buildozer removes the second load because the symbol was
already loaded. This is incorrect - removing the second load changes the
behaviour of this file.

Instead, only delete a load of the last time it was loaded was from the
same place.
  • Loading branch information
illicitonion authored Mar 2, 2023
1 parent cf44629 commit a6ca93f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 14 additions & 0 deletions buildozer/buildozer_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -1970,6 +1970,14 @@ load(":bar.bzl", "bar") # bar
load(":qux.bzl", "qux")
# after
foobar()
load(":somewhere_else.bzl", "foobar")
foobar()
load(":somewhere_else.bzl", "foobar")
foobar()' 'fix unusedLoads' 'pkg/BUILD'
assert_equals '# TODO: refactor
Expand All @@ -1983,6 +1991,12 @@ load(":baz.bzl", "baz") # this is @unused
# before
# after
foobar()
load(":somewhere_else.bzl", "foobar")
foobar()
foobar()'
}

Expand Down
16 changes: 14 additions & 2 deletions edit/fix.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,9 @@ func cleanUnusedLoads(f *build.File) bool {
symbols := UsedSymbols(f)
fixed := false

// Map of symbol in this file -> modules it's loaded from
symbolsToModules := make(map[string][]string)

var all []build.Expr
for _, stmt := range f.Stmt {
load, ok := stmt.(*build.LoadStmt)
Expand All @@ -363,10 +366,19 @@ func cleanUnusedLoads(f *build.File) bool {
toSymbol := load.To[i]
if symbols[toSymbol.Name] {
// The symbol is actually used

// If the most recent load for this symbol was from the same file, remove it.
previousModules := symbolsToModules[toSymbol.Name]
if len(previousModules) > 0 {
if previousModules[len(previousModules)-1] == load.Module.Value {
fixed = true
continue
}
}
symbolsToModules[toSymbol.Name] = append(symbolsToModules[toSymbol.Name], load.Module.Value)

fromSymbols = append(fromSymbols, fromSymbol)
toSymbols = append(toSymbols, toSymbol)
// If the same symbol is loaded twice, we'll remove it.
delete(symbols, toSymbol.Name)
} else {
fixed = true
}
Expand Down

0 comments on commit a6ca93f

Please sign in to comment.