Search in sources :

Example 6 with TreeFormatter

use of org.gradle.internal.logging.text.TreeFormatter in project gradle by gradle.

the class InitBuild method setupProjectLayout.

@TaskAction
public void setupProjectLayout() {
    UserInputHandler inputHandler = getServices().get(UserInputHandler.class);
    ProjectLayoutSetupRegistry projectLayoutRegistry = getProjectLayoutRegistry();
    BuildInitializer initDescriptor = null;
    if (isNullOrEmpty(type)) {
        BuildConverter converter = projectLayoutRegistry.getBuildConverter();
        if (converter.canApplyToCurrentDirectory(projectDir)) {
            if (inputHandler.askYesNoQuestion("Found a " + converter.getSourceBuildDescription() + " build. Generate a Gradle build from this?", true)) {
                initDescriptor = converter;
            }
        }
        if (initDescriptor == null) {
            ComponentType componentType = inputHandler.selectOption("Select type of project to generate", projectLayoutRegistry.getComponentTypes(), projectLayoutRegistry.getDefault().getComponentType());
            List<Language> languages = projectLayoutRegistry.getLanguagesFor(componentType);
            if (languages.size() == 1) {
                initDescriptor = projectLayoutRegistry.get(componentType, languages.get(0));
            } else {
                if (!languages.contains(Language.JAVA)) {
                    // Not yet implemented
                    throw new UnsupportedOperationException();
                }
                Language language = inputHandler.selectOption("Select implementation language", languages, Language.JAVA);
                initDescriptor = projectLayoutRegistry.get(componentType, language);
            }
        }
    } else {
        initDescriptor = projectLayoutRegistry.get(type);
    }
    ModularizationOption modularizationOption;
    if (splitProject.isPresent()) {
        modularizationOption = splitProject.get() ? ModularizationOption.WITH_LIBRARY_PROJECTS : ModularizationOption.SINGLE_PROJECT;
    } else if (initDescriptor.getModularizationOptions().size() == 1) {
        modularizationOption = initDescriptor.getModularizationOptions().iterator().next();
    } else if (!isNullOrEmpty(type)) {
        modularizationOption = ModularizationOption.SINGLE_PROJECT;
    } else {
        modularizationOption = inputHandler.selectOption("Split functionality across multiple subprojects?", initDescriptor.getModularizationOptions(), ModularizationOption.SINGLE_PROJECT);
    }
    BuildInitDsl dsl;
    if (isNullOrEmpty(this.dsl)) {
        dsl = initDescriptor.getDefaultDsl();
        if (initDescriptor.getDsls().size() > 1) {
            dsl = inputHandler.selectOption("Select build script DSL", initDescriptor.getDsls(), dsl);
        }
    } else {
        dsl = BuildInitDsl.fromName(getDsl());
        if (!initDescriptor.getDsls().contains(dsl)) {
            throw new GradleException("The requested DSL '" + getDsl() + "' is not supported for '" + initDescriptor.getId() + "' build type");
        }
    }
    boolean useIncubatingAPIs;
    if (this.useIncubatingAPIs.isPresent()) {
        useIncubatingAPIs = this.useIncubatingAPIs.get();
    } else {
        useIncubatingAPIs = inputHandler.askYesNoQuestion("Generate build using new APIs and behavior (some features may change in the next minor release)?", false);
    }
    BuildInitTestFramework testFramework = null;
    if (modularizationOption == ModularizationOption.WITH_LIBRARY_PROJECTS) {
        // currently we only support JUnit5 tests for this combination
        testFramework = BuildInitTestFramework.JUNIT_JUPITER;
    } else if (isNullOrEmpty(this.testFramework)) {
        testFramework = initDescriptor.getDefaultTestFramework();
        if (initDescriptor.getTestFrameworks().size() > 1) {
            testFramework = inputHandler.selectOption("Select test framework", initDescriptor.getTestFrameworks(), testFramework);
        }
    } else {
        for (BuildInitTestFramework candidate : initDescriptor.getTestFrameworks()) {
            if (this.testFramework.equals(candidate.getId())) {
                testFramework = candidate;
                break;
            }
        }
        if (testFramework == null) {
            TreeFormatter formatter = new TreeFormatter();
            formatter.node("The requested test framework '" + getTestFramework() + "' is not supported for '" + initDescriptor.getId() + "' build type. Supported frameworks");
            formatter.startChildren();
            for (BuildInitTestFramework framework : initDescriptor.getTestFrameworks()) {
                formatter.node("'" + framework.getId() + "'");
            }
            formatter.endChildren();
            throw new GradleException(formatter.toString());
        }
    }
    String projectName = this.projectName;
    if (initDescriptor.supportsProjectName()) {
        if (isNullOrEmpty(projectName)) {
            projectName = inputHandler.askQuestion("Project name", getProjectName());
        }
    } else if (!isNullOrEmpty(projectName)) {
        throw new GradleException("Project name is not supported for '" + initDescriptor.getId() + "' build type.");
    }
    String packageName = this.packageName;
    if (initDescriptor.supportsPackage()) {
        if (isNullOrEmpty(packageName)) {
            packageName = inputHandler.askQuestion("Source package", toPackageName(projectName));
        }
    } else if (!isNullOrEmpty(packageName)) {
        throw new GradleException("Package name is not supported for '" + initDescriptor.getId() + "' build type.");
    }
    if (!isNullOrEmpty(packageName)) {
        if (!SourceVersion.isName(packageName)) {
            throw new GradleException("Package name: '" + packageName + "' is not valid - it may contain invalid characters or reserved words.");
        }
    }
    List<String> subprojectNames = initDescriptor.getComponentType().getDefaultProjectNames();
    InitSettings settings = new InitSettings(projectName, useIncubatingAPIs, subprojectNames, modularizationOption, dsl, packageName, testFramework, insecureProtocol.get(), projectDir);
    initDescriptor.generate(settings);
    initDescriptor.getFurtherReading(settings).ifPresent(link -> getLogger().lifecycle("Get more help with your project: {}", link));
}
Also used : ProjectLayoutSetupRegistry(org.gradle.buildinit.plugins.internal.ProjectLayoutSetupRegistry) BuildConverter(org.gradle.buildinit.plugins.internal.BuildConverter) BuildInitDsl(org.gradle.buildinit.plugins.internal.modifiers.BuildInitDsl) ComponentType(org.gradle.buildinit.plugins.internal.modifiers.ComponentType) BuildInitializer(org.gradle.buildinit.plugins.internal.BuildInitializer) ModularizationOption(org.gradle.buildinit.plugins.internal.modifiers.ModularizationOption) UserInputHandler(org.gradle.api.internal.tasks.userinput.UserInputHandler) Language(org.gradle.buildinit.plugins.internal.modifiers.Language) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) GradleException(org.gradle.api.GradleException) InitSettings(org.gradle.buildinit.plugins.internal.InitSettings) BuildInitTestFramework(org.gradle.buildinit.plugins.internal.modifiers.BuildInitTestFramework) TaskAction(org.gradle.api.tasks.TaskAction)

Example 7 with TreeFormatter

use of org.gradle.internal.logging.text.TreeFormatter in project gradle by gradle.

the class DefaultProjectDependencyPublicationResolver method resolve.

@Override
public <T> T resolve(Class<T> coordsType, ProjectInternal project) {
    // Ensure target project is configured
    projectConfigurer.configureFully(project);
    List<ProjectComponentPublication> publications = new ArrayList<>();
    for (ProjectComponentPublication publication : publicationRegistry.getPublications(ProjectComponentPublication.class, project.getIdentityPath())) {
        if (!publication.isLegacy() && publication.getCoordinates(coordsType) != null) {
            publications.add(publication);
        }
    }
    if (publications.isEmpty()) {
        // Project has no publications: simply use the project name in place of the dependency name
        if (coordsType.isAssignableFrom(ModuleVersionIdentifier.class)) {
            return coordsType.cast(DefaultModuleVersionIdentifier.newId(project.getGroup().toString(), project.getName(), project.getVersion().toString()));
        }
        throw new UnsupportedOperationException(String.format("Could not find any publications of type %s in %s.", coordsType.getSimpleName(), project.getDisplayName()));
    }
    // Select all entry points. An entry point is a publication that does not contain a component whose parent is also published
    Set<SoftwareComponent> ignored = new HashSet<>();
    for (ProjectComponentPublication publication : publications) {
        if (publication.getComponent() != null && publication.getComponent() instanceof ComponentWithVariants) {
            ComponentWithVariants parent = (ComponentWithVariants) publication.getComponent();
            ignored.addAll(parent.getVariants());
        }
    }
    Set<ProjectComponentPublication> topLevel = new LinkedHashSet<>();
    Set<ProjectComponentPublication> topLevelWithComponent = new LinkedHashSet<>();
    for (ProjectComponentPublication publication : publications) {
        if (!publication.isAlias() && (publication.getComponent() == null || !ignored.contains(publication.getComponent()))) {
            topLevel.add(publication);
            if (publication.getComponent() != null) {
                topLevelWithComponent.add(publication);
            }
        }
    }
    if (topLevelWithComponent.size() == 1) {
        return topLevelWithComponent.iterator().next().getCoordinates(coordsType);
    }
    // See if all entry points have the same identifier
    Iterator<ProjectComponentPublication> iterator = topLevel.iterator();
    T candidate = iterator.next().getCoordinates(coordsType);
    while (iterator.hasNext()) {
        T alternative = iterator.next().getCoordinates(coordsType);
        if (!candidate.equals(alternative)) {
            TreeFormatter formatter = new TreeFormatter();
            formatter.node("Publishing is not able to resolve a dependency on a project with multiple publications that have different coordinates.");
            formatter.node("Found the following publications in " + project.getDisplayName());
            formatter.startChildren();
            for (ProjectComponentPublication publication : topLevel) {
                formatter.node(publication.getDisplayName().getCapitalizedDisplayName() + " with coordinates " + publication.getCoordinates(coordsType));
            }
            formatter.endChildren();
            throw new UnsupportedOperationException(formatter.toString());
        }
    }
    return candidate;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) ComponentWithVariants(org.gradle.api.component.ComponentWithVariants) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) SoftwareComponent(org.gradle.api.component.SoftwareComponent) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 8 with TreeFormatter

use of org.gradle.internal.logging.text.TreeFormatter in project gradle by gradle.

the class DefaultVariantTransformRegistry method registerTransform.

@Override
@SuppressWarnings("deprecation")
public void registerTransform(Action<? super org.gradle.api.artifacts.transform.VariantTransform> registrationAction) {
    try {
        UntypedRegistration registration = instantiatorFactory.decorateLenient().newInstance(UntypedRegistration.class, immutableAttributesFactory, instantiatorFactory);
        registrationAction.execute(registration);
        validateActionType(registration.actionType);
        try {
            validateAttributes(registration);
            Object[] parameters = registration.getTransformParameters();
            ArtifactTransformRegistration finalizedRegistration = registrationFactory.create(registration.from.asImmutable(), registration.to.asImmutable(), registration.actionType, parameters);
            transforms.add(finalizedRegistration);
        } catch (Exception e) {
            TreeFormatter formatter = new TreeFormatter();
            formatter.node("Could not register artifact transform ");
            formatter.appendType(registration.actionType);
            formatter.append(" (from ");
            formatter.appendValue(registration.from);
            formatter.append(" to ");
            formatter.appendValue(registration.to);
            formatter.append(").");
            throw new VariantTransformConfigurationException(formatter.toString(), e);
        }
    } catch (VariantTransformConfigurationException e) {
        throw e;
    } catch (Exception e) {
        throw new VariantTransformConfigurationException("Could not register artifact transform.", e);
    }
}
Also used : ArtifactTransformRegistration(org.gradle.api.internal.artifacts.ArtifactTransformRegistration) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) VariantTransformConfigurationException(org.gradle.api.artifacts.transform.VariantTransformConfigurationException) VariantTransformConfigurationException(org.gradle.api.artifacts.transform.VariantTransformConfigurationException)

Example 9 with TreeFormatter

use of org.gradle.internal.logging.text.TreeFormatter in project gradle by gradle.

the class DefaultVariantTransformRegistry method register.

private <T extends TransformParameters> void register(RecordingRegistration registration, Class<? extends TransformAction<?>> actionType, @Nullable T parameterObject) {
    validateActionType(actionType);
    try {
        validateAttributes(registration);
        ArtifactTransformRegistration finalizedRegistration = registrationFactory.create(registration.from.asImmutable(), registration.to.asImmutable(), actionType, parameterObject);
        transforms.add(finalizedRegistration);
    } catch (Exception e) {
        TreeFormatter formatter = new TreeFormatter();
        formatter.node("Could not register artifact transform ");
        formatter.appendType(actionType);
        formatter.append(" (from ");
        formatter.appendValue(registration.from);
        formatter.append(" to ");
        formatter.appendValue(registration.to);
        formatter.append(").");
        throw new VariantTransformConfigurationException(formatter.toString(), e);
    }
}
Also used : ArtifactTransformRegistration(org.gradle.api.internal.artifacts.ArtifactTransformRegistration) TreeFormatter(org.gradle.internal.logging.text.TreeFormatter) VariantTransformConfigurationException(org.gradle.api.artifacts.transform.VariantTransformConfigurationException) VariantTransformConfigurationException(org.gradle.api.artifacts.transform.VariantTransformConfigurationException)

Example 10 with TreeFormatter

use of org.gradle.internal.logging.text.TreeFormatter 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

TreeFormatter (org.gradle.internal.logging.text.TreeFormatter)46 ImmutableList (com.google.common.collect.ImmutableList)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Nullable (javax.annotation.Nullable)3 GradleException (org.gradle.api.GradleException)3 VariantTransformConfigurationException (org.gradle.api.artifacts.transform.VariantTransformConfigurationException)3 ResolvedVariant (org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedVariant)3 Lists (com.google.common.collect.Lists)2 File (java.io.File)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 Collectors (java.util.stream.Collectors)2 Inject (javax.inject.Inject)2 InvalidUserDataException (org.gradle.api.InvalidUserDataException)2 ArtifactTransformRegistration (org.gradle.api.internal.artifacts.ArtifactTransformRegistration)2 ConfigurationMetadata (org.gradle.internal.component.model.ConfigurationMetadata)2 ClassGenerationException (org.gradle.internal.instantiation.ClassGenerationException)2 Solution (org.gradle.problems.Solution)2 ImmutableMap (com.google.common.collect.ImmutableMap)1