Search in sources :

Example 1 with BuildException

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

the class ProjectImportErrorHandlerTest method getUserFriendlyError.

// https://code.google.com/p/android/issues/detail?id=226506
@Test
public void getUserFriendlyError() {
    ProjectImportErrorHandler errorHandler = new ProjectImportErrorHandler();
    IllegalStateException cause = new IllegalStateException("Failed to find Build Tools revision 24.0.3");
    BuildException error = new BuildException("Could not run build action.", cause);
    ExternalSystemException userFriendlyError = errorHandler.getUserFriendlyError(error, "fakeProjectPath", null);
    assertNotNull(userFriendlyError);
    assertEquals("Failed to find Build Tools revision 24.0.3", userFriendlyError.getMessage());
}
Also used : ExternalSystemException(com.intellij.openapi.externalSystem.model.ExternalSystemException) BuildException(org.gradle.tooling.BuildException) Test(org.junit.Test)

Example 2 with BuildException

use of org.gradle.tooling.BuildException 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 3 with BuildException

use of org.gradle.tooling.BuildException in project atlas by alibaba.

the class ResourcesShrinker method splitAction.

@Nullable
public File splitAction(@NonNull ApkData apkData, @Nullable File uncompressedResourceFile, TransformInvocation invocation, SplitList splitList) {
    if (uncompressedResourceFile == null) {
        return null;
    }
    List<File> classes = new ArrayList<>();
    classes.addAll(AtlasBuildContext.atlasMainDexHelperMap.get(variantContext.getVariantName()).getInputDirs());
    classes.addAll(AtlasBuildContext.atlasMainDexHelperMap.get(variantContext.getVariantName()).getAllMainDexJars());
    AppVariantOutputContext appVariantOutputContext = variantContext.getAppVariantOutputContext(apkData);
    for (AwbTransform awbTransform : appVariantOutputContext.getAwbTransformMap().values()) {
        classes.addAll(awbTransform.getInputLibraries());
        if (awbTransform.getInputDirs() != null && awbTransform.getInputDirs().size() > 0) {
            classes.addAll(awbTransform.getInputDirs());
        }
    }
    WaitableExecutor executor = WaitableExecutor.useGlobalSharedThreadPool();
    Collection<BuildOutput> mergedManifests = BuildOutputs.load(ResourcesShrinker.this.mergedManifests);
    BuildOutput mergedManifest = OutputScope.getOutput(mergedManifests, TaskOutputHolder.TaskOutputType.MERGED_MANIFESTS, apkData);
    File mappingFile = mappingFileSrc != null ? mappingFileSrc.getSingleFile() : null;
    ForkJoinTask<File> task = executor.execute(() -> {
        File reportFile = null;
        if (mappingFile != null) {
            File logDir = mappingFile.getParentFile();
            if (logDir != null) {
                reportFile = new File(logDir, "resources.txt");
            }
        }
        File compressedResourceFile = new File(compressedResources, "resources-" + apkData.getBaseName() + "-stripped.ap_");
        FileUtils.mkdirs(compressedResourceFile.getParentFile());
        if (mergedManifest == null) {
            try {
                FileUtils.copyFile(uncompressedResourceFile, compressedResourceFile);
            } catch (IOException e) {
                logger.error("Failed to copy uncompressed resource file :", e);
                throw new RuntimeException("Failed to copy uncompressed resource file", e);
            }
            return compressedResourceFile;
        }
        // Analyze resources and usages and strip out unused
        ResourceUsageAnalyzer analyzer = new ResourceUsageAnalyzer(sourceDir, classes, mergedManifest.getOutputFile(), mappingFile, resourceDir.getSingleFile(), reportFile);
        try {
            analyzer.setVerbose(logger.isEnabled(LogLevel.INFO));
            analyzer.setDebug(logger.isEnabled(LogLevel.DEBUG));
            analyzer.analyze();
            // Just rewrite the .ap_ file to strip out the res/ files for unused resources
            analyzer.rewriteResourceZip(uncompressedResourceFile, compressedResourceFile);
            // Dump some stats
            int unused = analyzer.getUnusedResourceCount();
            if (unused > 0) {
                StringBuilder sb = new StringBuilder(200);
                sb.append("Removed unused resources");
                // This is a bit misleading until we can strip out all resource types:
                // int total = analyzer.getTotalResourceCount()
                // sb.append("(" + unused + "/" + total + ")")
                long before = uncompressedResourceFile.length();
                long after = compressedResourceFile.length();
                long percent = (int) ((before - after) * 100 / before);
                sb.append(": Binary resource data reduced from ").append(toKbString(before)).append("KB to ").append(toKbString(after)).append("KB: Removed ").append(percent).append("%");
                if (!ourWarned) {
                    ourWarned = true;
                    String name = variantData.getVariantConfiguration().getBuildType().getName();
                    sb.append("\n").append("Note: If necessary, you can disable resource shrinking by adding\n").append("android {\n").append("    buildTypes {\n").append("        ").append(name).append(" {\n").append("            shrinkResources false\n").append("        }\n").append("    }\n").append("}");
                }
                System.out.println(sb.toString());
            }
        } catch (Exception e) {
            logger.quiet("Failed to shrink resources: ignoring", e);
        } finally {
            analyzer.dispose();
        }
        return compressedResourceFile;
    });
    for (AwbTransform awbTransform : appVariantOutputContext.getAwbTransformMap().values()) {
        AwbBundle awbBundle = awbTransform.getAwbBundle();
        File compressedBundleResourceFile = appVariantOutputContext.getAwbCompressResourcePackageOutputFile(awbBundle);
        File unCompressedBundleResourceFile = appVariantOutputContext.getAwbProcessResourcePackageOutputFile(awbBundle);
        File awbResDir = appVariantOutputContext.getAwbMergedResourceDir(variantContext.getVariantConfiguration(), awbBundle);
        File reportFile = new File(uncompressedResourceFile.getParentFile(), "resources.txt");
        File bundleSourceDir = appVariantOutputContext.getAwbRClassSourceOutputDir(variantContext.getVariantConfiguration(), awbBundle);
        executor.execute(() -> {
            ResourceUsageAnalyzer analyzer = new ResourceUsageAnalyzer(bundleSourceDir, classes, mergedManifest.getOutputFile(), mappingFile, awbResDir, reportFile);
            try {
                analyzer.setVerbose(logger.isEnabled(LogLevel.INFO));
                analyzer.setDebug(logger.isEnabled(LogLevel.DEBUG));
                analyzer.analyze();
                // Just rewrite the .ap_ file to strip out the res/ files for unused resources
                analyzer.rewriteResourceZip(unCompressedBundleResourceFile, compressedBundleResourceFile);
                // Dump some stats
                int unused = analyzer.getUnusedResourceCount();
                if (unused > 0) {
                    StringBuilder sb = new StringBuilder(200);
                    sb.append("Removed awb bundle" + awbBundle.getName() + " unused resources");
                    // This is a bit misleading until we can strip out all resource types:
                    // int total = analyzer.getTotalResourceCount()
                    // sb.append("(" + unused + "/" + total + ")")
                    long before = unCompressedBundleResourceFile.length();
                    long after = compressedBundleResourceFile.length();
                    long percent = (int) ((before - after) * 100 / before);
                    sb.append(": Binary resource data reduced from ").append(toKbString(before)).append("KB to ").append(toKbString(after)).append("KB: Removed ").append(percent).append("%");
                    if (!ourWarned) {
                        ourWarned = true;
                        String name = variantData.getVariantConfiguration().getBuildType().getName();
                        sb.append("\n").append("Note: If necessary, you can disable resource shrinking by adding\n").append("android {\n").append("    buildTypes {\n").append("        ").append(name).append(" {\n").append("            shrinkResources false\n").append("        }\n").append("    }\n").append("}");
                    }
                    System.out.println(sb.toString());
                }
            } catch (Exception e) {
                logger.quiet("Failed to shrink resources: ignoring", e);
            } finally {
                analyzer.dispose();
            }
            return compressedBundleResourceFile;
        });
    }
    try {
        List<WaitableExecutor.TaskResult<File>> taskResults = executor.waitForAllTasks();
        taskResults.forEach(taskResult -> {
            if (taskResult.getException() != null) {
                throw new BuildException(taskResult.getException().getMessage(), taskResult.getException());
            }
        });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
    return task.join();
}
Also used : WaitableExecutor(com.android.ide.common.internal.WaitableExecutor) AppVariantOutputContext(com.android.build.gradle.internal.api.AppVariantOutputContext) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) BuildException(org.gradle.tooling.BuildException) AwbTransform(com.android.build.gradle.internal.api.AwbTransform) ResourceUsageAnalyzer(com.android.build.gradle.tasks.ResourceUsageAnalyzer) BuildException(org.gradle.tooling.BuildException) AwbBundle(com.taobao.android.builder.dependency.model.AwbBundle) File(java.io.File) Nullable(com.android.annotations.Nullable)

Example 4 with BuildException

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

the class ToolingApiGradleExecutor method run.

@Override
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 2.6 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())));
        if (parameters.getStandardInput() != null) {
            launcher.setStandardInput(parameters.getStandardInput());
        }
        launcher.addProgressListener(new TaskExecutionProgressListener(tasks), OperationType.TASK);
        launcher.withArguments(parameters.getBuildArgs().toArray(new String[0]));
        launcher.setJvmArguments(parameters.getJvmArgs().toArray(new String[0]));
        launcher.setEnvironmentVariables(parameters.getEnvironment());
        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)

Aggregations

BuildException (org.gradle.tooling.BuildException)4 File (java.io.File)2 IOException (java.io.IOException)2 GradleConnector (org.gradle.tooling.GradleConnector)2 ProjectConnection (org.gradle.tooling.ProjectConnection)2 DefaultGradleConnector (org.gradle.tooling.internal.consumer.DefaultGradleConnector)2 Nullable (com.android.annotations.Nullable)1 AppVariantOutputContext (com.android.build.gradle.internal.api.AppVariantOutputContext)1 AwbTransform (com.android.build.gradle.internal.api.AwbTransform)1 ResourceUsageAnalyzer (com.android.build.gradle.tasks.ResourceUsageAnalyzer)1 WaitableExecutor (com.android.ide.common.internal.WaitableExecutor)1 BuildMode (com.android.tools.idea.gradle.util.BuildMode)1 ExternalSystemException (com.intellij.openapi.externalSystem.model.ExternalSystemException)1 AwbBundle (com.taobao.android.builder.dependency.model.AwbBundle)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 TeeOutputStream (org.apache.commons.io.output.TeeOutputStream)1 StreamByteBuffer (org.gradle.internal.io.StreamByteBuffer)1