Java Code Examples for com.google.devtools.build.lib.syntax.EvalUtils#isNullOrNone()

The following examples show how to use com.google.devtools.build.lib.syntax.EvalUtils#isNullOrNone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Attribute.java    From bazel with Apache License 2.0 6 votes vote down vote up
private Object computeValue(EventHandler eventHandler, AttributeMap rule)
    throws EvalException, InterruptedException {
  Map<String, Object> attrValues = new HashMap<>();
  for (String attrName : rule.getAttributeNames()) {
    Attribute attr = rule.getAttributeDefinition(attrName);
    if (!attr.hasComputedDefault()) {
      Object value = rule.get(attrName, attr.getType());
      if (!EvalUtils.isNullOrNone(value)) {
        // Some attribute values are not valid Starlark values:
        // visibility is an ImmutableList, for example.
        attrValues.put(attr.getName(), Starlark.fromJava(value, /*mutability=*/ null));
      }
    }
  }
  return invokeCallback(eventHandler, attrValues);
}
 
Example 2
Source File: GitModule.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Nullable
private PatchTransformation maybeGetPatchTransformation(Object patch) throws EvalException {
  if (EvalUtils.isNullOrNone(patch)) {
    return null;
  }
  check(
      patch instanceof PatchTransformation,
      "'%s' is not a patch.apply(...) transformation",
      PATCH_FIELD);
  return  (PatchTransformation) patch;
}
 
Example 3
Source File: SkylarkUtil.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an object that can be the NoneType to the actual object if it is not
 * or returns the default value if none.
 */
@SuppressWarnings("unchecked")
public static <T> T convertFromNoneable(Object obj, @Nullable T defaultValue) {
  if (EvalUtils.isNullOrNone(obj)) {
    return defaultValue;
  }
  return (T) obj;
}
 
Example 4
Source File: Type.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Like {@link #convert(Object, Object, Object)}, but converts Starlark {@code None} to given
 * {@code defaultValue}.
 */
@Nullable
public final T convertOptional(Object x, String what, @Nullable Object context, T defaultValue)
    throws ConversionException {
  if (EvalUtils.isNullOrNone(x)) {
    return defaultValue;
  }
  return convert(x, what, context);
}
 
Example 5
Source File: CcModule.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an object that can be the NoneType to the actual object if it is not or returns the
 * default value if none.
 *
 * <p>This operation is wildly unsound. It performs no dymamic checks (casts), it simply lies
 * about the type.
 */
@SuppressWarnings("unchecked")
protected static <T> T convertFromNoneable(Object obj, @Nullable T defaultValue) {
  if (EvalUtils.isNullOrNone(obj)) {
    return defaultValue;
  }
  return (T) obj; // totally unsafe
}
 
Example 6
Source File: StarlarkNativeModule.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public NoneType exportsFiles(
    Sequence<?> srcs, Object visibilityO, Object licensesO, StarlarkThread thread)
    throws EvalException {
  BazelStarlarkContext.from(thread).checkLoadingPhase("native.exports_files");
  Package.Builder pkgBuilder = getContext(thread).pkgBuilder;
  List<String> files = Type.STRING_LIST.convert(srcs, "'exports_files' operand");

  RuleVisibility visibility =
      EvalUtils.isNullOrNone(visibilityO)
          ? ConstantRuleVisibility.PUBLIC
          : PackageUtils.getVisibility(
              pkgBuilder.getBuildFileLabel(),
              BuildType.LABEL_LIST.convert(
                  visibilityO, "'exports_files' operand", pkgBuilder.getBuildFileLabel()));

  // TODO(bazel-team): is licenses plural or singular?
  License license = BuildType.LICENSE.convertOptional(licensesO, "'exports_files' operand");

  Location loc = thread.getCallerLocation();
  for (String file : files) {
    String errorMessage = LabelValidator.validateTargetName(file);
    if (errorMessage != null) {
      throw Starlark.errorf("%s", errorMessage);
    }
    try {
      InputFile inputFile = pkgBuilder.createInputFile(file, loc);
      if (inputFile.isVisibilitySpecified() && inputFile.getVisibility() != visibility) {
        throw Starlark.errorf(
            "visibility for exported file '%s' declared twice", inputFile.getName());
      }
      if (license != null && inputFile.isLicenseSpecified()) {
        throw Starlark.errorf(
            "licenses for exported file '%s' declared twice", inputFile.getName());
      }

      // See if we should check third-party licenses: first checking for any hard-coded policy,
      // then falling back to user-settable flags.
      boolean checkLicenses;
      if (pkgBuilder.getThirdPartyLicenseExistencePolicy()
          == ThirdPartyLicenseExistencePolicy.ALWAYS_CHECK) {
        checkLicenses = true;
      } else if (pkgBuilder.getThirdPartyLicenseExistencePolicy()
          == ThirdPartyLicenseExistencePolicy.NEVER_CHECK) {
        checkLicenses = false;
      } else {
        checkLicenses = !thread.getSemantics().incompatibleDisableThirdPartyLicenseChecking();
      }

      if (checkLicenses
          && license == null
          && !pkgBuilder.getDefaultLicense().isSpecified()
          && RuleClass.isThirdPartyPackage(pkgBuilder.getPackageIdentifier())) {
        throw Starlark.errorf(
            "third-party file '%s' lacks a license declaration with one of the following types:"
                + " notice, reciprocal, permissive, restricted, unencumbered, by_exception_only",
            inputFile.getName());
      }

      pkgBuilder.setVisibilityAndLicense(inputFile, visibility, license);
    } catch (Package.Builder.GeneratedLabelConflict e) {
      throw Starlark.errorf("%s", e.getMessage());
    }
  }
  return Starlark.NONE;
}
 
Example 7
Source File: StarlarkRuleContext.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public Tuple<Object> resolveCommand(
    String command,
    Object attributeUnchecked,
    Boolean expandLocations,
    Object makeVariablesUnchecked,
    Sequence<?> tools,
    Dict<?, ?> labelDictUnchecked,
    Dict<?, ?> executionRequirementsUnchecked,
    StarlarkThread thread)
    throws ConversionException, EvalException {
  checkMutable("resolve_command");
  Label ruleLabel = getLabel();
  Map<Label, Iterable<Artifact>> labelDict = checkLabelDict(labelDictUnchecked);
  // The best way to fix this probably is to convert CommandHelper to Starlark.
  CommandHelper helper =
      CommandHelper.builder(getRuleContext())
          .addToolDependencies(Sequence.cast(tools, TransitiveInfoCollection.class, "tools"))
          .addLabelMap(labelDict)
          .build();
  String attribute = Type.STRING.convertOptional(attributeUnchecked, "attribute", ruleLabel);
  if (expandLocations) {
    command =
        helper.resolveCommandAndExpandLabels(command, attribute, /*allowDataInLabel=*/ false);
  }
  if (!EvalUtils.isNullOrNone(makeVariablesUnchecked)) {
    Map<String, String> makeVariables =
        Type.STRING_DICT.convert(makeVariablesUnchecked, "make_variables", ruleLabel);
    command = expandMakeVariables(attribute, command, makeVariables);
  }
  List<Artifact> inputs = new ArrayList<>();
  // TODO(lberki): This flattens a NestedSet.
  // However, we can't turn this into a Depset because it's an incompatible change to
  // Starlark.
  inputs.addAll(helper.getResolvedTools().toList());

  ImmutableMap<String, String> executionRequirements =
      ImmutableMap.copyOf(
          Dict.noneableCast(
              executionRequirementsUnchecked,
              String.class,
              String.class,
              "execution_requirements"));
  PathFragment shExecutable = ShToolchain.getPathOrError(ruleContext);

  BashCommandConstructor constructor =
      CommandHelper.buildBashCommandConstructor(
          executionRequirements,
          shExecutable,
          // Hash the command-line to prevent multiple actions from the same rule invocation
          // conflicting with each other.
          "." + Hashing.murmur3_32().hashUnencodedChars(command).toString() + SCRIPT_SUFFIX);
  List<String> argv = helper.buildCommandLine(command, inputs, constructor);
  return Tuple.<Object>of(
      StarlarkList.copyOf(thread.mutability(), inputs),
      StarlarkList.copyOf(thread.mutability(), argv),
      helper.getToolsRunfilesSuppliers());
}
 
Example 8
Source File: SkylarkRuleContextActions.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void run(
    SkylarkList<Object> arguments, Object shortName, Object userEnv, Location location)
    throws EvalException {
  Map<String, String> userEnvValidated =
      SkylarkDict.castSkylarkDictOrNoneToDict(userEnv, String.class, String.class, null);

  CommandLineArgs argumentsValidated;
  Object firstArgument;
  try {
    argumentsValidated =
        CommandLineArgsFactory.from(
            arguments.stream()
                .map(SkylarkRuleContextActions::getImmutableArg)
                .collect(ImmutableList.toImmutableList()));
    firstArgument =
        argumentsValidated
            .getArgsAndFormatStrings()
            .findFirst()
            .orElseThrow(
                () ->
                    new EvalException(
                        location, "At least one argument must be provided to 'run()'"))
            .getObject();
  } catch (CommandLineException e) {
    throw new EvalException(
        location,
        String.format(
            "Invalid type for %s. Must be one of string, int, Artifact, Label, or the result of ctx.actions.args()",
            e.getHumanReadableErrorMessage()));
  }

  String shortNameValidated;
  if (EvalUtils.isNullOrNone(shortName)) {
    if (firstArgument instanceof Artifact) {
      shortNameValidated =
          String.format("run action %s", ((Artifact) firstArgument).getBasename());
    } else if (firstArgument instanceof OutputArtifact) {
      shortNameValidated =
          String.format(
              "run action %s", ((OutputArtifact) firstArgument).getArtifact().getBasename());
    } else {
      shortNameValidated = String.format("run action %s", firstArgument);
    }
  } else {
    shortNameValidated = (String) shortName;
  }

  new RunAction(
      registry, shortNameValidated, argumentsValidated, ImmutableMap.copyOf(userEnvValidated));
}