com.google.devtools.build.lib.analysis.RuleContext.attributes() - java examples

Here are the examples of the java api com.google.devtools.build.lib.analysis.RuleContext.attributes() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

103 Examples 7

19 View Complete Implementation : ProtoCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private static boolean hasValidMigrationTag(RuleContext ruleContext) {
    return ruleContext.attributes().get("tags", Type.STRING_LIST).contains(PROTO_RULES_MIGRATION_LABEL);
}

19 View Complete Implementation : JavaCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private static List<TransitiveInfoCollection> getRuntimeDeps(RuleContext ruleContext) {
    // We need to check here because there are clreplacedes inheriting from this clreplaced that implement
    // rules that don't have this attribute.
    if (ruleContext.attributes().has("runtime_deps", BuildType.LABEL_LIST)) {
        return ImmutableList.copyOf(ruleContext.getPrerequisites("runtime_deps", Mode.TARGET));
    } else {
        return ImmutableList.of();
    }
}

19 View Complete Implementation : AndroidInstrumentationTestBase.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Checks expected rule invariants, throws rule errors if anything is set wrong.
 */
private static void validateRuleContext(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    if (getInstrumentationProvider(ruleContext) == null) {
        ruleContext.throwWithAttributeError("test_app", String.format("The android_binary target %s is missing an 'instruments' attribute. Please set " + "it to the label of the android_binary under test.", ruleContext.attributes().get("test_app", BuildType.LABEL)));
    }
}

19 View Complete Implementation : ProtoAttributes.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns whether the target is an objc_proto_library. It does so by making sure that the
 * portable_proto_filters attribute exists in this target's attributes (even if it's empty).
 */
boolean isObjcProtoLibrary() {
    return ruleContext.attributes().has(PORTABLE_PROTO_FILTERS_ATTR);
}

19 View Complete Implementation : JavaToolchain.java
Copyright Apache License 2.0
Author : bazelbuild
private static ImmutableListMultimap<String, String> getCompatibleJavacOptions(RuleContext ruleContext) {
    ImmutableListMultimap.Builder<String, String> result = ImmutableListMultimap.builder();
    for (Map.Entry<String, List<String>> entry : ruleContext.attributes().get("compatible_javacopts", Type.STRING_LIST_DICT).entrySet()) {
        result.putAll(entry.getKey(), JavaHelper.tokenizeJavaOptions(entry.getValue()));
    }
    return result.build();
}

19 View Complete Implementation : Filegroup.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException, ActionConflictException {
    String outputGroupName = ruleContext.attributes().get("output_group", Type.STRING);
    if (outputGroupName.endsWith(INTERNAL_SUFFIX)) {
        ruleContext.throwWithAttributeError("output_group", String.format(ILLEGAL_OUTPUT_GROUP_ERROR, outputGroupName));
    }
    NestedSet<Artifact> filesToBuild = outputGroupName.isEmpty() ? PrerequisiteArtifacts.nestedSet(ruleContext, "srcs", Mode.TARGET) : getArtifactsForOutputGroup(outputGroupName, ruleContext.getPrerequisites("srcs", Mode.TARGET));
    NestedSet<Artifact> middleman = CompilationHelper.getAggregatingMiddleman(ruleContext, Actions.escapeLabel(ruleContext.getLabel()), filesToBuild);
    InstrumentedFilesInfo instrumentedFilesProvider = InstrumentedFilesCollector.collectTransitive(ruleContext, // what do *we* know about whether this is a source file or not
    new InstrumentationSpec(FileTypeSet.ANY_FILE, "srcs", "deps", "data"), /* reportedToActualSources= */
    NestedSetBuilder.create(Order.STABLE_ORDER));
    RunfilesProvider runfilesProvider = RunfilesProvider.withData(new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES).build(), // If you're visiting a filegroup as data, then we also visit its data as data.
    new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addTransitiveArtifacts(filesToBuild).addDataDeps(ruleContext).build());
    return new RuleConfiguredTargetBuilder(ruleContext).add(RunfilesProvider.clreplaced, runfilesProvider).setFilesToBuild(filesToBuild).setRunfilesSupport(null, getExecutable(filesToBuild)).addNativeDeclaredProvider(instrumentedFilesProvider).add(MiddlemanProvider.clreplaced, new MiddlemanProvider(middleman)).add(FilegroupPathProvider.clreplaced, new FilegroupPathProvider(getFilegroupPath(ruleContext))).build();
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Reports an attribute error if the {@code default_python_version} attribute is set but
 * disallowed by the configuration.
 */
private void validateOldVersionAttrNotUsedIfDisabled() {
    AttributeMap attrs = ruleContext.attributes();
    if (!attrs.has(DEFAULT_PYTHON_VERSION_ATTRIBUTE, Type.STRING)) {
        return;
    }
    PythonVersion value;
    try {
        value = PythonVersion.parseTargetOrSentinelValue(attrs.get(DEFAULT_PYTHON_VERSION_ATTRIBUTE, Type.STRING));
    } catch (IllegalArgumentException e) {
        // Should be reported by validateTargetPythonVersionAttr(); no action required here.
        return;
    }
    PythonConfiguration config = ruleContext.getFragment(PythonConfiguration.clreplaced);
    if (value != PythonVersion._INTERNAL_SENTINEL && !config.oldPyVersionApiAllowed()) {
        ruleContext.attributeError(DEFAULT_PYTHON_VERSION_ATTRIBUTE, "the 'default_python_version' attribute is disabled by the " + "'--incompatible_remove_old_python_version_api' flag");
    }
}

19 View Complete Implementation : ConstraintSemantics.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Validity-checks this rule's constraint-related attributes. Returns true if all is good,
 * returns false and reports appropriate errors if there are any problems.
 */
private boolean validateAttributes(RuleContext ruleContext) {
    AttributeMap attributes = ruleContext.attributes();
    // Report an error if "restricted to" is explicitly set to nothing. Even if this made
    // conceptual sense, we don't know which groups we should apply that to.
    String restrictionAttr = RuleClreplaced.RESTRICTED_ENVIRONMENT_ATTR;
    List<? extends TransitiveInfoCollection> restrictionEnvironments = ruleContext.getPrerequisites(restrictionAttr, RuleConfiguredTarget.Mode.DONT_CHECK);
    if (restrictionEnvironments.isEmpty() && attributes.isAttributeValueExplicitlySpecified(restrictionAttr)) {
        attributeError(ruleContext, restrictionAttr, "attribute cannot be empty");
        return false;
    }
    return true;
}

19 View Complete Implementation : JavaHelper.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns true if the given Label is of the pseudo-cc_binary that tells Bazel a Java target's
 * JAVABIN is never to be replaced by the contents of --java_launcher; only the JDK's launcher
 * will ever be used.
 */
public static boolean isJdkLauncher(RuleContext ruleContext, Label label) {
    if (!ruleContext.attributes().has("$no_launcher")) {
        return false;
    }
    List<Label> noLauncherAttribute = ruleContext.attributes().get("$no_launcher", NODEP_LABEL_LIST);
    return noLauncherAttribute != null && noLauncherAttribute.contains(label);
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
private static List<Artifact> getDirectSetterStoreFiles(RuleContext context) {
    ImmutableList.Builder<Artifact> setterStoreFiles = ImmutableList.builder();
    if (context.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<DataBindingV2Provider> providers = context.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET, DataBindingV2Provider.PROVIDER);
        for (DataBindingV2Provider provider : providers) {
            setterStoreFiles.addAll(provider.getSetterStores());
        }
    }
    return setterStoreFiles.build();
}

19 View Complete Implementation : MultiArchSplitTransitionProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the apple platform type in the current rule context.
 *
 * @throws RuleErrorException if the platform type attribute in the current rulecontext is
 *     an invalid value
 */
public static PlatformType getPlatformType(RuleContext ruleContext) throws RuleErrorException {
    String attributeValue = ruleContext.attributes().get(PlatformRule.PLATFORM_TYPE_ATTR_NAME, STRING);
    try {
        return getPlatformType(attributeValue);
    } catch (@SuppressWarnings("UnusedException") ApplePlatform.UnsupportedPlatformTypeException exception) {
        throw ruleContext.throwWithAttributeError(PlatformRule.PLATFORM_TYPE_ATTR_NAME, String.format(UNSUPPORTED_PLATFORM_TYPE_ERROR_FORMAT, attributeValue));
    }
}

19 View Complete Implementation : AppleBinary.java
Copyright Apache License 2.0
Author : bazelbuild
private static BinaryType getBinaryType(RuleContext ruleContext) {
    String binaryTypeString = ruleContext.attributes().get(AppleBinaryRule.BINARY_TYPE_ATTR, STRING);
    return BinaryType.fromString(binaryTypeString);
}

19 View Complete Implementation : CcCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean hasAttribute(String name, Type<?> type) {
    return ruleContext.attributes().has(name, type);
}

19 View Complete Implementation : ProtoCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private static PathFragment getPathFragmentAttribute(RuleContext ruleContext, String attributeName) {
    if (!ruleContext.attributes().has(attributeName)) {
        return null;
    }
    if (!ruleContext.attributes().isAttributeValueExplicitlySpecified(attributeName)) {
        return null;
    }
    String replacedtring = ruleContext.attributes().get(attributeName, STRING);
    if (!PathFragment.isNormalized(replacedtring)) {
        ruleContext.attributeError(attributeName, "should be normalized (without uplevel references or '.' path segments)");
        return null;
    }
    return PathFragment.create(replacedtring);
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
private static ImmutableList<Artifact> getTransitiveBRFiles(RuleContext context) {
    ImmutableList.Builder<Artifact> brFiles = ImmutableList.builder();
    if (context.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<DataBindingV2Provider> providers = context.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET, DataBindingV2Provider.PROVIDER);
        for (DataBindingV2Provider provider : providers) {
            brFiles.addAll(provider.getTransitiveBRFiles().toList());
        }
    }
    return brFiles.build();
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the parsed value of the "srcs_version" attribute.
 */
private static PythonVersion initSrcsVersionAttr(RuleContext ruleContext) {
    String attrValue = ruleContext.attributes().get("srcs_version", Type.STRING);
    try {
        return PythonVersion.parseSrcsValue(attrValue);
    } catch (IllegalArgumentException ex) {
        // Should already have been disallowed in the rule.
        ruleContext.attributeError("srcs_version", String.format("'%s' is not a valid value. Expected one of: %s", attrValue, Joiner.on(", ").join(PythonVersion.SRCS_STRINGS)));
        return PythonVersion.DEFAULT_SRCS_VALUE;
    }
}

19 View Complete Implementation : JavaCommon.java
Copyright Apache License 2.0
Author : bazelbuild
public static List<TransitiveInfoCollection> getExports(RuleContext ruleContext) {
    // We need to check here because there are clreplacedes inheriting from this clreplaced that implement
    // rules that don't have this attribute.
    if (ruleContext.attributes().has("exports", BuildType.LABEL_LIST)) {
        return ImmutableList.copyOf(ruleContext.getPrerequisites("exports", Mode.TARGET));
    } else {
        return ImmutableList.of();
    }
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns a {@link PyRuntimeInfo} representing the runtime to use for this target, as retrieved
 * from the resolved toolchain.
 *
 * <p>This may only be called for executable Python rules (rules defining the attribute
 * "$py_toolchain_type", i.e. {@code py_binary} and {@code py_test}). In addition, it may not be
 * called if {@link #shouldGetRuntimeFromToolchain()} returns false.
 *
 * <p>If there was a problem retrieving the runtime information from the toolchain, null is
 * returned. An error would have already been reported on the rule context at {@code PyCommon}
 * initialization time.
 */
@Nullable
public PyRuntimeInfo getRuntimeFromToolchain() {
    Preconditions.checkArgument(ruleContext.attributes().has("$py_toolchain_type", BuildType.NODEP_LABEL), "Cannot retrieve Python toolchain information for '%s' rule", ruleContext.getRule().getRuleClreplaced());
    Preconditions.checkArgument(shouldGetRuntimeFromToolchain(), "Access to the Python toolchain is disabled by --incompatible_use_python_toolchains=false");
    return runtimeFromToolchain;
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Collects all the labels and Java packages of the given rule and every rule that has databinding
 * in the transitive dependencies of the given rule.
 *
 * @return A multimap of Java Package (as a string) to labels which have that Java package.
 */
private static ImmutableMultimap<String, String> getJavaPackagesWithDatabindingToLabelMap(RuleContext context) {
    // Since this method iterates over the labels in deps without first constructing a NestedSet,
    // multiple android_library rules could (and almost certainly will) be reached from dependencies
    // at the top-level which would produce false positives, so use a SetMultimap to avoid this.
    ImmutableMultimap.Builder<String, String> javaPackagesToLabel = ImmutableSetMultimap.builder();
    // Add this top-level rule's label and java package, e.g. for when an android_binary with
    // databinding depends on an android_library with databinding in the same java package.
    String label = context.getRule().getLabel().toString();
    String javaPackage = AndroidCommon.getJavaPackage(context);
    javaPackagesToLabel.put(javaPackage, label);
    if (context.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<DataBindingV2Provider> providers = context.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET, DataBindingV2Provider.PROVIDER);
        for (DataBindingV2Provider provider : providers) {
            for (LabelJavaPackagePair labelJavaPackagePair : provider.getTransitiveLabelAndJavaPackages().toList()) {
                javaPackagesToLabel.put(labelJavaPackagePair.getJavaPackage(), labelJavaPackagePair.getLabel());
            }
        }
    }
    return javaPackagesToLabel.build();
}

19 View Complete Implementation : JavaCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private static Iterable<JavaPluginInfoProvider> getPluginInfoProvidersForAttribute(RuleContext ruleContext, String attribute, Mode mode) {
    if (ruleContext.attributes().has(attribute, BuildType.LABEL_LIST)) {
        return JavaInfo.getProvidersFromListOfTargets(JavaPluginInfoProvider.clreplaced, ruleContext.getPrerequisites(attribute, mode));
    }
    return ImmutableList.of();
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
private static List<Artifact> getDirectClreplacedInfo(RuleContext context) {
    ImmutableList.Builder<Artifact> clreplacedInfoFiles = ImmutableList.builder();
    if (context.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<DataBindingV2Provider> providers = context.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET, DataBindingV2Provider.PROVIDER);
        for (DataBindingV2Provider provider : providers) {
            clreplacedInfoFiles.addAll(provider.getClreplacedInfos());
        }
    }
    return clreplacedInfoFiles.build();
}

19 View Complete Implementation : JavaHelper.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Control structure abstraction for safely extracting a prereq from the launcher attribute or
 * --java_launcher flag.
 */
private static String filterLauncherForTarget(RuleContext ruleContext) {
    // create_executable=0 disables the launcher
    if (ruleContext.getRule().isAttrDefined("create_executable", Type.BOOLEAN) && !ruleContext.attributes().get("create_executable", Type.BOOLEAN)) {
        return null;
    }
    // BUILD rule "launcher" attribute
    if (ruleContext.getRule().isAttrDefined("launcher", BuildType.LABEL) && ruleContext.attributes().get("launcher", BuildType.LABEL) != null) {
        if (isJdkLauncher(ruleContext, ruleContext.attributes().get("launcher", BuildType.LABEL))) {
            return null;
        }
        return "launcher";
    }
    // Blaze flag --java_launcher
    JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.clreplaced);
    if (ruleContext.getRule().isAttrDefined(":java_launcher", BuildType.LABEL) && javaConfig.getJavaLauncherLabel() != null && !isJdkLauncher(ruleContext, javaConfig.getJavaLauncherLabel())) {
        return ":java_launcher";
    }
    return null;
}

19 View Complete Implementation : ConstraintSemantics.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns all dependencies that should be constraint-checked against the current rule,
 * including both "uncoditional" deps (outside selects) and deps that only appear in selects.
 */
private static DepsToCheck getConstraintCheckedDependencies(RuleContext ruleContext) {
    Set<TransitiveInfoCollection> depsToCheck = new LinkedHashSet<>();
    Set<TransitiveInfoCollection> selectOnlyDeps = new LinkedHashSet<>();
    Set<TransitiveInfoCollection> depsOutsideSelects = new LinkedHashSet<>();
    AttributeMap attributes = ruleContext.attributes();
    for (String attr : attributes.getAttributeNames()) {
        Attribute attrDef = attributes.getAttributeDefinition(attr);
        if (attrDef.getType().getLabelClreplaced() != LabelClreplaced.DEPENDENCY || attrDef.skipConstraintsOverride()) {
            continue;
        }
        if (!attrDef.checkConstraintsOverride()) {
            // Use the same implicit deps check that query uses. This facilitates running queries to
            // determine exactly which rules need to be constraint-annotated for depot migrations.
            if (!DependencyFilter.NO_IMPLICIT_DEPS.apply(ruleContext.getRule(), attrDef) || // We can't identify host deps by calling BuildConfiguration.isHostConfiguration()
            // because --nodistinct_host_configuration subverts that call.
            attrDef.getTransitionFactory().isHost()) {
                continue;
            }
        }
        Set<Label> selectOnlyDepsForThisAttribute = getDepsOnlyInSelects(ruleContext, attr, attributes.getAttributeType(attr));
        for (TransitiveInfoCollection dep : ruleContext.getPrerequisites(attr, RuleConfiguredTarget.Mode.DONT_CHECK)) {
            // Output files inherit the environment spec of their generating rule.
            if (dep instanceof OutputFileConfiguredTarget) {
                // Note this rereplacedignment means constraint violation errors reference the generating
                // rule, not the file. This makes the source of the environmental mismatch more clear.
                dep = ((OutputFileConfiguredTarget) dep).getGeneratingRule();
            }
            // Input files don't support environments. We may subsequently opt them into constraint
            // checking, but for now just preplaced them by.
            if (dep.getProvider(SupportedEnvironmentsProvider.clreplaced) != null) {
                depsToCheck.add(dep);
                // For normal configured targets the target's label is the same label appearing in the
                // select(). But for AliasConfiguredTargets the label in the select() refers to the alias,
                // while dep.getLabel() refers to the target the alias points to. So add this quick check
                // to make sure we're comparing the same labels.
                Label depLabelInSelect = (dep instanceof AliasConfiguredTarget) ? ((AliasConfiguredTarget) dep).getOriginalLabel() : dep.getLabel();
                if (!selectOnlyDepsForThisAttribute.contains(depLabelInSelect)) {
                    depsOutsideSelects.add(dep);
                }
            }
        }
    }
    for (TransitiveInfoCollection dep : depsToCheck) {
        if (!depsOutsideSelects.contains(dep)) {
            selectOnlyDeps.add(dep);
        }
    }
    return new DepsToCheck(depsToCheck, selectOnlyDeps);
}

19 View Complete Implementation : JavaToolchain.java
Copyright Apache License 2.0
Author : bazelbuild
private ImmutableList<String> getJavacOpts(RuleContext ruleContext) {
    ImmutableList.Builder<String> javacopts = ImmutableList.builder();
    String source = ruleContext.attributes().get("source_version", Type.STRING);
    if (!isNullOrEmpty(source)) {
        javacopts.add("-source").add(source);
    }
    String target = ruleContext.attributes().get("target_version", Type.STRING);
    if (!isNullOrEmpty(target)) {
        javacopts.add("-target").add(target);
    }
    List<String> xlint = ruleContext.attributes().get("xlint", Type.STRING_LIST);
    if (!xlint.isEmpty()) {
        javacopts.add("-Xlint:" + Joiner.on(",").join(xlint));
    }
    javacopts.addAll(ruleContext.getExpander().withDataLocations().tokenized("misc"));
    javacopts.addAll(ruleContext.getExpander().withDataLocations().tokenized("javacopts"));
    return javacopts.build();
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void supplyJavaCoptsUsing(RuleContext ruleContext, boolean isBinary, Consumer<Iterable<String>> consumer) {
    DataBindingProcessorArgsBuilder args = new DataBindingProcessorArgsBuilder(useUpdatedArgs);
    String metadataOutputDir = DataBinding.getDataBindingExecPath(ruleContext).getPathString();
    args.metadataOutputDir(metadataOutputDir);
    args.sdkDir("/not/used");
    args.binary(isBinary);
    // Unused.
    args.exportClreplacedListTo("/tmp/exported_clreplacedes");
    args.modulePackage(AndroidCommon.getJavaPackage(ruleContext));
    args.directDependencyPkgs(getJavaPackagesOfDirectDependencies(ruleContext));
    // The minimum Android SDK compatible with this rule.
    // TODO(bazel-team): This probably should be based on the actual min-sdk from the manifest,
    // or an appropriate rule attribute.
    args.minApi("14");
    args.enableV2();
    if (AndroidResources.definesAndroidResources(ruleContext.attributes())) {
        args.clreplacedLogDir(getClreplacedInfoFile(ruleContext));
        args.layoutInfoDir(DataBinding.getLayoutInfoFile(ruleContext));
    } else {
        // send dummy files
        args.clreplacedLogDir("/tmp/no_resources");
        args.layoutInfoDir("/tmp/no_resources");
    }
    consumer.accept(args.build());
}

19 View Complete Implementation : J2ObjcLibrary.java
Copyright Apache License 2.0
Author : bazelbuild
private static void checkAttributes(RuleContext ruleContext, String attributeName) {
    if (!ruleContext.attributes().has(attributeName, BuildType.LABEL_LIST)) {
        return;
    }
    List<String> entryClreplacedes = ruleContext.attributes().get("entry_clreplacedes", Type.STRING_LIST);
    J2ObjcConfiguration j2objcConfiguration = ruleContext.getFragment(J2ObjcConfiguration.clreplaced);
    if (j2objcConfiguration.removeDeadCode() && (entryClreplacedes == null || entryClreplacedes.isEmpty())) {
        ruleContext.attributeError("entry_clreplacedes", NO_ENTRY_CLreplaced_ERROR_MSG);
    }
}

19 View Complete Implementation : IntermediateArtifacts.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * {@link CppModuleMap} that provides the clang module map for this target.
 */
public CppModuleMap moduleMap() {
    String moduleName;
    if (ruleContext.attributes().isAttributeValueExplicitlySpecified("module_name")) {
        moduleName = ruleContext.attributes().get("module_name", Type.STRING);
    } else {
        moduleName = ruleContext.getLabel().toString().replace("//", "").replace("@", "").replace("-", "_").replace("/", "_").replace(":", "_");
    }
    Optional<Artifact> customModuleMap = CompilationSupport.getCustomModuleMap(ruleContext);
    if (customModuleMap.isPresent()) {
        return new CppModuleMap(customModuleMap.get(), moduleName);
    } else if (umbrellaHeaderStrategy == UmbrellaHeaderStrategy.GENERATE) {
        // To get Swift to pick up module maps, we need to name them "module.modulemap" and have their
        // parent directory in the module map search paths.
        return new CppModuleMap(appendExtensionInGenfiles(".modulemaps/module.modulemap"), appendExtensionInGenfiles(".modulemaps/umbrella.h"), moduleName);
    } else {
        return new CppModuleMap(appendExtensionInGenfiles(".modulemaps/module.modulemap"), moduleName);
    }
}

19 View Complete Implementation : ConfigSetting.java
Copyright Apache License 2.0
Author : bazelbuild
private static RepositoryName getToolsRepository(RuleContext ruleContext) {
    try {
        return RepositoryName.create(ruleContext.attributes().get(ConfigSettingRule.TOOLS_REPOSITORY_ATTRIBUTE, Type.STRING));
    } catch (LabelSyntaxException ex) {
        throw new IllegalStateException(ex);
    }
}

19 View Complete Implementation : MultiArchSplitTransitionProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Validates that minimum OS was set to a valid value on the current rule.
 *
 * @throws RuleErrorException if the platform type attribute in the current rulecontext is an
 *     invalid value
 */
public static void validateMinimumOs(RuleContext ruleContext) throws RuleErrorException {
    String attributeValue = ruleContext.attributes().get(PlatformRule.MINIMUM_OS_VERSION, STRING);
    // TODO(b/37096178): This attribute should always be a version.
    if (Strings.isNullOrEmpty(attributeValue)) {
        if (ruleContext.getFragment(AppleConfiguration.clreplaced).isMandatoryMinimumVersion()) {
            ruleContext.throwWithAttributeError(PlatformRule.MINIMUM_OS_VERSION, "This attribute must be explicitly specified");
        }
    } else {
        try {
            DottedVersion minimumOsVersion = DottedVersion.fromString(attributeValue);
            if (minimumOsVersion.hasAlphabeticCharacters() || minimumOsVersion.numComponents() > 2) {
                ruleContext.throwWithAttributeError(PlatformRule.MINIMUM_OS_VERSION, String.format(INVALID_VERSION_STRING_ERROR_FORMAT, attributeValue));
            }
        } catch (DottedVersion.InvalidDottedVersionException exception) {
            ruleContext.throwWithAttributeError(PlatformRule.MINIMUM_OS_VERSION, String.format(INVALID_VERSION_STRING_ERROR_FORMAT, attributeValue));
        }
    }
}

19 View Complete Implementation : DataBinding.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the data binding resource processing output from deps under the given attribute.
 */
static List<Artifact> getTransitiveMetadata(RuleContext ruleContext, String attr) {
    ImmutableList.Builder<Artifact> dataBindingMetadataOutputs = ImmutableList.builder();
    if (ruleContext.attributes().has(attr, BuildType.LABEL_LIST)) {
        for (UsesDataBindingProvider provider : ruleContext.getPrerequisites(attr, RuleConfiguredTarget.Mode.TARGET, UsesDataBindingProvider.PROVIDER)) {
            dataBindingMetadataOutputs.addAll(provider.getMetadataOutputs());
        }
    }
    return dataBindingMetadataOutputs.build();
}

19 View Complete Implementation : ProtoAttributes.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns whether to use the protobuf library instead of the PB2 library.
 */
boolean hasPortableProtoFilters() {
    return ruleContext.attributes().isAttributeValueExplicitlySpecified(PORTABLE_PROTO_FILTERS_ATTR);
}

19 View Complete Implementation : Filegroup.java
Copyright Apache License 2.0
Author : bazelbuild
private PathFragment getFilegroupPath(RuleContext ruleContext) {
    String attr = ruleContext.attributes().get("path", Type.STRING);
    if (attr.isEmpty()) {
        return PathFragment.EMPTY_FRAGMENT;
    } else {
        return ruleContext.getLabel().getPackageIdentifier().getSourceRoot().getRelative(attr);
    }
}

19 View Complete Implementation : ProtoCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Check that .proto files in sources are from the same package. This is done to avoid clashes
 * with the generated sources.
 */
private static void checkSourceFilesAreInSamePackage(RuleContext ruleContext) {
    // TODO(bazel-team): this does not work with filegroups that contain files
    // that are not in the package
    for (Label source : ruleContext.attributes().get("srcs", BuildType.LABEL_LIST)) {
        if (!isConfiguredTargetInSamePackage(ruleContext, source)) {
            ruleContext.attributeError("srcs", "Proto source with label '" + source + "' must be in same package as consuming rule.");
        }
    }
}

19 View Complete Implementation : AndroidIdlHelper.java
Copyright Apache License 2.0
Author : bazelbuild
private static String getIdlImportRoot(RuleContext ruleContext) {
    return ruleContext.attributes().get("idl_import_root", Type.STRING);
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns whether, in the case that a user Python program fails, the stub script should emit a
 * warning that the failure may have been caused by the host configuration using the wrong Python
 * version.
 *
 * <p>This method should only be called for executable Python rules.
 *
 * <p>Background: Historically, Bazel did not necessarily launch a Python interpreter whose
 * version corresponded to the one determined by the replacedysis phase (#4815). Enabling Python
 * toolchains fixed this bug. However, this caused some builds to break due to targets that
 * contained Python-2-only code yet got replacedyzed for (and now run with) Python 3. This is
 * particularly problematic for the host configuration, where the value of {@code
 * --host_force_python} overrides the declared or implicit Python version of the target.
 *
 * <p>Our mitigation for this is to warn users when a Python target has a non-zero exit code and
 * the failure could be due to a bad Python version in the host configuration. In this case,
 * instead of just giving the user a confusing traceback of a PY2 vs PY3 error, we append a
 * diagnostic message to stderr. See #7899 and especially #8549 for context.
 *
 * <p>This method returns true when all of the following hold:
 *
 * <ol>
 *   <li>Python toolchains are enabled. (The warning is needed the most when toolchains are
 *       enabled, since that's an incompatible change likely to cause breakages. At the same time,
 *       warning when toolchains are disabled could be misleading, since we don't actually know
 *       whether the interpreter invoked at runtime is correct.)
 *   <li>The target is built in the host configuration. This avoids polluting stderr with spurious
 *       warnings for non-host-configured targets, while covering the most problematic case.
 *   <li>Either the value of {@code --host_force_python} overrode the target's normal Python
 *       version to a different value (in which case we know a mismatch occurred), or else {@code
 *       --host_force_python} is in agreement with the target's version but the target's version
 *       was set by default instead of explicitly (in which case we suspect the target may have
 *       been defined incorrectly).
 * </ol>
 *
 * @throws IllegalArgumentException if there is a problem parsing the Python version from the
 *     attributes; see {@link #readPythonVersionFromAttributes}.
 */
// TODO(#6443): Remove this logic and the corresponding stub script logic once we no longer have
// the possibility of Python binaries appearing in the host configuration.
public boolean shouldWarnAboutHostVersionUponFailure() {
    // Only warn when toolchains are used.
    PythonConfiguration config = ruleContext.getFragment(PythonConfiguration.clreplaced);
    if (!config.useToolchains()) {
        return false;
    }
    // Only warn in the host config.
    if (!ruleContext.getConfiguration().isHostConfiguration()) {
        return false;
    }
    PythonVersion configVersion = config.getPythonVersion();
    PythonVersion attrVersion = readPythonVersionFromAttributes(ruleContext.attributes());
    if (attrVersion == null) {
        // Warn if the version wasn't set explicitly.
        return true;
    } else {
        // Warn if the explicit version is different from the host config's version.
        return configVersion != attrVersion;
    }
}

19 View Complete Implementation : JavaBinary.java
Copyright Apache License 2.0
Author : bazelbuild
// Create the deploy jar and make it dependent on the runfiles middleman if an executable is
// created. Do not add the deploy jar to files to build, so we will only build it when it gets
// requested.
private ImmutableList<String> getDeployManifestLines(RuleContext ruleContext, String originalMainClreplaced) {
    ImmutableList.Builder<String> builder = ImmutableList.<String>builder().addAll(ruleContext.attributes().get("deploy_manifest_lines", Type.STRING_LIST));
    if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
        builder.add("Coverage-Main-Clreplaced: " + originalMainClreplaced);
    }
    return builder.build();
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns true if any of this target's {@code deps} or {@code data} deps has a shared library
 * file (e.g. a {@code .so}) in its transitive dependency closure.
 *
 * <p>For targets with the py provider, we consult the {@code uses_shared_libraries} field. For
 * targets without this provider, we look for {@link CppFileTypes#SHARED_LIBRARY}-type files in
 * the filesToBuild.
 */
private static boolean initUsesSharedLibraries(RuleContext ruleContext) {
    Iterable<? extends TransitiveInfoCollection> targets;
    // The deps attribute must exist for all rule types that use PyCommon, but not necessarily the
    // data attribute.
    if (ruleContext.attributes().has("data")) {
        targets = Iterables.concat(ruleContext.getPrerequisites("deps", Mode.TARGET), ruleContext.getPrerequisites("data", Mode.DONT_CHECK));
    } else {
        targets = ruleContext.getPrerequisites("deps", Mode.TARGET);
    }
    for (TransitiveInfoCollection target : targets) {
        try {
            if (PyProviderUtils.getUsesSharedLibraries(target)) {
                return true;
            }
        } catch (EvalException e) {
            ruleContext.ruleError(String.format("In dep '%s': %s", target.getLabel(), e.getMessage()));
        }
    }
    return false;
}

19 View Complete Implementation : DataBindingV2Context.java
Copyright Apache License 2.0
Author : bazelbuild
private static Set<String> getJavaPackagesOfDirectDependencies(RuleContext ruleContext) {
    ImmutableSet.Builder<String> javaPackagesOfDirectDependencies = ImmutableSet.builder();
    if (ruleContext.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<DataBindingV2Provider> providers = ruleContext.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET, DataBindingV2Provider.PROVIDER);
        for (DataBindingV2Provider provider : providers) {
            for (LabelJavaPackagePair labelJavaPackagePair : provider.getLabelAndJavaPackages()) {
                javaPackagesOfDirectDependencies.add(labelJavaPackagePair.getJavaPackage());
            }
        }
    }
    return javaPackagesOfDirectDependencies.build();
}

19 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Reports an attribute error if the given target Python version attribute ({@code
 * default_python_version} or {@code python_version}) cannot be parsed as {@code PY2}, {@code
 * PY3}, or the sentinel value.
 *
 * <p>This *should* be enforced by rule attribute validation ({@link
 * Attribute.Builder.allowedValues}), but this check is here to fail-fast just in case.
 */
private void validateTargetPythonVersionAttr(String attr) {
    AttributeMap attrs = ruleContext.attributes();
    if (!attrs.has(attr, Type.STRING)) {
        return;
    }
    String attrValue = attrs.get(attr, Type.STRING);
    try {
        PythonVersion.parseTargetOrSentinelValue(attrValue);
    } catch (IllegalArgumentException ex) {
        ruleContext.attributeError(attr, String.format("'%s' is not a valid value. Expected either 'PY2' or 'PY3'", attrValue));
    }
}

19 View Complete Implementation : JavaCommon.java
Copyright Apache License 2.0
Author : bazelbuild
private static boolean hasValidTag(RuleContext ruleContext) {
    return ruleContext.attributes().get("tags", Type.STRING_LIST).contains("__JAVA_RULES_MIGRATION_DO_NOT_USE_WILL_BREAK__");
}

19 View Complete Implementation : AndroidLibrary.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * TODO(b/14473160): Remove when deps are no longer implicitly exported.
 *
 * <p>Returns true if the rule (possibly) relies on the implicit dep exports behavior.
 *
 * <p>If this returns true, then the rule *is* exporting deps implicitly, and does not have any
 * srcs or locally-used resources consuming the deps.
 *
 * <p>Else, this rule either is not using deps or has another deps-consuming attribute (src,
 * locally-used resources)
 */
private static boolean usesDeprecatedImplicitExport(RuleContext ruleContext) throws RuleErrorException {
    AttributeMap attrs = ruleContext.attributes();
    if (!attrs.isAttributeValueExplicitlySpecified("deps") || attrs.get("deps", BuildType.LABEL_LIST).isEmpty()) {
        return false;
    }
    String[] labelListAttrs = { "srcs", "idl_srcs", "replacedets", "resource_files" };
    for (String attr : labelListAttrs) {
        if (attrs.isAttributeValueExplicitlySpecified(attr) && !attrs.get(attr, BuildType.LABEL_LIST).isEmpty()) {
            return false;
        }
    }
    boolean hasManifest = attrs.isAttributeValueExplicitlySpecified("manifest");
    boolean hasreplacedetsDir = attrs.isAttributeValueExplicitlySpecified("replacedets_dir");
    boolean hasInlineConsts = attrs.isAttributeValueExplicitlySpecified("inline_constants") && attrs.get("inline_constants", Type.BOOLEAN);
    boolean hasExportsManifest = attrs.isAttributeValueExplicitlySpecified("exports_manifest") && attrs.get("exports_manifest", BuildType.TRISTATE) == TriState.YES;
    return !(hasManifest || hasInlineConsts || hasreplacedetsDir || hasExportsManifest);
}

19 View Complete Implementation : AndroidAssets.java
Copyright Apache License 2.0
Author : bazelbuild
@Nullable
private static PathFragment getreplacedetDir(RuleContext ruleContext) {
    if (!ruleContext.attributes().isAttributeValueExplicitlySpecified(replacedETS_DIR_ATTR)) {
        return null;
    }
    return PathFragment.create(ruleContext.attributes().get(replacedETS_DIR_ATTR, Type.STRING));
}

19 View Complete Implementation : AndroidManifest.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Gets the Android package for this target, from either rule configuration or Java package
 */
private static String getAndroidPackage(RuleContext ruleContext) {
    if (ruleContext.attributes().isAttributeValueExplicitlySpecified(CUSTOM_PACKAGE_ATTR)) {
        return ruleContext.attributes().get(CUSTOM_PACKAGE_ATTR, Type.STRING);
    }
    return getDefaultPackage(ruleContext.getLabel(), ruleContext, ruleContext);
}

19 View Complete Implementation : ResourceFilterFactory.java
Copyright Apache License 2.0
Author : bazelbuild
static ResourceFilterFactory fromRuleContextAndAttrs(RuleContext ruleContext) throws RuleErrorException {
    Preconditions.checkNotNull(ruleContext);
    if (!ruleContext.isLegalFragment(AndroidConfiguration.clreplaced)) {
        return empty();
    }
    return fromAttrs(ruleContext.attributes());
}

19 View Complete Implementation : J2ObjcAspect.java
Copyright Apache License 2.0
Author : bazelbuild
private static void addJ2ObjCMappingsForAttribute(ImmutableList.Builder<J2ObjcMappingFileProvider> builder, RuleContext context, String attributeName) {
    if (context.attributes().has(attributeName, BuildType.LABEL_LIST)) {
        for (TransitiveInfoCollection dependencyInfoDatum : context.getPrerequisites(attributeName, Mode.TARGET)) {
            J2ObjcMappingFileProvider provider = dependencyInfoDatum.getProvider(J2ObjcMappingFileProvider.clreplaced);
            if (provider != null) {
                builder.add(provider);
            }
        }
    }
}

18 View Complete Implementation : SkylarkRuleConfiguredTargetUtil.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Create a Rule Configured Target from the ruleContext and the ruleImplementation. Returns null
 * if there were errors during target creation.
 */
@Nullable
public static ConfiguredTarget buildRule(RuleContext ruleContext, AdvertisedProviderSet advertisedProviders, BaseFunction ruleImplementation, Location location, StarlarkSemantics starlarkSemantics, String toolsRepository) throws InterruptedException, RuleErrorException, ActionConflictException {
    String expectFailure = ruleContext.attributes().get("expect_failure", Type.STRING);
    SkylarkRuleContext skylarkRuleContext = null;
    try (Mutability mutability = Mutability.create("configured target")) {
        skylarkRuleContext = new SkylarkRuleContext(ruleContext, null, starlarkSemantics);
        StarlarkThread thread = StarlarkThread.builder(mutability).setSemantics(starlarkSemantics).build();
        thread.setPrintHandler(StarlarkThread.makeDebugPrintHandler(ruleContext.getreplacedysisEnvironment().getEventHandler()));
        new BazelStarlarkContext(BazelStarlarkContext.Phase.replacedYSIS, toolsRepository, /*fragmentNameToClreplaced=*/
        null, ruleContext.getTarget().getPackage().getRepositoryMapping(), ruleContext.getSymbolGenerator(), ruleContext.getLabel()).storeInThread(thread);
        RuleClreplaced ruleClreplaced = ruleContext.getRule().getRuleClreplacedObject();
        if (ruleClreplaced.getRuleClreplacedType().equals(RuleClreplaced.Builder.RuleClreplacedType.WORKSPACE)) {
            ruleContext.ruleError("Found reference to a workspace rule in a context where a build" + " rule was expected; probably a reference to a target in that external" + " repository, properly specified as @reponame//path/to/package:target," + " should have been specified by the requesting rule.");
            return null;
        }
        if (ruleClreplaced.hasFunctionTransitionWhitelist() && !Whitelist.isAvailableBasedOnRuleLocation(ruleContext, FunctionSplitTransitionWhitelist.WHITELIST_NAME)) {
            if (!Whitelist.isAvailable(ruleContext, FunctionSplitTransitionWhitelist.WHITELIST_NAME)) {
                ruleContext.ruleError("Non-whitelisted use of Starlark transition");
            }
        }
        Object target = Starlark.call(thread, ruleImplementation, /*args=*/
        ImmutableList.of(skylarkRuleContext), /*kwargs=*/
        ImmutableMap.of());
        if (ruleContext.hasErrors()) {
            return null;
        } else if (!(target instanceof Info) && target != Starlark.NONE && !(target instanceof Iterable)) {
            ruleContext.ruleError(String.format("Rule should return a struct or a list, but got %s", EvalUtils.getDataTypeName(target)));
            return null;
        } else if (!expectFailure.isEmpty()) {
            ruleContext.ruleError("Expected failure not found: " + expectFailure);
            return null;
        }
        ConfiguredTarget configuredTarget = createTarget(skylarkRuleContext, target);
        if (configuredTarget != null) {
            // If there was error creating the ConfiguredTarget, no further validation is needed.
            // Null will be returned and the errors thus reported.
            SkylarkProviderValidationUtil.validateArtifacts(ruleContext);
            checkDeclaredProviders(configuredTarget, advertisedProviders, location);
        }
        return configuredTarget;
    } catch (EvalException e) {
        addRuleToStackTrace(e, ruleContext.getRule(), ruleImplementation);
        // If the error was expected, return an empty target.
        if (!expectFailure.isEmpty() && getMessageWithoutStackTrace(e).matches(expectFailure)) {
            return new RuleConfiguredTargetBuilder(ruleContext).add(RunfilesProvider.clreplaced, RunfilesProvider.EMPTY).build();
        }
        ruleContext.ruleError("\n" + e.print());
        return null;
    } finally {
        if (skylarkRuleContext != null) {
            skylarkRuleContext.nullify();
        }
    }
}

18 View Complete Implementation : BazelGenRule.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
protected boolean isStampingEnabled(RuleContext ruleContext) {
    if (!ruleContext.attributes().has("stamp", Type.BOOLEAN)) {
        return false;
    }
    return ruleContext.attributes().get("stamp", Type.BOOLEAN);
}

18 View Complete Implementation : BazelJavaSemantics.java
Copyright Apache License 2.0
Author : bazelbuild
private String getMainClreplacedFromRule(RuleContext ruleContext) {
    String mainClreplaced = ruleContext.attributes().get("main_clreplaced", Type.STRING);
    if (!mainClreplaced.isEmpty()) {
        return mainClreplaced;
    }
    if (JavaSemantics.useLegacyJavaTest(ruleContext)) {
        // Legacy behavior for java_test rules: main_clreplaced defaulted to JUnit4 runner.
        // TODO(dmarting): remove once we drop the legacy bazel java_test behavior.
        if ("java_test".equals(ruleContext.getRule().getRuleClreplaced())) {
            return JUNIT4_RUNNER;
        }
    } else {
        if (ruleContext.attributes().get("use_testrunner", Type.BOOLEAN)) {
            return BAZEL_TEST_RUNNER_MAIN_CLreplaced;
        }
    }
    return mainClreplaced;
}

18 View Complete Implementation : BazelJavaSemantics.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public Iterable<String> getJvmFlags(RuleContext ruleContext, ImmutableList<Artifact> sources, List<String> userJvmFlags) {
    ImmutableList.Builder<String> jvmFlags = ImmutableList.builder();
    jvmFlags.addAll(userJvmFlags);
    if (!JavaSemantics.useLegacyJavaTest(ruleContext)) {
        if (ruleContext.attributes().get("use_testrunner", Type.BOOLEAN)) {
            String testClreplaced = ruleContext.getRule().isAttrDefined("test_clreplaced", Type.STRING) ? ruleContext.attributes().get("test_clreplaced", Type.STRING) : "";
            if (testClreplaced.isEmpty()) {
                testClreplaced = JavaCommon.determinePrimaryClreplaced(ruleContext, sources);
            }
            if (testClreplaced == null) {
                ruleContext.ruleError("cannot determine test clreplaced");
            } else {
                // Always run junit tests with -ea (enable replacedertion)
                jvmFlags.add("-ea");
                // "suite" is a misnomer.
                jvmFlags.add("-Dbazel.test_suite=" + ShellEscaper.escapeString(testClreplaced));
            }
        }
    }
    return jvmFlags.build();
}

18 View Complete Implementation : AndroidDataContext.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns true if the context dictates that resource shrinking is enabled. This doesn't
 * necessarily mean that shrinking should be performed - for that, use {@link
 * #useResourceShrinking(boolean)}, which calls this.
 */
boolean isResourceShrinkingEnabled() {
    if (!ruleContext.attributes().has("shrink_resources")) {
        return false;
    }
    TriState state = ruleContext.attributes().get("shrink_resources", BuildType.TRISTATE);
    if (state == TriState.AUTO) {
        state = getAndroidConfig().useAndroidResourceShrinking() ? TriState.YES : TriState.NO;
    }
    return state == TriState.YES;
}