Search in sources :

Example 6 with GradleInvocationResult

use of com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult in project android by JetBrains.

the class GradleTaskRunner method newRunner.

static GradleTaskRunner newRunner(@NotNull Project project) {
    return new GradleTaskRunner() {

        @Override
        public boolean run(@NotNull List<String> tasks, @Nullable BuildMode buildMode, @NotNull List<String> commandLineArguments) throws InvocationTargetException, InterruptedException {
            assert !ApplicationManager.getApplication().isDispatchThread();
            final GradleBuildInvoker gradleBuildInvoker = GradleBuildInvoker.getInstance(project);
            final AtomicBoolean success = new AtomicBoolean();
            final Semaphore done = new Semaphore();
            done.down();
            final GradleBuildInvoker.AfterGradleInvocationTask afterTask = new GradleBuildInvoker.AfterGradleInvocationTask() {

                @Override
                public void execute(@NotNull GradleInvocationResult result) {
                    success.set(result.isBuildSuccessful());
                    gradleBuildInvoker.remove(this);
                    done.up();
                }
            };
            // To ensure that the "Run Configuration" waits for the Gradle tasks to be executed, we use SwingUtilities.invokeAndWait. I tried
            // using Application.invokeAndWait but it never worked. IDEA also uses SwingUtilities in this scenario (see CompileStepBeforeRun.)
            TransactionGuard.submitTransaction(project, () -> {
                gradleBuildInvoker.add(afterTask);
                gradleBuildInvoker.executeTasks(tasks, buildMode, commandLineArguments);
            });
            done.waitFor();
            return success.get();
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) List(java.util.List) Semaphore(com.intellij.util.concurrency.Semaphore) BuildMode(com.android.tools.idea.gradle.util.BuildMode) NotNull(org.jetbrains.annotations.NotNull) Nullable(org.jetbrains.annotations.Nullable) GradleBuildInvoker(com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker)

Example 7 with GradleInvocationResult

use of com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult in project android by JetBrains.

the class AndroidGradleTestCase method invokeGradle.

@NotNull
private static GradleInvocationResult invokeGradle(@NotNull Project project, @NotNull Consumer<GradleBuildInvoker> gradleInvocationTask) throws InterruptedException {
    Ref<GradleInvocationResult> resultRef = new Ref<>();
    CountDownLatch latch = new CountDownLatch(1);
    GradleBuildInvoker gradleBuildInvoker = GradleBuildInvoker.getInstance(project);
    GradleBuildInvoker.AfterGradleInvocationTask task = result -> {
        resultRef.set(result);
        latch.countDown();
    };
    gradleBuildInvoker.add(task);
    try {
        gradleInvocationTask.consume(gradleBuildInvoker);
    } finally {
        gradleBuildInvoker.remove(task);
    }
    latch.await();
    GradleInvocationResult result = resultRef.get();
    assert result != null;
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Projects.isLegacyIdeaAndroidProject(com.android.tools.idea.gradle.util.Projects.isLegacyIdeaAndroidProject) TestFixtureBuilder(com.intellij.testFramework.fixtures.TestFixtureBuilder) PsiManager(com.intellij.psi.PsiManager) Matcher(java.util.regex.Matcher) ProjectManager(com.intellij.openapi.project.ProjectManager) JavaTestFixtureFactory(com.intellij.testFramework.fixtures.JavaTestFixtureFactory) GradleProjectImporter(com.android.tools.idea.gradle.project.importing.GradleProjectImporter) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) GradleSyncInvoker(com.android.tools.idea.gradle.project.sync.GradleSyncInvoker) Truth.assertAbout(com.google.common.truth.Truth.assertAbout) IdeInfo(com.android.tools.idea.IdeInfo) PlatformTestCase(com.intellij.testFramework.PlatformTestCase) EmptyModuleType(com.intellij.openapi.module.EmptyModuleType) AndroidGradleProjectComponent(com.android.tools.idea.gradle.project.AndroidGradleProjectComponent) LocalProperties(com.android.tools.idea.gradle.util.LocalProperties) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) AndroidProjectInfo(com.android.tools.idea.project.AndroidProjectInfo) Nullable(org.jetbrains.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) FileSubject.file(com.android.tools.idea.testing.FileSubject.file) IdeaTestApplication(com.intellij.idea.IdeaTestApplication) Pattern(java.util.regex.Pattern) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) Consumer(com.intellij.util.Consumer) GradleSyncListener(com.android.tools.idea.gradle.project.sync.GradleSyncListener) JDK_1_8(com.intellij.pom.java.LanguageLevel.JDK_1_8) WriteCommandAction.runWriteCommandAction(com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction) WriteAction(com.intellij.openapi.application.WriteAction) SdkConstants(com.android.SdkConstants) ModuleManager(com.intellij.openapi.module.ModuleManager) MINUTES(java.util.concurrent.TimeUnit.MINUTES) Lists(com.google.common.collect.Lists) IdeaProjectTestFixture(com.intellij.testFramework.fixtures.IdeaProjectTestFixture) Files(com.google.common.io.Files) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) ModuleType(com.intellij.openapi.module.ModuleType) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) AndroidTestBase(org.jetbrains.android.AndroidTestBase) VfsUtilCore.virtualToIoFile(com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile) Charsets(com.google.common.base.Charsets) SIMPLE_APPLICATION(com.android.tools.idea.testing.TestProjectPaths.SIMPLE_APPLICATION) Files.write(com.google.common.io.Files.write) GradleBuildInvoker(com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) IOException(java.io.IOException) StringUtil.isEmpty(com.intellij.openapi.util.text.StringUtil.isEmpty) GradleWrapper(com.android.tools.idea.gradle.util.GradleWrapper) TestDialog(com.intellij.openapi.ui.TestDialog) Truth.assertThat(com.google.common.truth.Truth.assertThat) Sdk(com.intellij.openapi.projectRoots.Sdk) RegEx(javax.annotation.RegEx) File(java.io.File) IdeSdks(com.android.tools.idea.sdk.IdeSdks) TestUtils.getWorkspaceFile(com.android.testutils.TestUtils.getWorkspaceFile) TestUtils.getSdk(com.android.testutils.TestUtils.getSdk) Result(com.intellij.openapi.application.Result) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) Jdks(com.android.tools.idea.sdk.Jdks) IdeaTestFixtureFactory(com.intellij.testFramework.fixtures.IdeaTestFixtureFactory) ModuleFileType(com.intellij.ide.highlighter.ModuleFileType) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) Ref(com.intellij.openapi.util.Ref) CountDownLatch(java.util.concurrent.CountDownLatch) GradleBuildInvoker(com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with GradleInvocationResult

use of com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult in project android by JetBrains.

the class NlPreviewTest method testEditCustomView.

@RunIn(TestGroup.UNRELIABLE)
@Test
public void testEditCustomView() throws Exception {
    // Opens the LayoutTest project, opens a layout with a custom view, checks
    // that it can't render yet (because the project hasn't been built),
    // builds the project, checks that the render works, edits the custom view
    // source code, ensures that the render lists the custom view as out of date,
    // applies the suggested fix to build the project, and finally asserts that the
    // build is now successful.
    EditorFixture editor = guiTest.importProjectAndWaitForProjectSyncToFinish("LayoutTest").getEditor().open("app/src/main/res/layout/layout1.xml", EditorFixture.Tab.EDITOR);
    NlPreviewFixture preview = editor.getLayoutPreview(false);
    preview.waitForRenderToFinish();
    assertTrue(preview.hasRenderErrors());
    preview.waitForErrorPanelToContain("The following classes could not be found");
    preview.waitForErrorPanelToContain("com.android.tools.tests.layout.MyButton");
    preview.waitForErrorPanelToContain("Change to android.widget.Button");
    GradleInvocationResult result = guiTest.ideFrame().invokeProjectMake();
    assertTrue(result.isBuildSuccessful());
    // Build completion should trigger re-render
    preview.waitForRenderToFinish();
    assertFalse(preview.hasRenderErrors());
    editor.open("app/src/main/java/com/android/tools/tests/layout/MyButton.java", EditorFixture.Tab.EDITOR).moveBetween("extends Button {", "").enterText(// Next let's edit the custom view source file
    " // test").open("app/src/main/res/layout/layout1.xml", // Switch back; should trigger render
    EditorFixture.Tab.EDITOR);
    preview.waitForRenderToFinish();
    preview.waitForErrorPanelToContain("The MyButton custom view has been edited more recently than the last build");
    result = guiTest.ideFrame().invokeProjectMake();
    assertTrue(result.isBuildSuccessful());
    preview.waitForRenderToFinish();
    assertFalse(preview.hasRenderErrors());
    // Now make some changes to the file which updates the modification timestamp of the source. However,
    // also edit them back and save again (which still leaves a new modification timestamp). Gradle will
    // *not* rebuild if the file contents have not changed (it uses checksums rather than file timestamps).
    // Make sure that we don't get render errors in this scenario! (Regression test for http://b.android.com/76676)
    editor.open("app/src/main/java/com/android/tools/tests/layout/MyButton.java", EditorFixture.Tab.EDITOR).moveBetween("extends Button {", "").enterText(" ").invokeAction(EditorFixture.EditorAction.SAVE).invokeAction(EditorFixture.EditorAction.BACK_SPACE).invokeAction(EditorFixture.EditorAction.SAVE);
    waitForBackgroundTasks(guiTest.robot());
    editor.open("app/src/main/res/layout/layout1.xml", EditorFixture.Tab.EDITOR);
    preview.waitForRenderToFinish();
    preview.waitForErrorPanelToContain("The MyButton custom view has been edited more recently than the last build");
    // this build won't do anything this time, since Gradle notices checksum has not changed
    result = guiTest.ideFrame().invokeProjectMake();
    assertTrue(result.isBuildSuccessful());
    preview.waitForRenderToFinish();
    // but our build timestamp check this time will mask the out of date warning
    assertFalse(preview.hasRenderErrors());
}
Also used : GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) EditorFixture(com.android.tools.idea.tests.gui.framework.fixture.EditorFixture) Test(org.junit.Test) RunIn(com.android.tools.idea.tests.gui.framework.RunIn)

Example 9 with GradleInvocationResult

use of com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult in project android by JetBrains.

the class TemplateTest method checkProject.

private void checkProject(@NonNull String projectName, @NonNull NewProjectWizardState projectValues, @Nullable TemplateWizardState templateValues) throws Exception {
    String modifiedProjectName = projectName + "!@#$^&()_+=-,.`~你所有的基地都属于我们";
    ourCount++;
    projectValues.put(ATTR_RES_OUT, null);
    projectValues.put(ATTR_SRC_OUT, null);
    projectValues.put(ATTR_MANIFEST_OUT, null);
    projectValues.put(ATTR_TEST_OUT, null);
    JavaCodeInsightTestFixture fixture = null;
    File projectDir = null;
    try {
        projectValues.put(ATTR_MODULE_NAME, modifiedProjectName);
        IdeaTestFixtureFactory factory = IdeaTestFixtureFactory.getFixtureFactory();
        TestFixtureBuilder<IdeaProjectTestFixture> projectBuilder = factory.createFixtureBuilder(modifiedProjectName);
        fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture());
        fixture.setUp();
        Project project = fixture.getProject();
        projectDir = Projects.getBaseDirPath(project);
        projectValues.put(ATTR_PROJECT_LOCATION, projectDir.getPath());
        // We only need to sync the model if lint needs to look at the synced project afterwards
        boolean syncModel = CHECK_LINT;
        //noinspection ConstantConditions
        createProject(fixture, projectValues, syncModel);
        if (templateValues != null && !projectValues.getBoolean(ATTR_CREATE_ACTIVITY)) {
            templateValues.put(ATTR_PROJECT_LOCATION, projectDir.getPath());
            ApplicationManager.getApplication().runWriteAction(() -> {
                File projectRoot = virtualToIoFile(project.getBaseDir());
                Template template = templateValues.getTemplate();
                assert template != null;
                File moduleRoot = new File(projectRoot, modifiedProjectName);
                templateValues.put(ATTR_MODULE_NAME, moduleRoot.getName());
                templateValues.populateDirectoryParameters();
                RenderingContext context = RenderingContext.Builder.newContext(template, project).withOutputRoot(moduleRoot).withModuleRoot(moduleRoot).withParams(templateValues.getParameters()).build();
                template.render(context);
                // Add in icons if necessary
                if (templateValues.getTemplateMetadata() != null && templateValues.getTemplateMetadata().getIconName() != null) {
                    File drawableFolder = new File(FileUtil.join(templateValues.getString(ATTR_RES_OUT)), FileUtil.join("drawable"));
                    drawableFolder.mkdirs();
                    String fileName = myStringEvaluator.evaluate(templateValues.getTemplateMetadata().getIconName(), templateValues.getParameters());
                    File iconFile = new File(drawableFolder, fileName + DOT_XML);
                    File sourceFile = new File(getTestDataPath(), FileUtil.join("drawables", "progress_horizontal.xml"));
                    try {
                        FileUtil.copy(sourceFile, iconFile);
                    } catch (IOException e) {
                        fail(e.getMessage());
                    }
                }
            });
        }
        assertNotNull(project);
        System.out.println("Checking project " + projectName + " in " + project.getBaseDir());
        GradleInvocationResult result = invokeGradleTasks(project, "assembleDebug");
        assertThat(result.isBuildSuccessful()).isTrue();
        if (CHECK_LINT) {
            assertLintsCleanly(project, Severity.INFORMATIONAL, Sets.newHashSet(ManifestDetector.TARGET_NEWER));
        // TODO: Check for other warnings / inspections, such as unused imports?
        }
    } finally {
        if (fixture != null) {
            fixture.tearDown();
        }
        Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
        // 1: the project created by default by the test case
        assertTrue(openProjects.length <= 1);
        // Clean up; ensure that we don't bleed contents through to the next iteration
        if (projectDir != null && projectDir.exists()) {
            FileUtil.delete(projectDir);
            LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir);
        }
    }
}
Also used : RenderingContext(com.android.tools.idea.templates.recipe.RenderingContext) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) VirtualFile(com.intellij.openapi.vfs.VirtualFile) VfsUtilCore.virtualToIoFile(com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile) File(java.io.File)

Aggregations

GradleInvocationResult (com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult)9 GradleSyncState (com.android.tools.idea.gradle.project.sync.GradleSyncState)3 File (java.io.File)3 IOException (java.io.IOException)3 NotNull (org.jetbrains.annotations.NotNull)3 Test (org.junit.Test)3 SdkConstants (com.android.SdkConstants)2 GradleBuildInvoker (com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker)2 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)2 RunIn (com.android.tools.idea.tests.gui.framework.RunIn)2 Project (com.intellij.openapi.project.Project)2 VfsUtilCore.virtualToIoFile (com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 Nullable (org.jetbrains.annotations.Nullable)2 Ignore (org.junit.Ignore)2 AndroidLibrary (com.android.builder.model.AndroidLibrary)1 Message (com.android.ide.common.blame.Message)1 TestUtils.getSdk (com.android.testutils.TestUtils.getSdk)1 TestUtils.getWorkspaceFile (com.android.testutils.TestUtils.getWorkspaceFile)1 IdeInfo (com.android.tools.idea.IdeInfo)1