@@ -66,6 +66,35 @@ func matchesAnyGlob(s string, globs []string) bool {
6666 return false
6767}
6868
69+ // validateExistingRules checks existing Python rules in the BUILD file and return the rules with invalid srcs.
70+ func (py * Python ) validateExistingRules (args language.GenerateArgs ) (emptyRules []* rule.Rule ) {
71+ if args .File == nil {
72+ return
73+ }
74+ regularFiles := args .RegularFiles
75+ regularFilesMap := make (map [string ]struct {})
76+ for _ , file := range regularFiles {
77+ regularFilesMap [file ] = struct {}{}
78+ }
79+ for _ , existingRule := range args .File .Rules {
80+ if _ , ok := py .Kinds ()[existingRule .Kind ()]; ! ok {
81+ continue
82+ }
83+ allInvalidSrcs := true
84+ for _ , src := range existingRule .AttrStrings ("srcs" ) {
85+ if _ , ok := regularFilesMap [src ]; ok {
86+ allInvalidSrcs = false
87+ break
88+ }
89+ }
90+ // If all srcs are invalid, delete the rule.
91+ if allInvalidSrcs {
92+ emptyRules = append (emptyRules , newTargetBuilder (existingRule .Kind (), existingRule .Name (), args .Config .RepoRoot , args .Rel , nil ).build ())
93+ }
94+ }
95+ return emptyRules
96+ }
97+
6998// GenerateRules extracts build metadata from source files in a directory.
7099// GenerateRules is called in each directory where an update is requested
71100// in depth-first post-order.
@@ -225,7 +254,6 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
225254
226255 var result language.GenerateResult
227256 result .Gen = make ([]* rule.Rule , 0 )
228-
229257 collisionErrors := singlylinkedlist .New ()
230258
231259 appendPyLibrary := func (srcs * treeset.Set , pyLibraryTargetName string ) {
@@ -473,7 +501,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
473501 result .Gen = append (result .Gen , pyTest )
474502 result .Imports = append (result .Imports , pyTest .PrivateAttr (config .GazelleImportsKey ))
475503 }
476-
504+ // Validate existing rules have valid srcs
505+ if ! cfg .CoarseGrainedGeneration () {
506+ emptyRules := py .validateExistingRules (args )
507+ result .Empty = append (result .Empty , emptyRules ... )
508+ }
477509 if ! collisionErrors .Empty () {
478510 it := collisionErrors .Iterator ()
479511 for it .Next () {
0 commit comments