// Copyright 2014 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.rules;
import static com.google.devtools.build.lib.syntax.SkylarkType.castMap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.extra.SpawnInfo;
import com.google.devtools.build.lib.analysis.AbstractConfiguredTarget;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.LocationExpander;
import com.google.devtools.build.lib.analysis.PseudoAction;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction.Substitution;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature;
import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature.Param;
import com.google.devtools.build.lib.syntax.BuiltinFunction;
import com.google.devtools.build.lib.syntax.Environment;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.EvalUtils;
import com.google.devtools.build.lib.syntax.Printer;
import com.google.devtools.build.lib.syntax.Runtime;
import com.google.devtools.build.lib.syntax.SkylarkList;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import com.google.devtools.build.lib.syntax.SkylarkNestedSet;
import com.google.devtools.build.lib.syntax.SkylarkSignatureProcessor;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.syntax.Type.ConversionException;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
// TODO(bazel-team): function argument names are often duplicated,
// figure out a nicely readable way to get rid of the duplications.
/**
* A helper class to provide an easier API for Skylark rule implementations
* and hide the original Java API. This is experimental code.
*/
public class SkylarkRuleImplementationFunctions {
// TODO(bazel-team): add all the remaining parameters
// TODO(bazel-team): merge executable and arguments
/**
* A Skylark built-in function to create and register a SpawnAction using a
* dictionary of parameters:
* createSpawnAction(
* inputs = [input1, input2, ...],
* outputs = [output1, output2, ...],
* executable = executable,
* arguments = [argument1, argument2, ...],
* mnemonic = 'Mnemonic',
* command = 'command',
* )
*/
@SkylarkSignature(
name = "action",
doc =
"Creates an action that runs an executable or a shell command. You must specify either "
+ "command or executable.",
objectType = SkylarkRuleContext.class,
returnType = Runtime.NoneType.class,
mandatoryPositionals = {
@Param(name = "self", type = SkylarkRuleContext.class, doc = "This RuleContext.")
},
mandatoryNamedOnly = {
@Param(
name = "outputs",
type = SkylarkList.class,
generic1 = Artifact.class,
doc = "list of the output files of the action"
)
},
optionalNamedOnly = {
@Param(
name = "inputs",
type = SkylarkList.class,
generic1 = Artifact.class,
defaultValue = "[]",
doc = "list of the input files of the action"
),
@Param(
name = "executable",
type = Object.class, // File or PathFragment or None
defaultValue = "None",
doc = "the executable file to be called by the action"
),
@Param(
name = "arguments",
type = SkylarkList.class,
generic1 = String.class,
defaultValue = "[]",
doc = "command line arguments of the action"
),
@Param(
name = "mnemonic",
type = String.class,
noneable = true,
defaultValue = "None",
doc = "a one-word description of the action, e.g. CppCompile or GoLink"
),
@Param(
name = "command",
type = Object.class, // string or ListOf(string) or NoneType
defaultValue = "None",
doc =
"shell command to execute. It is usually preferable to "
+ "use executable instead. Arguments are available with "
+ "$1, $2, etc."
),
@Param(
name = "progress_message",
type = String.class,
noneable = true,
defaultValue = "None",
doc =
"progress message to show to the user during the build, "
+ "e.g. \"Compiling foo.cc to create foo.o\""
),
@Param(
name = "use_default_shell_env",
type = Boolean.class,
defaultValue = "False",
doc = "whether the action should use the built in shell environment or not"
),
@Param(
name = "env",
type = Map.class,
noneable = true,
defaultValue = "None",
doc = "sets the dictionary of environment variables"
),
@Param(
name = "execution_requirements",
type = Map.class,
noneable = true,
defaultValue = "None",
doc =
"information for scheduling the action."
+ " See [tags](/docs/be/common-definitions.html#common.tags) for useful keys."
),
@Param(
name = "input_manifests",
type = Map.class,
noneable = true,
defaultValue = "None",
doc =
"sets the map of input manifests files; "
+ "they are typically generated by resolve_command"
)
},
useLocation = true
)
private static final BuiltinFunction createSpawnAction =
new BuiltinFunction("action") {
public Runtime.NoneType invoke(
SkylarkRuleContext ctx,
SkylarkList outputs,
SkylarkList inputs,
Object executableO,
SkylarkList arguments,
Object mnemonicO,
Object commandO,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envO,
Object executionRequirementsO,
Object inputManifestsO,
Location loc)
throws EvalException, ConversionException {
SpawnAction.Builder builder = new SpawnAction.Builder();
// TODO(bazel-team): builder still makes unnecessary copies of inputs, outputs and args.
boolean hasCommand = commandO != Runtime.NONE;
builder.addInputs(inputs.getContents(Artifact.class, "inputs"));
builder.addOutputs(outputs.getContents(Artifact.class, "outputs"));
if (hasCommand && arguments.size() > 0) {
// When we use a shell command, add an empty argument before other arguments.
// e.g. bash -c "cmd" '' 'arg1' 'arg2'
// bash will use the empty argument as the value of $0 (which we don't care about).
// arg1 and arg2 will be $1 and $2, as a user exects.
builder.addArgument("");
}
builder.addArguments(arguments.getContents(String.class, "arguments"));
if (executableO != Runtime.NONE) {
if (executableO instanceof Artifact) {
Artifact executable = (Artifact) executableO;
builder.addInput(executable);
FilesToRunProvider provider = ctx.getExecutableRunfiles(executable);
if (provider == null) {
builder.setExecutable(executable);
} else {
builder.setExecutable(provider);
}
} else if (executableO instanceof PathFragment) {
builder.setExecutable((PathFragment) executableO);
} else {
throw new EvalException(
loc,
"expected file or PathFragment for "
+ "executable but got "
+ EvalUtils.getDataTypeName(executableO)
+ " instead");
}
}
if ((commandO == Runtime.NONE) == (executableO == Runtime.NONE)) {
throw new EvalException(
loc, "You must specify either 'command' or 'executable' argument");
}
if (hasCommand) {
if (commandO instanceof String) {
builder.setShellCommand((String) commandO);
} else if (commandO instanceof SkylarkList) {
SkylarkList commandList = (SkylarkList) commandO;
if (commandList.size() < 3) {
throw new EvalException(loc, "'command' list has to be of size at least 3");
}
builder.setShellCommand(commandList.getContents(String.class, "command"));
} else {
throw new EvalException(
loc,
"expected string or list of strings for "
+ "command instead of "
+ EvalUtils.getDataTypeName(commandO));
}
}
// The actual command can refer to an executable from the inputs, which could
// require some runfiles. Consequently, we add the runfiles of every executable
// input file that is in HOST configuration to the action as a precaution.
addRequiredIndirectRunfiles(ctx, builder);
if (mnemonicO != Runtime.NONE) {
builder.setMnemonic((String) mnemonicO);
}
if (envO != Runtime.NONE) {
builder.setEnvironment(
ImmutableMap.copyOf(castMap(envO, String.class, String.class, "env")));
}
if (progressMessage != Runtime.NONE) {
builder.setProgressMessage((String) progressMessage);
}
if (EvalUtils.toBoolean(useDefaultShellEnv)) {
builder.useDefaultShellEnvironment();
}
if (executionRequirementsO != Runtime.NONE) {
builder.setExecutionInfo(
ImmutableMap.copyOf(
castMap(
executionRequirementsO,
String.class,
String.class,
"execution_requirements")));
}
if (inputManifestsO != Runtime.NONE) {
for (Map.Entry entry :
castMap(
inputManifestsO,
PathFragment.class,
Artifact.class,
"input manifest file map")
.entrySet()) {
builder.addInputManifest(entry.getValue(), entry.getKey());
}
}
// Always register the action
ctx.getRuleContext().registerAction(builder.build(ctx.getRuleContext()));
return Runtime.NONE;
}
};
/**
* Adds the runfiles of the given input files to the action builder when they are executable and
* in HOST configuration.
*/
private static void addRequiredIndirectRunfiles(
SkylarkRuleContext ctx, SpawnAction.Builder builder) {
RuleContext ruleContext = ctx.getRuleContext();
AttributeMap attrMap = ruleContext.attributes();
for (String attrName : attrMap.getAttributeNames()) {
Attribute attr = attrMap.getAttributeDefinition(attrName);
if (attr.isExecutable()
&& (attr.getConfigurationTransition() == ConfigurationTransition.HOST)) {
FilesToRunProvider prov = ruleContext.getExecutablePrerequisite(attrName, Mode.HOST);
if (prov != null) {
builder.addTool(prov);
}
}
}
}
@SkylarkSignature(name = "expand_location",
doc =
"Expands the given string so that all labels are replaced with the location "
+ "of their target file(s). Currently, the algorithm uses output, srcs, deps, "
+ "tools and data attributes for looking up mappings from label to locations.",
objectType = SkylarkRuleContext.class, returnType = String.class,
mandatoryPositionals = {
@Param(name = "self", type = SkylarkRuleContext.class, doc = "this context"),
@Param(name = "input", type = String.class, doc = "string to be expanded"),
},
optionalPositionals = {
@Param(name = "targets", type = SkylarkList.class,
generic1 = AbstractConfiguredTarget.class, defaultValue = "[]",
doc = "list of targets for additional lookup information"),
},
useLocation = true, useEnvironment = true)
private static final BuiltinFunction expandLocation = new BuiltinFunction("expand_location") {
@SuppressWarnings("unused")
public String invoke(SkylarkRuleContext ctx, String input, SkylarkList targets,
Location loc, Environment env) throws EvalException {
try {
return new LocationExpander(ctx.getRuleContext(),
makeLabelMap(targets.getContents(AbstractConfiguredTarget.class, "targets")), false)
.expand(input);
} catch (IllegalStateException ise) {
throw new EvalException(loc, ise);
}
}
};
/**
* Builds a map: Label -> List of files from the given labels
* @param knownLabels List of known labels
* @return Immutable map with immutable collections as values
*/
private static ImmutableMap