Search in sources :

Example 26 with InvalidUserDataException

use of org.gradle.api.InvalidUserDataException in project gradle by gradle.

the class DefaultTransformationRegistrationFactory method create.

@Override
public ArtifactTransformRegistration create(ImmutableAttributes from, ImmutableAttributes to, Class<? extends TransformAction<?>> implementation, @Nullable TransformParameters parameterObject) {
    TypeMetadata actionMetadata = actionMetadataStore.getTypeMetadata(implementation);
    boolean cacheable = implementation.isAnnotationPresent(CacheableTransform.class);
    DefaultTypeValidationContext validationContext = DefaultTypeValidationContext.withoutRootType(documentationRegistry, cacheable);
    actionMetadata.visitValidationFailures(null, validationContext);
    // Should retain this on the metadata rather than calculate on each invocation
    Class<? extends FileNormalizer> inputArtifactNormalizer = null;
    Class<? extends FileNormalizer> dependenciesNormalizer = null;
    DirectorySensitivity artifactDirectorySensitivity = DirectorySensitivity.DEFAULT;
    DirectorySensitivity dependenciesDirectorySensitivity = DirectorySensitivity.DEFAULT;
    LineEndingSensitivity artifactLineEndingSensitivity = LineEndingSensitivity.DEFAULT;
    LineEndingSensitivity dependenciesLineEndingSensitivity = LineEndingSensitivity.DEFAULT;
    for (PropertyMetadata propertyMetadata : actionMetadata.getPropertiesMetadata()) {
        Class<? extends Annotation> propertyType = propertyMetadata.getPropertyType();
        if (propertyType.equals(InputArtifact.class)) {
            // Should ask the annotation handler to figure this out instead
            NormalizerCollectingVisitor visitor = new NormalizerCollectingVisitor();
            actionMetadata.getAnnotationHandlerFor(propertyMetadata).visitPropertyValue(propertyMetadata.getPropertyName(), null, propertyMetadata, visitor, null);
            inputArtifactNormalizer = visitor.normalizer;
            artifactDirectorySensitivity = visitor.directorySensitivity;
            artifactLineEndingSensitivity = visitor.lineEndingSensitivity;
            DefaultTransformer.validateInputFileNormalizer(propertyMetadata.getPropertyName(), inputArtifactNormalizer, cacheable, validationContext);
        } else if (propertyType.equals(InputArtifactDependencies.class)) {
            NormalizerCollectingVisitor visitor = new NormalizerCollectingVisitor();
            actionMetadata.getAnnotationHandlerFor(propertyMetadata).visitPropertyValue(propertyMetadata.getPropertyName(), null, propertyMetadata, visitor, null);
            dependenciesNormalizer = visitor.normalizer;
            dependenciesDirectorySensitivity = visitor.directorySensitivity;
            dependenciesLineEndingSensitivity = visitor.lineEndingSensitivity;
            DefaultTransformer.validateInputFileNormalizer(propertyMetadata.getPropertyName(), dependenciesNormalizer, cacheable, validationContext);
        }
    }
    ImmutableMap<String, Severity> validationMessages = validationContext.getProblems();
    if (!validationMessages.isEmpty()) {
        String formatString = validationMessages.size() == 1 ? "A problem was found with the configuration of %s." : "Some problems were found with the configuration of %s.";
        throw new DefaultMultiCauseException(String.format(formatString, ModelType.of(implementation).getDisplayName()), validationMessages.keySet().stream().sorted().map(InvalidUserDataException::new).collect(Collectors.toList()));
    }
    Transformer transformer = new DefaultTransformer(implementation, parameterObject, from, FileParameterUtils.normalizerOrDefault(inputArtifactNormalizer), FileParameterUtils.normalizerOrDefault(dependenciesNormalizer), cacheable, artifactDirectorySensitivity, dependenciesDirectorySensitivity, artifactLineEndingSensitivity, dependenciesLineEndingSensitivity, buildOperationExecutor, classLoaderHierarchyHasher, isolatableFactory, fileCollectionFactory, fileLookup, parametersPropertyWalker, actionInstantiationScheme, owner, calculatedValueContainerFactory, internalServices, documentationRegistry);
    return new DefaultArtifactTransformRegistration(from, to, new TransformationStep(transformer, transformerInvocationFactory, owner, inputFingerprinter));
}
Also used : LineEndingSensitivity(org.gradle.internal.fingerprint.LineEndingSensitivity) TypeMetadata(org.gradle.api.internal.tasks.properties.TypeMetadata) InputArtifactDependencies(org.gradle.api.artifacts.transform.InputArtifactDependencies) DirectorySensitivity(org.gradle.internal.fingerprint.DirectorySensitivity) Severity(org.gradle.internal.reflect.validation.Severity) DefaultMultiCauseException(org.gradle.internal.exceptions.DefaultMultiCauseException) InvalidUserDataException(org.gradle.api.InvalidUserDataException) DefaultTypeValidationContext(org.gradle.internal.reflect.DefaultTypeValidationContext) PropertyMetadata(org.gradle.internal.reflect.PropertyMetadata)

Example 27 with InvalidUserDataException

use of org.gradle.api.InvalidUserDataException in project gradle by gradle.

the class DefaultTransformer method fingerprintParameters.

private static void fingerprintParameters(DocumentationRegistry documentationRegistry, InputFingerprinter inputFingerprinter, FileCollectionFactory fileCollectionFactory, PropertyWalker propertyWalker, Hasher hasher, Object parameterObject, boolean cacheable) {
    DefaultTypeValidationContext validationContext = DefaultTypeValidationContext.withoutRootType(documentationRegistry, cacheable);
    InputFingerprinter.Result result = inputFingerprinter.fingerprintInputProperties(ImmutableSortedMap.of(), ImmutableSortedMap.of(), ImmutableSortedMap.of(), ImmutableSortedMap.of(), visitor -> propertyWalker.visitProperties(parameterObject, validationContext, new PropertyVisitor.Adapter() {

        @Override
        public void visitInputProperty(String propertyName, PropertyValue value, boolean optional) {
            try {
                Object preparedValue = InputParameterUtils.prepareInputParameterValue(value);
                if (preparedValue == null && !optional) {
                    reportValueNotSet(propertyName, validationContext);
                }
                visitor.visitInputProperty(propertyName, () -> preparedValue);
            } catch (Throwable e) {
                throw new InvalidUserDataException(String.format("Error while evaluating property '%s' of %s", propertyName, getParameterObjectDisplayName(parameterObject)), e);
            }
        }

        @Override
        public void visitInputFileProperty(String propertyName, boolean optional, boolean skipWhenEmpty, DirectorySensitivity directorySensitivity, LineEndingSensitivity lineEndingNormalization, boolean incremental, @Nullable Class<? extends FileNormalizer> fileNormalizer, PropertyValue value, InputFilePropertyType filePropertyType) {
            validateInputFileNormalizer(propertyName, fileNormalizer, cacheable, validationContext);
            visitor.visitInputFileProperty(propertyName, incremental ? InputFingerprinter.InputPropertyType.INCREMENTAL : InputFingerprinter.InputPropertyType.NON_INCREMENTAL, new FileValueSupplier(value, fileNormalizer == null ? AbsolutePathInputNormalizer.class : fileNormalizer, directorySensitivity, lineEndingNormalization, () -> FileParameterUtils.resolveInputFileValue(fileCollectionFactory, filePropertyType, value)));
        }

        @Override
        public void visitOutputFileProperty(String propertyName, boolean optional, PropertyValue value, OutputFilePropertyType filePropertyType) {
            validationContext.visitPropertyProblem(problem -> problem.withId(ValidationProblemId.ARTIFACT_TRANSFORM_SHOULD_NOT_DECLARE_OUTPUT).reportAs(Severity.ERROR).forProperty(propertyName).withDescription("declares an output").happensBecause("is annotated with an output annotation").addPossibleSolution("Remove the output property and use the TransformOutputs parameter from transform(TransformOutputs) instead").documentedAt("validation_problems", "artifact_transform_should_not_declare_output"));
        }
    }));
    ImmutableMap<String, Severity> validationMessages = validationContext.getProblems();
    if (!validationMessages.isEmpty()) {
        throw new DefaultMultiCauseException(String.format(validationMessages.size() == 1 ? "A problem was found with the configuration of the artifact transform parameter %s." : "Some problems were found with the configuration of the artifact transform parameter %s.", getParameterObjectDisplayName(parameterObject)), validationMessages.keySet().stream().sorted().map(InvalidUserDataException::new).collect(Collectors.toList()));
    }
    for (Map.Entry<String, ValueSnapshot> entry : result.getValueSnapshots().entrySet()) {
        hasher.putString(entry.getKey());
        entry.getValue().appendToHasher(hasher);
    }
    for (Map.Entry<String, CurrentFileCollectionFingerprint> entry : result.getFileFingerprints().entrySet()) {
        hasher.putString(entry.getKey());
        hasher.putHash(entry.getValue().getHash());
    }
}
Also used : LineEndingSensitivity(org.gradle.internal.fingerprint.LineEndingSensitivity) ValueSnapshot(org.gradle.internal.snapshot.ValueSnapshot) FileValueSupplier(org.gradle.internal.execution.fingerprint.InputFingerprinter.FileValueSupplier) FileNormalizer(org.gradle.api.tasks.FileNormalizer) OutputFilePropertyType(org.gradle.api.internal.tasks.properties.OutputFilePropertyType) DefaultTypeValidationContext(org.gradle.internal.reflect.DefaultTypeValidationContext) DirectorySensitivity(org.gradle.internal.fingerprint.DirectorySensitivity) PropertyValue(org.gradle.api.internal.tasks.properties.PropertyValue) InputFilePropertyType(org.gradle.api.internal.tasks.properties.InputFilePropertyType) Severity(org.gradle.internal.reflect.validation.Severity) DefaultMultiCauseException(org.gradle.internal.exceptions.DefaultMultiCauseException) InputFingerprinter(org.gradle.internal.execution.fingerprint.InputFingerprinter) InvalidUserDataException(org.gradle.api.InvalidUserDataException) CurrentFileCollectionFingerprint(org.gradle.internal.fingerprint.CurrentFileCollectionFingerprint) DslObject(org.gradle.api.internal.plugins.DslObject) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) Nullable(javax.annotation.Nullable)

Example 28 with InvalidUserDataException

use of org.gradle.api.InvalidUserDataException in project gradle by gradle.

the class LegacyTransformer method transform.

@Override
public ImmutableList<File> transform(Provider<FileSystemLocation> inputArtifactProvider, File outputDir, ArtifactTransformDependencies dependencies, @Nullable InputChanges inputChanges) {
    File inputArtifact = inputArtifactProvider.get().getAsFile();
    org.gradle.api.artifacts.transform.ArtifactTransform transformer = newTransformer();
    transformer.setOutputDirectory(outputDir);
    List<File> outputs = transformer.transform(inputArtifact);
    if (outputs == null) {
        throw new InvalidUserDataException("Transform returned null result.");
    }
    validateOutputs(inputArtifact, outputDir, outputs);
    return ImmutableList.copyOf(outputs);
}
Also used : InvalidUserDataException(org.gradle.api.InvalidUserDataException) File(java.io.File)

Example 29 with InvalidUserDataException

use of org.gradle.api.InvalidUserDataException in project gradle by gradle.

the class RepositoryTransportFactory method validateConnectorFactoryCredentials.

private void validateConnectorFactoryCredentials(Set<String> schemes, ResourceConnectorFactory factory, Collection<Authentication> authentications) {
    Set<Class<? extends Authentication>> configuredAuthenticationTypes = Sets.newHashSet();
    for (Authentication authentication : authentications) {
        AuthenticationInternal authenticationInternal = (AuthenticationInternal) authentication;
        boolean isAuthenticationSupported = false;
        Credentials credentials = authenticationInternal.getCredentials();
        boolean needCredentials = authenticationInternal.requiresCredentials();
        for (Class<?> authenticationType : factory.getSupportedAuthentication()) {
            if (authenticationType.isAssignableFrom(authentication.getClass())) {
                isAuthenticationSupported = true;
                break;
            }
        }
        if (!isAuthenticationSupported) {
            throw new InvalidUserDataException(String.format("Authentication scheme %s is not supported by protocol '%s'", authentication, schemes.iterator().next()));
        }
        if (credentials != null) {
            if (!((AuthenticationInternal) authentication).supports(credentials)) {
                throw new InvalidUserDataException(String.format("Credentials type of '%s' is not supported by authentication scheme %s", credentials.getClass().getSimpleName(), authentication));
            }
        } else {
            if (needCredentials) {
                throw new InvalidUserDataException("You cannot configure authentication schemes for this repository type if no credentials are provided.");
            }
        }
        if (!configuredAuthenticationTypes.add(authenticationInternal.getType())) {
            throw new InvalidUserDataException(String.format("You cannot configure multiple authentication schemes of the same type.  The duplicate one is %s.", authentication));
        }
    }
}
Also used : Authentication(org.gradle.authentication.Authentication) InvalidUserDataException(org.gradle.api.InvalidUserDataException) AuthenticationInternal(org.gradle.internal.authentication.AuthenticationInternal) Credentials(org.gradle.api.credentials.Credentials)

Example 30 with InvalidUserDataException

use of org.gradle.api.InvalidUserDataException in project gradle by gradle.

the class DefaultDependenciesAccessors method assertCanGenerateAccessors.

private static boolean assertCanGenerateAccessors(ProjectRegistry<? extends ProjectDescriptor> projectRegistry) {
    List<String> errors = Lists.newArrayList();
    projectRegistry.getAllProjects().stream().map(ProjectDescriptor::getName).filter(p -> !SUPPORTED_PATTERN.matcher(p).matches()).map(name -> "project '" + name + "' doesn't follow the naming convention: " + SUPPORTED_PROJECT_NAMES).forEach(errors::add);
    for (ProjectDescriptor project : projectRegistry.getAllProjects()) {
        project.getChildren().stream().map(ProjectDescriptor::getName).collect(Collectors.groupingBy(AbstractSourceGenerator::toJavaName)).entrySet().stream().filter(e -> e.getValue().size() > 1).forEachOrdered(e -> {
            String javaName = e.getKey();
            List<String> names = e.getValue();
            errors.add("subprojects " + names + " of project " + project.getPath() + " map to the same method name get" + javaName + "()");
        });
    }
    if (!errors.isEmpty()) {
        TreeFormatter formatter = new TreeFormatter();
        formatter.node("Cannot generate project dependency accessors");
        formatter.startChildren();
        for (String error : errors) {
            formatter.node("Cannot generate project dependency accessors because " + error);
        }
        formatter.endChildren();
        throw new InvalidUserDataException(formatter.toString());
    }
    return errors.isEmpty();
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) DirectorySensitivity(org.gradle.internal.fingerprint.DirectorySensitivity) CurrentFileCollectionFingerprint(org.gradle.internal.fingerprint.CurrentFileCollectionFingerprint) Hashing(org.gradle.internal.hash.Hashing) SettingsInternal(org.gradle.api.internal.SettingsInternal) FileValueSupplier(org.gradle.internal.execution.fingerprint.InputFingerprinter.FileValueSupplier) ExecutionResult(org.gradle.internal.execution.ExecutionResult) InputFingerprinter(org.gradle.internal.execution.fingerprint.InputFingerprinter) IncubationLogger(org.gradle.util.internal.IncubationLogger) VersionCatalogBuilder(org.gradle.api.initialization.dsl.VersionCatalogBuilder) DependencyResolutionManagementInternal(org.gradle.internal.management.DependencyResolutionManagementInternal) ProjectInternal(org.gradle.api.internal.project.ProjectInternal) Map(java.util.Map) ExtensionContainer(org.gradle.api.plugins.ExtensionContainer) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) InputVisitor(org.gradle.internal.execution.fingerprint.InputFingerprinter.InputVisitor) Set(java.util.Set) InputPropertyType(org.gradle.internal.execution.fingerprint.InputFingerprinter.InputPropertyType) ValueSnapshot(org.gradle.internal.snapshot.ValueSnapshot) Hasher(org.gradle.internal.hash.Hasher) Settings(org.gradle.api.initialization.Settings) Collectors(java.util.stream.Collectors) List(java.util.List) ProjectRegistry(org.gradle.api.internal.project.ProjectRegistry) DefaultClassPath(org.gradle.internal.classpath.DefaultClassPath) DefaultProjectDependencyFactory(org.gradle.api.internal.artifacts.DefaultProjectDependencyFactory) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) Optional(java.util.Optional) ClassPath(org.gradle.internal.classpath.ClassPath) Pattern(java.util.regex.Pattern) ServiceRegistry(org.gradle.internal.service.ServiceRegistry) Inject(javax.inject.Inject) ExecutionEngine(org.gradle.internal.execution.ExecutionEngine) Lists(com.google.common.collect.Lists) FeaturePreviews(org.gradle.api.internal.FeaturePreviews) TreeType(org.gradle.internal.file.TreeType) ProjectDescriptor(org.gradle.api.initialization.ProjectDescriptor) FileCollectionFactory(org.gradle.api.internal.file.FileCollectionFactory) WorkspaceProvider(org.gradle.internal.execution.workspace.WorkspaceProvider) DependenciesAccessors(org.gradle.initialization.DependenciesAccessors) VersionCatalogsExtension(org.gradle.api.artifacts.VersionCatalogsExtension) Nullable(javax.annotation.Nullable) UnitOfWork(org.gradle.internal.execution.UnitOfWork) ClassPathRegistry(org.gradle.api.internal.ClassPathRegistry) ClasspathNormalizer(org.gradle.api.tasks.ClasspathNormalizer) Iterator(java.util.Iterator) ProjectFinder(org.gradle.api.internal.artifacts.dsl.dependencies.ProjectFinder) StringWriter(java.io.StringWriter) ClassLoaderScope(org.gradle.api.internal.initialization.ClassLoaderScope) LineEndingSensitivity(org.gradle.internal.fingerprint.LineEndingSensitivity) VersionCatalogBuilderInternal(org.gradle.internal.management.VersionCatalogBuilderInternal) Cast(org.gradle.internal.Cast) Maps(com.google.common.collect.Maps) File(java.io.File) ProviderFactory(org.gradle.api.provider.ProviderFactory) VersionCatalog(org.gradle.api.artifacts.VersionCatalog) Property(org.gradle.api.provider.Property) InvalidUserDataException(org.gradle.api.InvalidUserDataException) Collections(java.util.Collections) ProjectDescriptor(org.gradle.api.initialization.ProjectDescriptor) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) InvalidUserDataException(org.gradle.api.InvalidUserDataException)

Aggregations

InvalidUserDataException (org.gradle.api.InvalidUserDataException)61 File (java.io.File)18 Task (org.gradle.api.Task)6 ArrayList (java.util.ArrayList)5 LinkedHashSet (java.util.LinkedHashSet)5 Action (org.gradle.api.Action)5 TaskAction (org.gradle.api.tasks.TaskAction)5 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 DefaultTask (org.gradle.api.DefaultTask)4 ImmutableList (com.google.common.collect.ImmutableList)3 Closure (groovy.lang.Closure)3 Map (java.util.Map)3 MavenArtifactRepository (org.gradle.api.artifacts.repositories.MavenArtifactRepository)3 TaskInternal (org.gradle.api.internal.TaskInternal)3 MavenPublicationInternal (org.gradle.api.publish.maven.internal.publication.MavenPublicationInternal)3 DirectorySensitivity (org.gradle.internal.fingerprint.DirectorySensitivity)3 LineEndingSensitivity (org.gradle.internal.fingerprint.LineEndingSensitivity)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Nullable (javax.annotation.Nullable)2