<commit_before>/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.testkit.runner

import groovy.transform.Sortable
import org.gradle.integtests.fixtures.AbstractIntegrationSpec
import org.gradle.integtests.fixtures.AbstractMultiTestRunner
import org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer
import org.gradle.integtests.fixtures.daemon.DaemonsFixture
import org.gradle.integtests.fixtures.executer.*
import org.gradle.integtests.fixtures.versions.ReleasedVersionDistributions
import org.gradle.internal.jvm.Jvm
import org.gradle.internal.nativeintegration.services.NativeServices
import org.gradle.internal.os.OperatingSystem
import org.gradle.test.fixtures.file.TestFile
import org.gradle.testkit.runner.fixtures.*
import org.gradle.testkit.runner.internal.GradleProvider
import org.gradle.testkit.runner.internal.feature.TestKitFeature
import org.gradle.util.GradleVersion
import org.gradle.util.SetSystemProperties
import org.gradle.wrapper.GradleUserHomeLookup
import org.junit.Rule
import org.junit.runner.RunWith
import spock.lang.Shared

import java.lang.annotation.Annotation

import static org.gradle.testkit.runner.internal.ToolingApiGradleExecutor.TEST_KIT_DAEMON_DIR_NAME

@RunWith(Runner)
abstract class BaseGradleRunnerIntegrationTest extends AbstractIntegrationSpec {

    public static final GradleVersion MIN_TESTED_VERSION = GradleVersion.version('1.0')
    public static final GradleVersion CUSTOM_DAEMON_DIR_SUPPORT_VERSION = GradleVersion.version("2.2")

    // Context set by multi run infrastructure
    public static GradleVersion gradleVersion
    public static GradleProvider gradleProvider
    public static boolean debug
    public static boolean crossVersion

    @Shared
    IntegrationTestBuildContext buildContext = new IntegrationTestBuildContext()

    @Rule
    SetSystemProperties setSystemProperties = new SetSystemProperties(
        (NativeServices.NATIVE_DIR_OVERRIDE): buildContext.gradleUserHomeDir.file("native").absolutePath,
        (GradleUserHomeLookup.GRADLE_USER_HOME_PROPERTY_KEY): buildContext.gradleUserHomeDir.absolutePath
    )

    boolean requireIsolatedTestKitDir

    TestFile getTestKitDir() {
        requireIsolatedTestKitDir ? file("test-kit-workspace") : buildContext.gradleUserHomeDir
    }

    String getRootProjectName() {
        testDirectory.name
    }

    GradleRunner runner(List<String> arguments) {
        runner(arguments as String[])
    }

    GradleRunner runner(String... arguments) {
        def gradleRunner = GradleRunner.create()
            .withTestKitDir(testKitDir)
            .withProjectDir(testDirectory)
            .withArguments(arguments)
            .withDebug(debug)

        gradleProvider.applyTo(gradleRunner)
        gradleRunner
    }

    static String helloWorldTask() {
        """
        task helloWorld {
            doLast {
                println 'Hello world!'
            }
        }
        """
    }

    DaemonsFixture testKitDaemons() {
        testKitDaemons(gradleVersion)
    }

    DaemonsFixture testKitDaemons(GradleVersion gradleVersion) {
        def daemonDirName = gradleVersion < CUSTOM_DAEMON_DIR_SUPPORT_VERSION ? "daemon" : TEST_KIT_DAEMON_DIR_NAME
        daemons(testKitDir.file(daemonDirName), gradleVersion)
    }

    DaemonsFixture daemons(File daemonDir, GradleVersion version) {
        DaemonLogsAnalyzer.newAnalyzer(daemonDir, version.version)
    }

    def cleanup() {
        if (requireIsolatedTestKitDir) {
            testKitDaemons().killAll()
        }
    }

    ExecutionResult execResult(BuildResult buildResult) {
        new OutputScrapingExecutionResult(buildResult.output, buildResult.output)
    }

    ExecutionFailure execFailure(BuildResult buildResult) {
        new OutputScrapingExecutionFailure(buildResult.output, buildResult.output)
    }

    static class Runner extends AbstractMultiTestRunner {

        private static final Map<Class<? extends Annotation>, TestKitFeature> TESTKIT_FEATURES = [
            (InspectsExecutedTasks): TestKitFeature.CAPTURE_BUILD_RESULT_TASKS,
            (InspectsBuildOutput): TestKitFeature.CAPTURE_BUILD_RESULT_OUTPUT_IN_DEBUG,
            (InjectsPluginClasspath): TestKitFeature.PLUGIN_CLASSPATH_INJECTION
        ]

        private static final IntegrationTestBuildContext BUILD_CONTEXT = new IntegrationTestBuildContext()
        private static final String COMPATIBILITY_SYSPROP_NAME = 'org.gradle.integtest.testkit.compatibility'
        private static final ReleasedVersionDistributions RELEASED_VERSION_DISTRIBUTIONS = new ReleasedVersionDistributions()

        Runner(Class<?> target) {
            super(target)
        }

        @Override
        protected void createExecutions() {
            determineTestedGradleDistributions().each { testedGradleDistribution ->
                def releasedDist = RELEASED_VERSION_DISTRIBUTIONS.getDistribution(testedGradleDistribution.gradleVersion)
                addExecutions(releasedDist, testedGradleDistribution)
            }
        }

        private Set<TestedGradleDistribution> determineTestedGradleDistributions() {
            if (target.getAnnotation(NonCrossVersion)) {
                return [TestedGradleDistribution.UNDER_DEVELOPMENT] as Set
            }

            String version = System.getProperty(COMPATIBILITY_SYSPROP_NAME, 'current')
            switch (version) {
                case 'all':
                    crossVersion = true
                    return [
                        TestedGradleDistribution.forVersion(getMinCompatibleVersion()),
                        TestedGradleDistribution.mostRecentFinalRelease(),
                        TestedGradleDistribution.UNDER_DEVELOPMENT
                    ] as SortedSet
                case 'current': return [
                    TestedGradleDistribution.UNDER_DEVELOPMENT
                ] as Set
                default:
                    throw new IllegalArgumentException("Invalid value for $COMPATIBILITY_SYSPROP_NAME system property: $version (valid values: 'all', 'current')")
            }
        }

        private void addExecutions(releasedDist, TestedGradleDistribution testedGradleDistribution) {
            if (releasedDist && !releasedDist.worksWith(Jvm.current())) {<commit_msg>Field isn't used anymore<commit_after>/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.testkit.runner

import groovy.transform.Sortable
import org.gradle.integtests.fixtures.AbstractIntegrationSpec
import org.gradle.integtests.fixtures.AbstractMultiTestRunner
import org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer
import org.gradle.integtests.fixtures.daemon.DaemonsFixture
import org.gradle.integtests.fixtures.executer.*
import org.gradle.integtests.fixtures.versions.ReleasedVersionDistributions
import org.gradle.internal.jvm.Jvm
import org.gradle.internal.nativeintegration.services.NativeServices
import org.gradle.internal.os.OperatingSystem
import org.gradle.test.fixtures.file.TestFile
import org.gradle.testkit.runner.fixtures.*
import org.gradle.testkit.runner.internal.GradleProvider
import org.gradle.testkit.runner.internal.feature.TestKitFeature
import org.gradle.util.GradleVersion
import org.gradle.util.SetSystemProperties
import org.gradle.wrapper.GradleUserHomeLookup
import org.junit.Rule
import org.junit.runner.RunWith
import spock.lang.Shared

import java.lang.annotation.Annotation

import static org.gradle.testkit.runner.internal.ToolingApiGradleExecutor.TEST_KIT_DAEMON_DIR_NAME

@RunWith(Runner)
abstract class BaseGradleRunnerIntegrationTest extends AbstractIntegrationSpec {

    public static final GradleVersion MIN_TESTED_VERSION = GradleVersion.version('1.0')
    public static final GradleVersion CUSTOM_DAEMON_DIR_SUPPORT_VERSION = GradleVersion.version("2.2")

    // Context set by multi run infrastructure
    public static GradleVersion gradleVersion
    public static GradleProvider gradleProvider
    public static boolean debug

    @Shared
    IntegrationTestBuildContext buildContext = new IntegrationTestBuildContext()

    @Rule
    SetSystemProperties setSystemProperties = new SetSystemProperties(
        (NativeServices.NATIVE_DIR_OVERRIDE): buildContext.gradleUserHomeDir.file("native").absolutePath,
        (GradleUserHomeLookup.GRADLE_USER_HOME_PROPERTY_KEY): buildContext.gradleUserHomeDir.absolutePath
    )

    boolean requireIsolatedTestKitDir

    TestFile getTestKitDir() {
        requireIsolatedTestKitDir ? file("test-kit-workspace") : buildContext.gradleUserHomeDir
    }

    String getRootProjectName() {
        testDirectory.name
    }

    GradleRunner runner(List<String> arguments) {
        runner(arguments as String[])
    }

    GradleRunner runner(String... arguments) {
        def gradleRunner = GradleRunner.create()
            .withTestKitDir(testKitDir)
            .withProjectDir(testDirectory)
            .withArguments(arguments)
            .withDebug(debug)

        gradleProvider.applyTo(gradleRunner)
        gradleRunner
    }

    static String helloWorldTask() {
        """
        task helloWorld {
            doLast {
                println 'Hello world!'
            }
        }
        """
    }

    DaemonsFixture testKitDaemons() {
        testKitDaemons(gradleVersion)
    }

    DaemonsFixture testKitDaemons(GradleVersion gradleVersion) {
        def daemonDirName = gradleVersion < CUSTOM_DAEMON_DIR_SUPPORT_VERSION ? "daemon" : TEST_KIT_DAEMON_DIR_NAME
        daemons(testKitDir.file(daemonDirName), gradleVersion)
    }

    DaemonsFixture daemons(File daemonDir, GradleVersion version) {
        DaemonLogsAnalyzer.newAnalyzer(daemonDir, version.version)
    }

    def cleanup() {
        if (requireIsolatedTestKitDir) {
            testKitDaemons().killAll()
        }
    }

    ExecutionResult execResult(BuildResult buildResult) {
        new OutputScrapingExecutionResult(buildResult.output, buildResult.output)
    }

    ExecutionFailure execFailure(BuildResult buildResult) {
        new OutputScrapingExecutionFailure(buildResult.output, buildResult.output)
    }

    static class Runner extends AbstractMultiTestRunner {

        private static final Map<Class<? extends Annotation>, TestKitFeature> TESTKIT_FEATURES = [
            (InspectsExecutedTasks): TestKitFeature.CAPTURE_BUILD_RESULT_TASKS,
            (InspectsBuildOutput): TestKitFeature.CAPTURE_BUILD_RESULT_OUTPUT_IN_DEBUG,
            (InjectsPluginClasspath): TestKitFeature.PLUGIN_CLASSPATH_INJECTION
        ]

        private static final IntegrationTestBuildContext BUILD_CONTEXT = new IntegrationTestBuildContext()
        private static final String COMPATIBILITY_SYSPROP_NAME = 'org.gradle.integtest.testkit.compatibility'
        private static final ReleasedVersionDistributions RELEASED_VERSION_DISTRIBUTIONS = new ReleasedVersionDistributions()

        Runner(Class<?> target) {
            super(target)
        }

        @Override
        protected void createExecutions() {
            determineTestedGradleDistributions().each { testedGradleDistribution ->
                def releasedDist = RELEASED_VERSION_DISTRIBUTIONS.getDistribution(testedGradleDistribution.gradleVersion)
                addExecutions(releasedDist, testedGradleDistribution)
            }
        }

        private Set<TestedGradleDistribution> determineTestedGradleDistributions() {
            if (target.getAnnotation(NonCrossVersion)) {
                return [TestedGradleDistribution.UNDER_DEVELOPMENT] as Set
            }

            String version = System.getProperty(COMPATIBILITY_SYSPROP_NAME, 'current')
            switch (version) {
                case 'all': return [
                    TestedGradleDistribution.forVersion(getMinCompatibleVersion()),
                    TestedGradleDistribution.mostRecentFinalRelease(),
                    TestedGradleDistribution.UNDER_DEVELOPMENT
                ] as SortedSet
                case 'current': return [
                    TestedGradleDistribution.UNDER_DEVELOPMENT
                ] as Set
                default:
                    throw new IllegalArgumentException("Invalid value for $COMPATIBILITY_SYSPROP_NAME system property: $version (valid values: 'all', 'current')")
            }
        }

        private void addExecutions(releasedDist, TestedGradleDistribution testedGradleDistribution) {
            if (releasedDist && !releasedDist.worksWith(Jvm.current())) {
{'fraction_non_alphanumeric': 0.06878774488142583, 'fraction_numerical': 0.0017675651789659744, 'mean_word_length': 3.325899968142721, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6653390', 'n_tokens_mistral': 3747, 'n_tokens_neox': 3531, 'n_words': 733}