fix(gazelle): generate empty py_library only when need (#1905)
#1887 incorrectly generated an empty py_library for all dirs, although
it will eventually be removed because it is empty, but it will easily
conflict with other existing rules.
Fix this error, and only generate an empty py_library for bazel packages
with the same name py_library rule.
diff --git a/gazelle/python/generate.go b/gazelle/python/generate.go
index 7454339..ef49dd7 100644
--- a/gazelle/python/generate.go
+++ b/gazelle/python/generate.go
@@ -27,11 +27,12 @@
"github.com/bazelbuild/bazel-gazelle/label"
"github.com/bazelbuild/bazel-gazelle/language"
"github.com/bazelbuild/bazel-gazelle/rule"
- "github.com/bazelbuild/rules_python/gazelle/pythonconfig"
"github.com/bmatcuk/doublestar/v4"
"github.com/emirpasic/gods/lists/singlylinkedlist"
"github.com/emirpasic/gods/sets/treeset"
godsutils "github.com/emirpasic/gods/utils"
+
+ "github.com/bazelbuild/rules_python/gazelle/pythonconfig"
)
const (
@@ -270,6 +271,23 @@
}
}
+ // If we're doing per-file generation, srcs could be empty at this point, meaning we shouldn't make a py_library.
+ // If there is already a package named py_library target before, we should generate an empty py_library.
+ if srcs.Empty() {
+ if args.File == nil {
+ return
+ }
+ generateEmptyLibrary := false
+ for _, r := range args.File.Rules {
+ if r.Kind() == actualPyLibraryKind && r.Name() == pyLibraryTargetName {
+ generateEmptyLibrary = true
+ }
+ }
+ if !generateEmptyLibrary {
+ return
+ }
+ }
+
// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
// generating. If so, we have to throw an error since Gazelle won't
diff --git a/gazelle/python/testdata/remove_invalid_library/others/BUILD.in b/gazelle/python/testdata/remove_invalid_library/others/BUILD.in
new file mode 100644
index 0000000..5578327
--- /dev/null
+++ b/gazelle/python/testdata/remove_invalid_library/others/BUILD.in
@@ -0,0 +1,5 @@
+genrule(
+ name = "others", # same to directory name
+ outs = ["data.txt"],
+ cmd = "echo foo bar baz > $@",
+)
\ No newline at end of file
diff --git a/gazelle/python/testdata/remove_invalid_library/others/BUILD.out b/gazelle/python/testdata/remove_invalid_library/others/BUILD.out
new file mode 100644
index 0000000..5578327
--- /dev/null
+++ b/gazelle/python/testdata/remove_invalid_library/others/BUILD.out
@@ -0,0 +1,5 @@
+genrule(
+ name = "others", # same to directory name
+ outs = ["data.txt"],
+ cmd = "echo foo bar baz > $@",
+)
\ No newline at end of file