Skip to content

Commit

Permalink
[6.2.0] Add native.module_{name,version} (bazelbuild#17893)
Browse files Browse the repository at this point in the history
* Remove BzlmodRepoRuleHelper

The helper logic is only used in the BzlmodRepoRuleFunction so no need to have it in a separate place.
- Remove BzlmodRepoRuleHelper Interface & its implementations
- Refactor BzlmodRepoRuleFunction to use the helper logic
- Update tests and Build files accordingly

PiperOrigin-RevId: 486712547
Change-Id: I9a274a6a0afcc77be56bbe20e0c4d17c41c31c58

* Separate selection from bazel dependency graph

* Created new K/F/V for Bazel dependency graph named "BazelDepGraph"
* Refactored "BazelModuleResolution" to only run resolution (discovery, selection and checks) to create pruned and unpruned graph and not create any dependency value
* BazelDepGraphResolution calls BazelModuleResolution and extracts the dependency graph from it
* Updated tests

PiperOrigin-RevId: 499026445
Change-Id: Id1237f9d09015ffe8987d933431fccfcfa0c0963

* Add native.module_{name,version}

Extension authors often want to write some macro and change its behavior depending on which module is using it. For example, for rules_go, they want to look at the `go_deps` tags in a certain module and only allow access to repos generated from those tags.

We do this by introducing two new methods on `native`, callable only during the loading phase. They return the name and version of the module associated with the current repo. If the repo is from WORKSPACE, they return `None`. If the repo is generated by an extension, they return info about the module hosting the extension.

The implementation works by storing the "associated module" information in `RepositoryMappingValue`. I had attempted to store them in `BzlmodRepoRuleValue` or even `RepositoryDirectoryValue`, but those are not the right places since they might happen before we even evaluate the MODULE.bazel file (i.e. for non-registry overrides).

Fixes bazelbuild#17652.

RELNOTES: Added `native.module_name()` and `native.module_version()` to allow BUILD macro authors to acquire information about which Bazel module the current repo is associated with.
PiperOrigin-RevId: 518849334
Change-Id: I06b4bc95b5a57de2412ee02544240b054c708165

* fix BUILD

* remove test case that was accidentally cherry-picked

---------

Co-authored-by: salma-samy <[email protected]>
Co-authored-by: kshyanashree <[email protected]>
  • Loading branch information
3 people authored Mar 27, 2023
1 parent 10792ce commit 99b3f38
Show file tree
Hide file tree
Showing 48 changed files with 1,353 additions and 1,391 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.bazel.bzlmod.BazelDepGraphFunction;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleInspectorFunction;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleInspectorValue.AugmentedModule.ResolutionReason;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleResolutionFunction;
Expand Down Expand Up @@ -248,8 +249,9 @@ public ResolutionReason getResolutionReason() {
.addSkyFunction(
SkyFunctions.MODULE_FILE,
new ModuleFileFunction(registryFactory, directories.getWorkspace(), builtinModules))
.addSkyFunction(SkyFunctions.BAZEL_MODULE_RESOLUTION, new BazelModuleResolutionFunction())
.addSkyFunction(SkyFunctions.BAZEL_DEP_GRAPH, new BazelDepGraphFunction())
.addSkyFunction(SkyFunctions.BAZEL_MODULE_INSPECTION, new BazelModuleInspectorFunction())
.addSkyFunction(SkyFunctions.BAZEL_MODULE_RESOLUTION, new BazelModuleResolutionFunction())
.addSkyFunction(SkyFunctions.SINGLE_EXTENSION_EVAL, singleExtensionEvalFunction)
.addSkyFunction(SkyFunctions.SINGLE_EXTENSION_USAGES, new SingleExtensionUsagesFunction());
filesystem = runtime.getFileSystem();
Expand Down
20 changes: 2 additions & 18 deletions src/main/java/com/google/devtools/build/lib/bazel/bzlmod/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ java_library(
srcs = [
"AbridgedModule.java",
"ArchiveOverride.java",
"BazelDepGraphValue.java",
"BazelModuleResolutionValue.java",
"GitOverride.java",
"LocalPathOverride.java",
Expand Down Expand Up @@ -125,6 +126,7 @@ java_library(
java_library(
name = "resolution_impl",
srcs = [
"BazelDepGraphFunction.java",
"BazelModuleResolutionFunction.java",
"Discovery.java",
"ModuleExtensionContext.java",
Expand Down Expand Up @@ -191,24 +193,6 @@ java_library(
],
)

java_library(
name = "repo_rule_helper",
srcs = [
"BzlmodRepoRuleHelper.java",
"BzlmodRepoRuleHelperImpl.java",
],
deps = [
":common",
":registry",
":resolution",
"//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/events",
"//src/main/java/com/google/devtools/build/skyframe",
"//third_party:guava",
"//third_party:jsr305",
],
)

java_library(
name = "repo_rule_creator",
srcs = ["BzlmodRepoRuleCreator.java"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package com.google.devtools.build.lib.bazel.bzlmod;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleResolutionFunction.BazelModuleResolutionFunctionException;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.packages.LabelConverter;
import com.google.devtools.build.lib.server.FailureDetails.ExternalDeps.Code;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import javax.annotation.Nullable;

/**
* This function runs Bazel module resolution, extracts the dependency graph from it and creates a
* value containing all Bazel modules, along with a few lookup maps that help with further usage. By
* this stage, module extensions are not evaluated yet.
*/
public class BazelDepGraphFunction implements SkyFunction {

@Override
@Nullable
public SkyValue compute(SkyKey skyKey, Environment env)
throws SkyFunctionException, InterruptedException {

BazelModuleResolutionValue selectionResult =
(BazelModuleResolutionValue) env.getValue(BazelModuleResolutionValue.KEY);
if (env.valuesMissing()) {
return null;
}

ImmutableMap<ModuleKey, Module> depGraph = selectionResult.getResolvedDepGraph();
ImmutableMap<RepositoryName, ModuleKey> canonicalRepoNameLookup =
depGraph.keySet().stream()
.collect(toImmutableMap(ModuleKey::getCanonicalRepoName, key -> key));

// For each extension usage, we resolve (i.e. canonicalize) its bzl file label. Then we can
// group all usages by the label + name (the ModuleExtensionId).
ImmutableTable.Builder<ModuleExtensionId, ModuleKey, ModuleExtensionUsage>
extensionUsagesTableBuilder = ImmutableTable.builder();
for (Module module : depGraph.values()) {
LabelConverter labelConverter =
new LabelConverter(
PackageIdentifier.create(module.getCanonicalRepoName(), PathFragment.EMPTY_FRAGMENT),
module.getRepoMappingWithBazelDepsOnly());
for (ModuleExtensionUsage usage : module.getExtensionUsages()) {
try {
ModuleExtensionId moduleExtensionId =
ModuleExtensionId.create(
labelConverter.convert(usage.getExtensionBzlFile()), usage.getExtensionName());
extensionUsagesTableBuilder.put(moduleExtensionId, module.getKey(), usage);
} catch (LabelSyntaxException e) {
throw new BazelModuleResolutionFunctionException(
ExternalDepsException.withCauseAndMessage(
Code.BAD_MODULE,
e,
"invalid label for module extension found at %s",
usage.getLocation()),
Transience.PERSISTENT);
}
}
}
ImmutableTable<ModuleExtensionId, ModuleKey, ModuleExtensionUsage> extensionUsagesById =
extensionUsagesTableBuilder.buildOrThrow();

// Calculate a unique name for each used extension id.
BiMap<String, ModuleExtensionId> extensionUniqueNames = HashBiMap.create();
for (ModuleExtensionId id : extensionUsagesById.rowKeySet()) {
// Ensure that the resulting extension name (and thus the repository names derived from it) do
// not start with a tilde.
RepositoryName repository = id.getBzlFileLabel().getRepository();
String nonEmptyRepoPart;
if (repository.isMain()) {
nonEmptyRepoPart = "_main";
} else {
nonEmptyRepoPart = repository.getName();
}
String bestName = nonEmptyRepoPart + "~" + id.getExtensionName();
if (extensionUniqueNames.putIfAbsent(bestName, id) == null) {
continue;
}
int suffix = 2;
while (extensionUniqueNames.putIfAbsent(bestName + suffix, id) != null) {
suffix++;
}
}

return BazelDepGraphValue.create(
depGraph,
canonicalRepoNameLookup,
depGraph.values().stream().map(AbridgedModule::from).collect(toImmutableList()),
extensionUsagesById,
ImmutableMap.copyOf(extensionUniqueNames.inverse()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package com.google.devtools.build.lib.bazel.bzlmod;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.skyframe.SkyFunctions;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.util.Map;

/**
* The result of running Bazel module resolution, containing the Bazel module dependency graph
* post-version-resolution.
*/
@AutoValue
public abstract class BazelDepGraphValue implements SkyValue {
@SerializationConstant public static final SkyKey KEY = () -> SkyFunctions.BAZEL_DEP_GRAPH;

public static BazelDepGraphValue create(
ImmutableMap<ModuleKey, Module> depGraph,
ImmutableMap<RepositoryName, ModuleKey> canonicalRepoNameLookup,
ImmutableList<AbridgedModule> abridgedModules,
ImmutableTable<ModuleExtensionId, ModuleKey, ModuleExtensionUsage> extensionUsagesTable,
ImmutableMap<ModuleExtensionId, String> extensionUniqueNames) {
return new AutoValue_BazelDepGraphValue(
depGraph,
canonicalRepoNameLookup,
abridgedModules,
extensionUsagesTable,
extensionUniqueNames);
}

/**
* The post-selection dep graph. Must have BFS iteration order, starting from the root module. For
* any KEY in the returned map, it's guaranteed that {@code depGraph[KEY].getKey() == KEY}.
*/
public abstract ImmutableMap<ModuleKey, Module> getDepGraph();

/** A mapping from a canonical repo name to the key of the module backing it. */
public abstract ImmutableMap<RepositoryName, ModuleKey> getCanonicalRepoNameLookup();

/** All modules in the same order as {@link #getDepGraph}, but with limited information. */
public abstract ImmutableList<AbridgedModule> getAbridgedModules();

/**
* All module extension usages grouped by the extension's ID and the key of the module where this
* usage occurs. For each extension identifier ID, extensionUsagesTable[ID][moduleKey] is the
* ModuleExtensionUsage of ID in the module keyed by moduleKey.
*/
public abstract ImmutableTable<ModuleExtensionId, ModuleKey, ModuleExtensionUsage>
getExtensionUsagesTable();

/**
* A mapping from the ID of a module extension to a unique string that serves as its "name". This
* is not the same as the extension's declared name, as the declared name is only unique within
* the .bzl file, whereas this unique name is guaranteed to be unique across the workspace.
*/
public abstract ImmutableMap<ModuleExtensionId, String> getExtensionUniqueNames();

/**
* Returns the full {@link RepositoryMapping} for the given module, including repos from Bazel
* module deps and module extensions.
*/
public final RepositoryMapping getFullRepoMapping(ModuleKey key) {
ImmutableMap.Builder<String, RepositoryName> mapping = ImmutableMap.builder();
for (Map.Entry<ModuleExtensionId, ModuleExtensionUsage> e :
getExtensionUsagesTable().column(key).entrySet()) {
ModuleExtensionId extensionId = e.getKey();
ModuleExtensionUsage usage = e.getValue();
for (Map.Entry<String, String> entry : usage.getImports().entrySet()) {
String canonicalRepoName =
getExtensionUniqueNames().get(extensionId) + "~" + entry.getValue();
mapping.put(entry.getKey(), RepositoryName.createUnvalidated(canonicalRepoName));
}
}
return getDepGraph()
.get(key)
.getRepoMappingWithBazelDepsOnly()
.withAdditionalMappings(mapping.buildOrThrow());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public SkyValue compute(SkyKey skyKey, Environment env)
}
ImmutableMap<String, ModuleOverride> overrides = root.getOverrides();
ImmutableMap<ModuleKey, Module> unprunedDepGraph = resolutionValue.getUnprunedDepGraph();
ImmutableMap<ModuleKey, Module> resolvedDepGraph = resolutionValue.getDepGraph();
ImmutableMap<ModuleKey, Module> resolvedDepGraph = resolutionValue.getResolvedDepGraph();

ImmutableMap<ModuleKey, AugmentedModule> depGraph =
computeAugmentedGraph(unprunedDepGraph, resolvedDepGraph.keySet(), overrides);
Expand Down
Loading

0 comments on commit 99b3f38

Please sign in to comment.