Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use apparent repo names when fixing loads #1321

Merged
merged 2 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions edit/bzlmod/bzlmod.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ limitations under the License.
package bzlmod

import (
"path"

"github.com/bazelbuild/buildtools/build"
"github.com/bazelbuild/buildtools/labels"
)
Expand Down Expand Up @@ -348,3 +350,85 @@ func lastProxyUsage(f *build.File, proxies []string) (lastUsage int, lastProxy s

return lastUsage, lastProxy
}

// ExtractModuleToApparentNameMapping collects the mapping of module names (e.g. "rules_go") to
// user-configured apparent names (e.g. "my_rules_go") from the repo's MODULE.bazel, if it exists.
// The given function is called with a repo-relative, slash-separated path and should return the
// content of the MODULE.bazel or *.MODULE.bazel file at that path, or nil if the file does not
// exist.
// See https://bazel.build/external/module#repository_names_and_strict_deps for more information on
// apparent names.
func ExtractModuleToApparentNameMapping(fileReader func(relPath string) *build.File) func(string) string {
moduleToApparentName := collectApparentNames(fileReader, "MODULE.bazel")

return func(moduleName string) string {
return moduleToApparentName[moduleName]
}
}

// Collects the mapping of module names (e.g. "rules_go") to user-configured apparent names (e.g.
// "my_rules_go"). See https://bazel.build/external/module#repository_names_and_strict_deps for more
// information on apparent names.
func collectApparentNames(fileReader func(relPath string) *build.File, relPath string) map[string]string {
apparentNames := make(map[string]string)
seenFiles := make(map[string]struct{})
filesToProcess := []string{relPath}

for len(filesToProcess) > 0 {
f := filesToProcess[0]
filesToProcess = filesToProcess[1:]
if _, seen := seenFiles[f]; seen {
continue
}
seenFiles[f] = struct{}{}
bf := fileReader(f)
if bf == nil {
return nil
}
names, includeLabels := collectApparentNamesAndIncludes(bf)
for name, apparentName := range names {
apparentNames[name] = apparentName
}
for _, includeLabel := range includeLabels {
l := labels.Parse(includeLabel)
p := path.Join(l.Package, l.Target)
filesToProcess = append(filesToProcess, p)
}
}

return apparentNames
}

func collectApparentNamesAndIncludes(f *build.File) (map[string]string, []string) {
apparentNames := make(map[string]string)
var includeLabels []string

for _, dep := range f.Rules("") {
if dep.ExplicitName() == "" {
if ident, ok := dep.Call.X.(*build.Ident); !ok || ident.Name != "include" {
continue
}
if len(dep.Call.List) != 1 {
continue
}
if str, ok := dep.Call.List[0].(*build.StringExpr); ok {
includeLabels = append(includeLabels, str.Value)
}
continue
}
if dep.Kind() != "module" && dep.Kind() != "bazel_dep" {
continue
}
// We support module in addition to bazel_dep to handle language repos that use Gazelle to
// manage their own BUILD files.
if name := dep.AttrString("name"); name != "" {
if repoName := dep.AttrString("repo_name"); repoName != "" {
apparentNames[name] = repoName
} else {
apparentNames[name] = name
}
}
}

return apparentNames, includeLabels
}
8 changes: 7 additions & 1 deletion tables/tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,13 @@ var PyNativeRules = []string{
var PyLoadPath = "@rules_python//python:defs.bzl"

// ProtoLoadPathPrefix is the load path prefix for the Starlark Proto Rules.
var ProtoLoadPathPrefix = "@com_google_protobuf//bazel"
var ProtoLoadPathPrefix = "@protobuf//bazel"

// ModuleToLegacyRepoName contains the mapping from module name to WORKSPACE repository name
// for modules with load fixes if those names are different.
var ModuleToLegacyRepoName = map[string]string{
"protobuf": "com_google_protobuf",
}

// IsModuleOverride contains the names of all Bzlmod module overrides available in MODULE.bazel.
var IsModuleOverride = map[string]bool{
Expand Down
1 change: 1 addition & 0 deletions warn/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ go_library(
"//build",
"//bzlenv",
"//edit",
"//edit/bzlmod",
"//labels",
"//tables",
],
Expand Down
112 changes: 56 additions & 56 deletions warn/warn.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,40 +118,64 @@ var RuleWarningMap = map[string]func(call *build.CallExpr, pkg string) *LinterFi

// FileWarningMap lists the warnings that run on the whole file.
var FileWarningMap = map[string]func(f *build.File) []*LinterFinding{
"attr-applicable_licenses": attrApplicableLicensesWarning,
"attr-cfg": attrConfigurationWarning,
"attr-license": attrLicenseWarning,
"attr-licenses": attrLicensesWarning,
"attr-non-empty": attrNonEmptyWarning,
"attr-output-default": attrOutputDefaultWarning,
"attr-single-file": attrSingleFileWarning,
"build-args-kwargs": argsKwargsInBuildFilesWarning,
"bzl-visibility": bzlVisibilityWarning,
"confusing-name": confusingNameWarning,
"constant-glob": constantGlobWarning,
"ctx-actions": ctxActionsWarning,
"ctx-args": contextArgsAPIWarning,
"depset-items": depsetItemsWarning,
"depset-iteration": depsetIterationWarning,
"depset-union": depsetUnionWarning,
"dict-method-named-arg": dictMethodNamedArgWarning,
"dict-concatenation": dictionaryConcatenationWarning,
"duplicated-name": duplicatedNameWarning,
"filetype": fileTypeWarning,
"function-docstring": functionDocstringWarning,
"function-docstring-header": functionDocstringHeaderWarning,
"function-docstring-args": functionDocstringArgsWarning,
"function-docstring-return": functionDocstringReturnWarning,
"attr-applicable_licenses": attrApplicableLicensesWarning,
"attr-cfg": attrConfigurationWarning,
"attr-license": attrLicenseWarning,
"attr-licenses": attrLicensesWarning,
"attr-non-empty": attrNonEmptyWarning,
"attr-output-default": attrOutputDefaultWarning,
"attr-single-file": attrSingleFileWarning,
"build-args-kwargs": argsKwargsInBuildFilesWarning,
"bzl-visibility": bzlVisibilityWarning,
"confusing-name": confusingNameWarning,
"constant-glob": constantGlobWarning,
"ctx-actions": ctxActionsWarning,
"ctx-args": contextArgsAPIWarning,
"depset-items": depsetItemsWarning,
"depset-iteration": depsetIterationWarning,
"depset-union": depsetUnionWarning,
"dict-method-named-arg": dictMethodNamedArgWarning,
"dict-concatenation": dictionaryConcatenationWarning,
"duplicated-name": duplicatedNameWarning,
"filetype": fileTypeWarning,
"function-docstring": functionDocstringWarning,
"function-docstring-header": functionDocstringHeaderWarning,
"function-docstring-args": functionDocstringArgsWarning,
"function-docstring-return": functionDocstringReturnWarning,
"integer-division": integerDivisionWarning,
"keyword-positional-params": keywordPositionalParametersWarning,
"list-append": listAppendWarning,
"load": unusedLoadWarning,
"module-docstring": moduleDocstringWarning,
"name-conventions": nameConventionsWarning,
"native-build": nativeInBuildFilesWarning,
"native-package": nativePackageWarning,
"no-effect": noEffectWarning,
"output-group": outputGroupWarning,
"overly-nested-depset": overlyNestedDepsetWarning,
"package-name": packageNameWarning,
"package-on-top": packageOnTopWarning,
"print": printWarning,
"provider-params": providerParamsWarning,
"redefined-variable": redefinedVariableWarning,
"repository-name": repositoryNameWarning,
"rule-impl-return": ruleImplReturnWarning,
"return-value": missingReturnValueWarning,
"skylark-comment": skylarkCommentWarning,
"skylark-docstring": skylarkDocstringWarning,
"string-iteration": stringIterationWarning,
"uninitialized": uninitializedVariableWarning,
"unreachable": unreachableStatementWarning,
"unsorted-dict-items": unsortedDictItemsWarning,
"unused-variable": unusedVariableWarning,
}

// MultiFileWarningMap lists the warnings that run on the whole file, but may use other files.
var MultiFileWarningMap = map[string]func(f *build.File, fileReader *FileReader) []*LinterFinding{
"deprecated-function": deprecatedFunctionWarning,
"git-repository": nativeGitRepositoryWarning,
"http-archive": nativeHTTPArchiveWarning,
"integer-division": integerDivisionWarning,
"keyword-positional-params": keywordPositionalParametersWarning,
"list-append": listAppendWarning,
"load": unusedLoadWarning,
"module-docstring": moduleDocstringWarning,
"name-conventions": nameConventionsWarning,
"native-android": nativeAndroidRulesWarning,
"native-build": nativeInBuildFilesWarning,
"native-cc": nativeCcRulesWarning,
"native-java-binary": NativeJavaRulesWarning("java_binary"),
"native-java-import": NativeJavaRulesWarning("java_import"),
Expand All @@ -164,7 +188,6 @@ var FileWarningMap = map[string]func(f *build.File) []*LinterFinding{
"native-java-common": NativeJavaSymbolsWarning("java_common", "java_common"),
"native-java-info": NativeJavaSymbolsWarning("JavaInfo", "java_info"),
"native-java-plugin-info": NativeJavaSymbolsWarning("JavaPluginInfo", "java_plugin_info"),
"native-package": nativePackageWarning,
"native-proto": NativeProtoRulesWarning("proto_library"),
"native-java-proto": NativeProtoRulesWarning("java_proto_library"),
"native-java-lite-proto": NativeProtoRulesWarning("java_lite_proto_library"),
Expand All @@ -174,30 +197,7 @@ var FileWarningMap = map[string]func(f *build.File) []*LinterFinding{
"native-proto-common": nativeProtoSymbolsWarning("proto_common", "proto_common.bzl"),
"native-proto-lang-toolchain-info": nativeProtoSymbolsWarning("ProtoLangToolchainInfo", "proto_lang_toolchain_info.bzl"),
"native-py": nativePyRulesWarning,
"no-effect": noEffectWarning,
"output-group": outputGroupWarning,
"overly-nested-depset": overlyNestedDepsetWarning,
"package-name": packageNameWarning,
"package-on-top": packageOnTopWarning,
"print": printWarning,
"provider-params": providerParamsWarning,
"redefined-variable": redefinedVariableWarning,
"repository-name": repositoryNameWarning,
"rule-impl-return": ruleImplReturnWarning,
"return-value": missingReturnValueWarning,
"skylark-comment": skylarkCommentWarning,
"skylark-docstring": skylarkDocstringWarning,
"string-iteration": stringIterationWarning,
"uninitialized": uninitializedVariableWarning,
"unreachable": unreachableStatementWarning,
"unsorted-dict-items": unsortedDictItemsWarning,
"unused-variable": unusedVariableWarning,
}

// MultiFileWarningMap lists the warnings that run on the whole file, but may use other files.
var MultiFileWarningMap = map[string]func(f *build.File, fileReader *FileReader) []*LinterFinding{
"deprecated-function": deprecatedFunctionWarning,
"unnamed-macro": unnamedMacroWarning,
"unnamed-macro": unnamedMacroWarning,
}

// nonDefaultWarnings contains warnings that are enabled by default because they're not applicable
Expand Down
Loading