Search in sources :

Example 11 with VersionNumber

use of org.gradle.util.internal.VersionNumber in project gradle by gradle.

the class AbstractWindowsKitComponentLocator method findIn.

private Set<T> findIn(File windowsKitDir, DiscoveryType discoveryType) {
    Set<T> found = new LinkedHashSet<T>();
    String[] versionDirs = getComponentVersionDirs(windowsKitDir);
    for (String versionDir : versionDirs) {
        VersionNumber version = VersionNumber.withPatchNumber().parse(versionDir);
        LOGGER.debug("Found {} {} at {}", getDisplayName(), version.toString(), windowsKitDir);
        File binDir = new File(windowsKitDir, "bin/" + versionDir);
        File unversionedBinDir = new File(windowsKitDir, "bin");
        if (isValidComponentBinDir(binDir)) {
            T component = newComponent(windowsKitDir, binDir, version, discoveryType);
            found.add(component);
        } else if (isValidComponentBinDir(unversionedBinDir)) {
            T component = newComponent(windowsKitDir, unversionedBinDir, version, discoveryType);
            found.add(component);
        }
    }
    if (found.isEmpty()) {
        LOGGER.debug("Ignoring candidate directory {} as it does not look like a {} installation.", windowsKitDir, getDisplayName());
    }
    return found;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) File(java.io.File) VersionNumber(org.gradle.util.internal.VersionNumber)

Example 12 with VersionNumber

use of org.gradle.util.internal.VersionNumber in project gradle by gradle.

the class GroovyRuntime method inferGroovyClasspath.

/**
 * Searches the specified class path for Groovy Jars ({@code groovy(-indy)}, {@code groovy-all(-indy)}) and returns a corresponding class path for executing Groovy tools such as the Groovy
 * compiler and Groovydoc tool. The tool versions will match those of the Groovy Jars found. If no Groovy Jars are found on the specified class path, a class path with the contents of the {@code
 * groovy} configuration will be returned.
 *
 * <p>The returned class path may be empty, or may fail to resolve when asked for its contents.
 *
 * @param classpath a class path containing Groovy Jars
 * @return a corresponding class path for executing Groovy tools such as the Groovy compiler and Groovydoc tool
 */
public FileCollection inferGroovyClasspath(final Iterable<File> classpath) {
    // would differ in at least the following ways: 1. live 2. no autowiring
    return new LazilyInitializedFileCollection() {

        @Override
        public String getDisplayName() {
            return "Groovy runtime classpath";
        }

        @Override
        public FileCollection createDelegate() {
            try {
                return inferGroovyClasspath();
            } catch (RuntimeException e) {
                return new FailingFileCollection(getDisplayName(), e);
            }
        }

        private FileCollection inferGroovyClasspath() {
            GroovyJarFile groovyJar = findGroovyJarFile(classpath);
            if (groovyJar == null) {
                throw new GradleException(String.format("Cannot infer Groovy class path because no Groovy Jar was found on class path: %s", Iterables.toString(classpath)));
            }
            if (groovyJar.isGroovyAll()) {
                return project.getLayout().files(groovyJar.getFile());
            }
            VersionNumber groovyVersion = groovyJar.getVersion();
            // Groovy 3 does not have groovy-all yet we may have the required pieces on classpath via localGroovy()
            if (groovyVersion.getMajor() == 3) {
                return inferGroovy3Classpath(groovyVersion);
            }
            String notation = groovyJar.getDependencyNotation();
            List<Dependency> dependencies = new ArrayList<>();
            addDependencyTo(dependencies, notation);
            if (groovyVersion.compareTo(GROOVY_VERSION_WITH_SEPARATE_ANT) >= 0) {
                // add groovy-ant to bring in Groovydoc for Groovy 2.0+
                addGroovyDependency(notation, dependencies, "groovy-ant");
            }
            if (groovyVersion.compareTo(GROOVY_VERSION_REQUIRING_TEMPLATES) >= 0) {
                // add groovy-templates for Groovy 2.5+
                addGroovyDependency(notation, dependencies, "groovy-templates");
            }
            return detachedRuntimeClasspath(dependencies.toArray(new Dependency[0]));
        }

        private void addGroovyDependency(String groovyDependencyNotion, List<Dependency> dependencies, String otherDependency) {
            String notation = groovyDependencyNotion.replace(":groovy:", ":" + otherDependency + ":");
            addDependencyTo(dependencies, notation);
        }

        private void addDependencyTo(List<Dependency> dependencies, String notation) {
            // project.getDependencies().create(String) seems to be the only feasible way to create a Dependency with a classifier
            dependencies.add(project.getDependencies().create(notation));
        }

        private FileCollection inferGroovy3Classpath(VersionNumber groovyVersion) {
            Set<String> groovyJarNames = groovyJarNamesFor(groovyVersion);
            List<File> groovyClasspath = collectJarsFromClasspath(classpath, groovyJarNames);
            if (groovyClasspath.size() == GROOVY3_LIBS.size()) {
                return project.getLayout().files(groovyClasspath);
            }
            return detachedRuntimeClasspath(GROOVY3_LIBS.stream().map(libName -> project.getDependencies().create("org.codehaus.groovy:" + libName + ":" + groovyVersion)).toArray(Dependency[]::new));
        }

        private Configuration detachedRuntimeClasspath(Dependency... dependencies) {
            Configuration classpath = project.getConfigurations().detachedConfiguration(dependencies);
            jvmEcosystemUtilities().configureAsRuntimeClasspath(classpath);
            return classpath;
        }

        // let's override this so that delegate isn't created at autowiring time (which would mean on every build)
        @Override
        public void visitDependencies(TaskDependencyResolveContext context) {
            if (classpath instanceof Buildable) {
                context.add(classpath);
            }
        }
    };
}
Also used : GroovyJarFile(org.gradle.api.internal.plugins.GroovyJarFile) Configuration(org.gradle.api.artifacts.Configuration) TaskDependencyResolveContext(org.gradle.api.internal.tasks.TaskDependencyResolveContext) ArrayList(java.util.ArrayList) LazilyInitializedFileCollection(org.gradle.api.internal.file.collections.LazilyInitializedFileCollection) Dependency(org.gradle.api.artifacts.Dependency) VersionNumber(org.gradle.util.internal.VersionNumber) FailingFileCollection(org.gradle.api.internal.file.collections.FailingFileCollection) GradleException(org.gradle.api.GradleException) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) GroovyJarFile(org.gradle.api.internal.plugins.GroovyJarFile) File(java.io.File) Buildable(org.gradle.api.Buildable)

Example 13 with VersionNumber

use of org.gradle.util.internal.VersionNumber in project gradle by gradle.

the class ApiGroovyCompiler method applyConfigurationScript.

private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.1")) < 0) {
        throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + "");
    }
    Binding binding = new Binding();
    binding.setVariable("configuration", configuration);
    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();
    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
    configuratorConfig.addCompilationCustomizers(customizer);
    GroovyShell shell = new GroovyShell(binding, configuratorConfig);
    try {
        shell.evaluate(configScript);
    } catch (Exception e) {
        throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e);
    }
}
Also used : Binding(groovy.lang.Binding) GradleException(org.gradle.api.GradleException) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) VersionNumber(org.gradle.util.internal.VersionNumber) GroovyShell(groovy.lang.GroovyShell) GradleException(org.gradle.api.GradleException)

Example 14 with VersionNumber

use of org.gradle.util.internal.VersionNumber in project gradle by gradle.

the class ApiGroovyCompiler method execute.

@Override
public WorkResult execute(final GroovyJavaJointCompileSpec spec) {
    ApiCompilerResult result = new ApiCompilerResult();
    result.getAnnotationProcessingResult().setFullRebuildCause("Incremental annotation processing is not supported by Groovy.");
    GroovySystemLoaderFactory groovySystemLoaderFactory = new GroovySystemLoaderFactory();
    ClassLoader compilerClassLoader = this.getClass().getClassLoader();
    GroovySystemLoader compilerGroovyLoader = groovySystemLoaderFactory.forClassLoader(compilerClassLoader);
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setVerbose(spec.getGroovyCompileOptions().isVerbose());
    configuration.setSourceEncoding(spec.getGroovyCompileOptions().getEncoding());
    configuration.setTargetBytecode(spec.getTargetCompatibility());
    configuration.setTargetDirectory(spec.getDestinationDir());
    canonicalizeValues(spec.getGroovyCompileOptions().getOptimizationOptions());
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.5")) >= 0) {
        configuration.setParameters(spec.getGroovyCompileOptions().isParameters());
    } else if (spec.getGroovyCompileOptions().isParameters()) {
        throw new GradleException("Using Groovy compiler flag '--parameters' requires Groovy 2.5+ but found Groovy " + version);
    }
    IncrementalCompilationCustomizer customizer = IncrementalCompilationCustomizer.fromSpec(spec, result);
    customizer.addToConfiguration(configuration);
    if (spec.getGroovyCompileOptions().getConfigurationScript() != null) {
        applyConfigurationScript(spec.getGroovyCompileOptions().getConfigurationScript(), configuration);
    }
    try {
        configuration.setOptimizationOptions(spec.getGroovyCompileOptions().getOptimizationOptions());
    } catch (NoSuchMethodError ignored) {
    /* method was only introduced in Groovy 1.8 */
    }
    try {
        configuration.setDisabledGlobalASTTransformations(spec.getGroovyCompileOptions().getDisabledGlobalASTTransformations());
    } catch (NoSuchMethodError ignored) {
    /* method was only introduced in Groovy 2.0.0 */
    }
    Map<String, Object> jointCompilationOptions = new HashMap<String, Object>();
    final File stubDir = spec.getGroovyCompileOptions().getStubDir();
    stubDir.mkdirs();
    jointCompilationOptions.put("stubDir", stubDir);
    jointCompilationOptions.put("keepStubs", spec.getGroovyCompileOptions().isKeepStubs());
    configuration.setJointCompilationOptions(jointCompilationOptions);
    ClassLoader classPathLoader;
    if (version.compareTo(VersionNumber.parse("2.0")) < 0) {
        // using a transforming classloader is only required for older buggy Groovy versions
        classPathLoader = new GroovyCompileTransformingClassLoader(getExtClassLoader(), DefaultClassPath.of(spec.getCompileClasspath()));
    } else {
        classPathLoader = new DefaultClassLoaderFactory().createIsolatedClassLoader("api-groovy-compile-loader", DefaultClassPath.of(spec.getCompileClasspath()));
    }
    GroovyClassLoader compileClasspathClassLoader = new GroovyClassLoader(classPathLoader, null);
    GroovySystemLoader compileClasspathLoader = groovySystemLoaderFactory.forClassLoader(classPathLoader);
    FilteringClassLoader.Spec groovyCompilerClassLoaderSpec = new FilteringClassLoader.Spec();
    groovyCompilerClassLoaderSpec.allowPackage("org.codehaus.groovy");
    groovyCompilerClassLoaderSpec.allowPackage("groovy");
    groovyCompilerClassLoaderSpec.allowPackage("groovyjarjarasm");
    // Disallow classes from Groovy Jar that reference external classes. Such classes must be loaded from astTransformClassLoader,
    // or a NoClassDefFoundError will occur. Essentially this is drawing a line between the Groovy compiler and the Groovy
    // library, albeit only for selected classes that run a high risk of being statically referenced from a transform.
    groovyCompilerClassLoaderSpec.disallowClass("groovy.util.GroovyTestCase");
    groovyCompilerClassLoaderSpec.disallowClass("org.codehaus.groovy.transform.NotYetImplementedASTTransformation");
    groovyCompilerClassLoaderSpec.disallowPackage("groovy.servlet");
    FilteringClassLoader groovyCompilerClassLoader = new FilteringClassLoader(GroovyClassLoader.class.getClassLoader(), groovyCompilerClassLoaderSpec);
    // AST transforms need their own class loader that shares compiler classes with the compiler itself
    final GroovyClassLoader astTransformClassLoader = new GroovyClassLoader(groovyCompilerClassLoader, null);
    // where the transform class is loaded from)
    for (File file : spec.getCompileClasspath()) {
        astTransformClassLoader.addClasspath(file.getPath());
    }
    JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(configuration, compileClasspathClassLoader) {

        @Override
        public GroovyClassLoader getTransformLoader() {
            return astTransformClassLoader;
        }
    };
    final boolean shouldProcessAnnotations = shouldProcessAnnotations(spec);
    if (shouldProcessAnnotations) {
        // If an annotation processor is detected, we need to force Java stub generation, so the we can process annotations on Groovy classes
        // We are forcing stub generation by tricking the groovy compiler into thinking there are java files to compile.
        // All java files are just passed to the compile method of the JavaCompiler and aren't processed internally by the Groovy Compiler.
        // Since we're maintaining our own list of Java files independent of what's passed by the Groovy compiler, adding a non-existent java file
        // to the sources won't cause any issues.
        unit.addSources(new File[] { new File("ForceStubGeneration.java") });
    }
    unit.addSources(getSortedSourceFiles(spec));
    unit.setCompilerFactory(new JavaCompilerFactory() {

        @Override
        public JavaCompiler createCompiler(final CompilerConfiguration config) {
            return new JavaCompiler() {

                @Override
                public void compile(List<String> files, CompilationUnit cu) {
                    if (shouldProcessAnnotations) {
                        // In order for the Groovy stubs to have annotation processors invoked against them, they must be compiled as source.
                        // Classes compiled as a result of being on the -sourcepath do not have the annotation processor run against them
                        spec.setSourceFiles(Iterables.concat(spec.getSourceFiles(), projectLayout.files(stubDir).getAsFileTree()));
                    } else {
                        // When annotation processing isn't required, it's better to add the Groovy stubs as part of the source path.
                        // This allows compilations to complete faster, because only the Groovy stubs that are needed by the java source are compiled.
                        ImmutableList.Builder<File> sourcepathBuilder = ImmutableList.builder();
                        sourcepathBuilder.add(stubDir);
                        if (spec.getCompileOptions().getSourcepath() != null) {
                            sourcepathBuilder.addAll(spec.getCompileOptions().getSourcepath());
                        }
                        spec.getCompileOptions().setSourcepath(sourcepathBuilder.build());
                    }
                    spec.setSourceFiles(Iterables.filter(spec.getSourceFiles(), new Predicate<File>() {

                        @Override
                        public boolean apply(File file) {
                            return hasExtension(file, ".java");
                        }
                    }));
                    try {
                        WorkResult javaCompilerResult = javaCompiler.execute(spec);
                        if (javaCompilerResult instanceof ApiCompilerResult) {
                            result.getSourceClassesMapping().putAll(((ApiCompilerResult) javaCompilerResult).getSourceClassesMapping());
                        }
                    } catch (CompilationFailedException e) {
                        cu.getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), cu));
                    }
                }
            };
        }
    });
    try {
        unit.compile();
        return result;
    } catch (org.codehaus.groovy.control.CompilationFailedException e) {
        System.err.println(e.getMessage());
        // Explicit flush, System.err is an auto-flushing PrintWriter unless it is replaced.
        System.err.flush();
        throw new CompilationFailedException();
    } finally {
        // Remove compile and AST types from the Groovy loader
        compilerGroovyLoader.discardTypesFrom(classPathLoader);
        compilerGroovyLoader.discardTypesFrom(astTransformClassLoader);
        // Discard the compile loader
        compileClasspathLoader.shutdown();
        CompositeStoppable.stoppable(classPathLoader, astTransformClassLoader).stop();
    }
}
Also used : HashMap(java.util.HashMap) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovySystemLoader(org.gradle.api.internal.classloading.GroovySystemLoader) GroovySystemLoaderFactory(org.gradle.api.internal.classloading.GroovySystemLoaderFactory) DefaultClassLoaderFactory(org.gradle.internal.classloader.DefaultClassLoaderFactory) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) JavaCompiler(org.codehaus.groovy.tools.javac.JavaCompiler) JavaCompilerFactory(org.codehaus.groovy.tools.javac.JavaCompilerFactory) VersionNumber(org.gradle.util.internal.VersionNumber) GradleException(org.gradle.api.GradleException) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) WorkResult(org.gradle.api.tasks.WorkResult) File(java.io.File)

Example 15 with VersionNumber

use of org.gradle.util.internal.VersionNumber in project gradle by gradle.

the class LegacyGradleEnterprisePluginCheckInService method collect.

@Override
public BuildScanConfig collect(BuildScanPluginMetadata pluginMetadata) {
    if (manager.isPresent()) {
        throw new IllegalStateException("Configuration has already been collected.");
    }
    VersionNumber pluginVersion = VersionNumber.parse(pluginMetadata.getVersion()).getBaseVersion();
    if (pluginVersion.compareTo(FIRST_GRADLE_ENTERPRISE_PLUGIN_VERSION) < 0) {
        throw new UnsupportedBuildScanPluginVersionException(GradleEnterprisePluginManager.OLD_SCAN_PLUGIN_VERSION_MESSAGE);
    }
    String unsupportedReason = unsupportedReason(pluginVersion);
    if (unsupportedReason == null) {
        manager.registerAdapter(new Adapter());
    } else {
        manager.unsupported();
        if (!isPluginAwareOfUnsupported(pluginVersion)) {
            throw new UnsupportedBuildScanPluginVersionException(unsupportedReason);
        }
    }
    return new Config(Requestedness.from(gradle), new Attributes(buildType), unsupportedReason);
}
Also used : BuildScanConfig(org.gradle.internal.scan.config.BuildScanConfig) GradleEnterprisePluginAdapter(org.gradle.internal.enterprise.core.GradleEnterprisePluginAdapter) VersionNumber(org.gradle.util.internal.VersionNumber)

Aggregations

VersionNumber (org.gradle.util.internal.VersionNumber)16 File (java.io.File)9 GradleException (org.gradle.api.GradleException)3 ArrayList (java.util.ArrayList)2 Matcher (java.util.regex.Matcher)2 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)2 TestFile (org.gradle.test.fixtures.file.TestFile)2 Binding (groovy.lang.Binding)1 GroovyClassLoader (groovy.lang.GroovyClassLoader)1 GroovyShell (groovy.lang.GroovyShell)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 StringReader (java.io.StringReader)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 Pattern (java.util.regex.Pattern)1 Collectors.toList (java.util.stream.Collectors.toList)1 MissingRegistryEntryException (net.rubygrapefruit.platform.MissingRegistryEntryException)1 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)1