Search in sources :

Example 6 with GradleConnector

use of org.gradle.tooling.GradleConnector in project android by JetBrains.

the class AndroidGradleTargetBuilder method doBuild.

private static void doBuild(@NotNull CompileContext context, @NotNull List<String> buildTasks, @NotNull BuilderExecutionSettings executionSettings, @Nullable String androidHome) throws ProjectBuildException {
    GradleConnector connector = getGradleConnector(executionSettings);
    ProjectConnection connection = connector.connect();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream(BUFFER_SIZE);
    ByteArrayOutputStream stderr = new ByteArrayOutputStream(BUFFER_SIZE);
    try {
        BuildLauncher launcher = connection.newBuild();
        launcher.forTasks(toStringArray(buildTasks));
        List<String> jvmArgs = Lists.newArrayList();
        BuildMode buildMode = executionSettings.getBuildMode();
        if (BuildMode.ASSEMBLE_TRANSLATE == buildMode) {
            String arg = AndroidGradleSettings.createJvmArg(GradleBuilds.ENABLE_TRANSLATION_JVM_ARG, true);
            jvmArgs.add(arg);
        }
        if (androidHome != null && !androidHome.isEmpty()) {
            String androidSdkArg = AndroidGradleSettings.createAndroidHomeJvmArg(androidHome);
            jvmArgs.add(androidSdkArg);
        }
        jvmArgs.addAll(executionSettings.getJvmOptions());
        LOG.info("Build JVM args: " + jvmArgs);
        if (!jvmArgs.isEmpty()) {
            launcher.setJvmArguments(toStringArray(jvmArgs));
        }
        List<String> commandLineArgs = Lists.newArrayList();
        commandLineArgs.addAll(executionSettings.getCommandLineOptions());
        commandLineArgs.add(AndroidGradleSettings.createProjectProperty(AndroidProject.PROPERTY_INVOKED_FROM_IDE, true));
        if (executionSettings.isParallelBuild() && !commandLineArgs.contains(PARALLEL_BUILD_OPTION)) {
            commandLineArgs.add(PARALLEL_BUILD_OPTION);
        }
        if (executionSettings.isOfflineBuild() && !commandLineArgs.contains(OFFLINE_MODE_OPTION)) {
            commandLineArgs.add(OFFLINE_MODE_OPTION);
        }
        if (executionSettings.isConfigureOnDemand() && !commandLineArgs.contains(CONFIGURE_ON_DEMAND_OPTION)) {
            commandLineArgs.add(CONFIGURE_ON_DEMAND_OPTION);
        }
        LOG.info("Build command line args: " + commandLineArgs);
        if (!commandLineArgs.isEmpty()) {
            launcher.withArguments(toStringArray(commandLineArgs));
        }
        File javaHomeDir = executionSettings.getJavaHomeDir();
        if (javaHomeDir != null) {
            launcher.setJavaHome(javaHomeDir);
        }
        launcher.setStandardOutput(stdout);
        launcher.setStandardError(stderr);
        launcher.run();
    } catch (BuildException e) {
        handleBuildException(e, context, stderr.toString());
    } finally {
        String outText = stdout.toString();
        context.processMessage(new ProgressMessage(outText, 1.0f));
        try {
            Closeables.close(stdout, true);
            Closeables.close(stderr, true);
        } catch (IOException e) {
            LOG.debug(e);
        }
        connection.close();
    }
}
Also used : ProgressMessage(org.jetbrains.jps.incremental.messages.ProgressMessage) BuildLauncher(org.gradle.tooling.BuildLauncher) ProjectConnection(org.gradle.tooling.ProjectConnection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProjectBuildException(org.jetbrains.jps.incremental.ProjectBuildException) BuildException(org.gradle.tooling.BuildException) IOException(java.io.IOException) BuildMode(com.android.tools.idea.gradle.util.BuildMode) File(java.io.File) GradleConnector(org.gradle.tooling.GradleConnector) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector)

Example 7 with GradleConnector

use of org.gradle.tooling.GradleConnector in project gradle by gradle.

the class ToolingApiGradleExecutor method run.

public GradleExecutionResult run(GradleExecutionParameters parameters) {
    final StreamByteBuffer outputBuffer = new StreamByteBuffer();
    final OutputStream syncOutput = new SynchronizedOutputStream(outputBuffer.getOutputStream());
    final List<BuildTask> tasks = new ArrayList<BuildTask>();
    maybeRegisterCleanup();
    GradleConnector gradleConnector = buildConnector(parameters.getGradleUserHome(), parameters.getProjectDir(), parameters.isEmbedded(), parameters.getGradleProvider());
    ProjectConnection connection = null;
    GradleVersion targetGradleVersion = null;
    try {
        connection = gradleConnector.connect();
        targetGradleVersion = determineTargetGradleVersion(connection);
        if (targetGradleVersion.compareTo(TestKitFeature.RUN_BUILDS.getSince()) < 0) {
            throw new UnsupportedFeatureException(String.format("The version of Gradle you are using (%s) is not supported by TestKit. TestKit supports all Gradle versions 1.2 and later.", targetGradleVersion.getVersion()));
        }
        DefaultBuildLauncher launcher = (DefaultBuildLauncher) connection.newBuild();
        launcher.setStandardOutput(new NoCloseOutputStream(teeOutput(syncOutput, parameters.getStandardOutput())));
        launcher.setStandardError(new NoCloseOutputStream(teeOutput(syncOutput, parameters.getStandardError())));
        launcher.addProgressListener(new TaskExecutionProgressListener(tasks), OperationType.TASK);
        launcher.withArguments(parameters.getBuildArgs().toArray(new String[0]));
        launcher.setJvmArguments(parameters.getJvmArgs().toArray(new String[0]));
        if (!parameters.getInjectedClassPath().isEmpty()) {
            if (targetGradleVersion.compareTo(TestKitFeature.PLUGIN_CLASSPATH_INJECTION.getSince()) < 0) {
                throw new UnsupportedFeatureException("support plugin classpath injection", targetGradleVersion, TestKitFeature.PLUGIN_CLASSPATH_INJECTION.getSince());
            }
            launcher.withInjectedClassPath(parameters.getInjectedClassPath());
        }
        launcher.run();
    } catch (UnsupportedVersionException e) {
        throw new InvalidRunnerConfigurationException("The build could not be executed due to a feature not being supported by the target Gradle version", e);
    } catch (BuildException t) {
        return new GradleExecutionResult(new BuildOperationParameters(targetGradleVersion, parameters.isEmbedded()), outputBuffer.readAsString(), tasks, t);
    } catch (GradleConnectionException t) {
        StringBuilder message = new StringBuilder("An error occurred executing build with ");
        if (parameters.getBuildArgs().isEmpty()) {
            message.append("no args");
        } else {
            message.append("args '");
            message.append(CollectionUtils.join(" ", parameters.getBuildArgs()));
            message.append("'");
        }
        message.append(" in directory '").append(parameters.getProjectDir().getAbsolutePath()).append("'");
        String capturedOutput = outputBuffer.readAsString();
        if (!capturedOutput.isEmpty()) {
            message.append(". Output before error:").append(SystemProperties.getInstance().getLineSeparator()).append(capturedOutput);
        }
        throw new IllegalStateException(message.toString(), t);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return new GradleExecutionResult(new BuildOperationParameters(targetGradleVersion, parameters.isEmbedded()), outputBuffer.readAsString(), tasks);
}
Also used : BuildTask(org.gradle.testkit.runner.BuildTask) UnsupportedFeatureException(org.gradle.testkit.runner.UnsupportedFeatureException) GradleConnectionException(org.gradle.tooling.GradleConnectionException) SynchronizedOutputStream(org.gradle.testkit.runner.internal.io.SynchronizedOutputStream) TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) NoCloseOutputStream(org.gradle.testkit.runner.internal.io.NoCloseOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ProjectConnection(org.gradle.tooling.ProjectConnection) StreamByteBuffer(org.gradle.internal.io.StreamByteBuffer) InvalidRunnerConfigurationException(org.gradle.testkit.runner.InvalidRunnerConfigurationException) DefaultBuildLauncher(org.gradle.tooling.internal.consumer.DefaultBuildLauncher) GradleConnector(org.gradle.tooling.GradleConnector) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) SynchronizedOutputStream(org.gradle.testkit.runner.internal.io.SynchronizedOutputStream) BuildException(org.gradle.tooling.BuildException) GradleVersion(org.gradle.util.GradleVersion) NoCloseOutputStream(org.gradle.testkit.runner.internal.io.NoCloseOutputStream) UnsupportedVersionException(org.gradle.tooling.UnsupportedVersionException)

Example 8 with GradleConnector

use of org.gradle.tooling.GradleConnector in project spring-boot by spring-projects.

the class GradleIT method test.

private void test(String name, String expected) throws Exception {
    File projectDirectory = new File("target/gradleit/" + name);
    File javaDirectory = new File("target/gradleit/" + name + "/src/main/java/org/test/");
    projectDirectory.mkdirs();
    javaDirectory.mkdirs();
    File script = new File(projectDirectory, "build.gradle");
    FileCopyUtils.copy(new File("src/it/" + name + "/build.gradle"), script);
    FileCopyUtils.copy(new File("src/it/" + name + "/src/main/java/org/test/SampleApplication.java"), new File(javaDirectory, "SampleApplication.java"));
    GradleConnector gradleConnector = GradleConnector.newConnector();
    gradleConnector.useGradleVersion("2.9");
    ((DefaultGradleConnector) gradleConnector).embedded(true);
    ProjectConnection project = gradleConnector.forProjectDirectory(projectDirectory).connect();
    project.newBuild().forTasks("clean", "build").setStandardOutput(System.out).setStandardError(System.err).withArguments("-PbootVersion=" + getBootVersion()).run();
    Verify.verify(new File("target/gradleit/" + name + "/build/libs/" + name + ".jar"), expected);
}
Also used : DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) ProjectConnection(org.gradle.tooling.ProjectConnection) File(java.io.File) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) GradleConnector(org.gradle.tooling.GradleConnector)

Example 9 with GradleConnector

use of org.gradle.tooling.GradleConnector in project paraphrase by JakeWharton.

the class ToolingApiGradleHandleFactory method start.

public GradleHandle start(File directory, List<String> arguments) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(directory);
    ProjectConnection connection = connector.connect();
    BuildLauncher launcher = connection.newBuild();
    String[] argumentArray = new String[arguments.size()];
    arguments.toArray(argumentArray);
    launcher.withArguments(argumentArray);
    return new BuildLauncherBackedGradleHandle(launcher);
}
Also used : BuildLauncher(org.gradle.tooling.BuildLauncher) ProjectConnection(org.gradle.tooling.ProjectConnection) GradleConnector(org.gradle.tooling.GradleConnector)

Example 10 with GradleConnector

use of org.gradle.tooling.GradleConnector in project intellij-community by JetBrains.

the class AbstractModelBuilderTest method setUp.

@Before
public void setUp() throws Exception {
    assumeThat(gradleVersion, versionMatcherRule.getMatcher());
    ensureTempDirCreated();
    String methodName = name.getMethodName();
    Matcher m = TEST_METHOD_NAME_PATTERN.matcher(methodName);
    if (m.matches()) {
        methodName = m.group(1);
    }
    testDir = new File(ourTempDir, methodName);
    FileUtil.ensureExists(testDir);
    final InputStream buildScriptStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.DEFAULT_SCRIPT_NAME);
    try {
        FileUtil.writeToFile(new File(testDir, GradleConstants.DEFAULT_SCRIPT_NAME), FileUtil.loadTextAndClose(buildScriptStream));
    } finally {
        StreamUtil.closeStream(buildScriptStream);
    }
    final InputStream settingsStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.SETTINGS_FILE_NAME);
    try {
        if (settingsStream != null) {
            FileUtil.writeToFile(new File(testDir, GradleConstants.SETTINGS_FILE_NAME), FileUtil.loadTextAndClose(settingsStream));
        }
    } finally {
        StreamUtil.closeStream(settingsStream);
    }
    GradleConnector connector = GradleConnector.newConnector();
    GradleVersion _gradleVersion = GradleVersion.version(gradleVersion);
    final URI distributionUri = new DistributionLocator().getDistributionFor(_gradleVersion);
    connector.useDistribution(distributionUri);
    connector.forProjectDirectory(testDir);
    int daemonMaxIdleTime = 10;
    try {
        daemonMaxIdleTime = Integer.parseInt(System.getProperty("gradleDaemonMaxIdleTime", "10"));
    } catch (NumberFormatException ignore) {
    }
    ((DefaultGradleConnector) connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
    ProjectConnection connection = connector.connect();
    try {
        boolean isGradleProjectDirSupported = _gradleVersion.compareTo(GradleVersion.version("2.4")) >= 0;
        boolean isCompositeBuildsSupported = isGradleProjectDirSupported && _gradleVersion.compareTo(GradleVersion.version("3.1")) >= 0;
        final ProjectImportAction projectImportAction = new ProjectImportAction(false, isGradleProjectDirSupported, isCompositeBuildsSupported);
        projectImportAction.addExtraProjectModelClasses(getModels());
        BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
        File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
        assertNotNull(initScript);
        String jdkHome = IdeaTestUtil.requireRealJdkHome();
        buildActionExecutor.setJavaHome(new File(jdkHome));
        buildActionExecutor.setJvmArguments("-Xmx128m", "-XX:MaxPermSize=64m");
        buildActionExecutor.withArguments("--info", "--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
        allModels = buildActionExecutor.run();
        assertNotNull(allModels);
    } finally {
        connection.close();
    }
}
Also used : Matcher(java.util.regex.Matcher) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) InputStream(java.io.InputStream) ProjectConnection(org.gradle.tooling.ProjectConnection) URI(java.net.URI) ProjectImportAction(org.jetbrains.plugins.gradle.model.ProjectImportAction) GradleConnector(org.gradle.tooling.GradleConnector) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) GradleVersion(org.gradle.util.GradleVersion) File(java.io.File) Before(org.junit.Before)

Aggregations

GradleConnector (org.gradle.tooling.GradleConnector)12 File (java.io.File)9 ProjectConnection (org.gradle.tooling.ProjectConnection)9 DefaultGradleConnector (org.gradle.tooling.internal.consumer.DefaultGradleConnector)8 BuildLauncher (org.gradle.tooling.BuildLauncher)3 GradleVersion (org.gradle.util.GradleVersion)3 InputStream (java.io.InputStream)2 URI (java.net.URI)2 Matcher (java.util.regex.Matcher)2 BuildException (org.gradle.tooling.BuildException)2 ProjectImportAction (org.jetbrains.plugins.gradle.model.ProjectImportAction)2 Before (org.junit.Before)2 AndroidProject (com.android.builder.model.AndroidProject)1 BuildMode (com.android.tools.idea.gradle.util.BuildMode)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 TeeOutputStream (org.apache.commons.io.output.TeeOutputStream)1 StreamByteBuffer (org.gradle.internal.io.StreamByteBuffer)1