Search in sources :

Example 6 with OrderEnumerator

use of com.intellij.openapi.roots.OrderEnumerator in project intellij-community by JetBrains.

the class PluginRunConfiguration method getState.

@Override
public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
    final Module module = getModule();
    if (module == null) {
        throw new ExecutionException(DevKitBundle.message("run.configuration.no.module.specified"));
    }
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
    final Sdk jdk = rootManager.getSdk();
    if (jdk == null) {
        throw CantRunException.noJdkForModule(module);
    }
    final Sdk ideaJdk = IdeaJdk.findIdeaJdk(jdk);
    if (ideaJdk == null) {
        throw new ExecutionException(DevKitBundle.message("sdk.type.incorrect.common"));
    }
    String sandboxHome = ((Sandbox) ideaJdk.getSdkAdditionalData()).getSandboxHome();
    if (sandboxHome == null) {
        throw new ExecutionException(DevKitBundle.message("sandbox.no.configured"));
    }
    try {
        sandboxHome = new File(sandboxHome).getCanonicalPath();
    } catch (IOException e) {
        throw new ExecutionException(DevKitBundle.message("sandbox.no.configured"));
    }
    final String canonicalSandbox = sandboxHome;
    //copy license from running instance of idea
    IdeaLicenseHelper.copyIDEALicense(sandboxHome);
    final JavaCommandLineState state = new JavaCommandLineState(env) {

        @Override
        protected JavaParameters createJavaParameters() throws ExecutionException {
            final JavaParameters params = new JavaParameters();
            ParametersList vm = params.getVMParametersList();
            fillParameterList(vm, VM_PARAMETERS);
            fillParameterList(params.getProgramParametersList(), PROGRAM_PARAMETERS);
            Sdk usedIdeaJdk = ideaJdk;
            String alternativeIdePath = getAlternativeJrePath();
            if (isAlternativeJreEnabled() && !StringUtil.isEmptyOrSpaces(alternativeIdePath)) {
                final Sdk configuredJdk = ProjectJdkTable.getInstance().findJdk(alternativeIdePath);
                if (configuredJdk != null) {
                    usedIdeaJdk = configuredJdk;
                } else {
                    try {
                        usedIdeaJdk = (Sdk) usedIdeaJdk.clone();
                    } catch (CloneNotSupportedException e) {
                        throw new ExecutionException(e.getMessage());
                    }
                    final SdkModificator sdkToSetUp = usedIdeaJdk.getSdkModificator();
                    sdkToSetUp.setHomePath(alternativeIdePath);
                    sdkToSetUp.commitChanges();
                }
            }
            String ideaJdkHome = usedIdeaJdk.getHomePath();
            boolean fromIdeaProject = IdeaJdk.isFromIDEAProject(ideaJdkHome);
            if (!fromIdeaProject) {
                String bootPath = "/lib/boot.jar";
                vm.add("-Xbootclasspath/a:" + ideaJdkHome + toSystemDependentName(bootPath));
            }
            vm.defineProperty("idea.config.path", canonicalSandbox + File.separator + "config");
            vm.defineProperty("idea.system.path", canonicalSandbox + File.separator + "system");
            vm.defineProperty("idea.plugins.path", canonicalSandbox + File.separator + "plugins");
            vm.defineProperty("idea.classpath.index.enabled", "false");
            if (!vm.hasProperty(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY) && PluginModuleType.isOfType(module)) {
                final String id = DescriptorUtil.getPluginId(module);
                if (id != null) {
                    vm.defineProperty(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY, id);
                }
            }
            if (SystemInfo.isMac) {
                vm.defineProperty("idea.smooth.progress", "false");
                vm.defineProperty("apple.laf.useScreenMenuBar", "true");
                vm.defineProperty("apple.awt.fileDialogForDirectories", "true");
            }
            if (SystemInfo.isXWindow) {
                if (VM_PARAMETERS == null || !VM_PARAMETERS.contains("-Dsun.awt.disablegrab")) {
                    // See http://devnet.jetbrains.net/docs/DOC-1142
                    vm.defineProperty("sun.awt.disablegrab", "true");
                }
            }
            if (!vm.hasProperty(PlatformUtils.PLATFORM_PREFIX_KEY)) {
                String buildNumber = IdeaJdk.getBuildNumber(ideaJdkHome);
                if (buildNumber != null) {
                    String prefix = IntelliJPlatformProduct.fromBuildNumber(buildNumber).getPlatformPrefix();
                    if (prefix != null) {
                        vm.defineProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix);
                    }
                }
            }
            params.setWorkingDirectory(ideaJdkHome + File.separator + "bin" + File.separator);
            params.setJdk(usedIdeaJdk);
            if (fromIdeaProject) {
                OrderEnumerator enumerator = OrderEnumerator.orderEntries(module).recursively();
                for (VirtualFile file : enumerator.getAllLibrariesAndSdkClassesRoots()) {
                    params.getClassPath().add(file);
                }
            } else {
                for (String path : Arrays.asList("log4j.jar", "jdom.jar", "trove4j.jar", "openapi.jar", "util.jar", "extensions.jar", "bootstrap.jar", "idea_rt.jar", "idea.jar")) {
                    params.getClassPath().add(ideaJdkHome + toSystemDependentName("/lib/" + path));
                }
            }
            params.getClassPath().addFirst(((JavaSdkType) usedIdeaJdk.getSdkType()).getToolsPath(usedIdeaJdk));
            params.setMainClass("com.intellij.idea.Main");
            return params;
        }
    };
    return state;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) IOException(java.io.IOException) SdkModificator(com.intellij.openapi.projectRoots.SdkModificator) Sandbox(org.jetbrains.idea.devkit.projectRoots.Sandbox) OrderEnumerator(com.intellij.openapi.roots.OrderEnumerator) Sdk(com.intellij.openapi.projectRoots.Sdk) Module(com.intellij.openapi.module.Module) ExecutionException(com.intellij.execution.ExecutionException) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 7 with OrderEnumerator

use of com.intellij.openapi.roots.OrderEnumerator in project intellij-community by JetBrains.

the class JavaScratchCompilationSupport method execute.

@Override
public boolean execute(CompileContext context) {
    final Project project = context.getProject();
    final RunConfiguration configuration = CompileStepBeforeRun.getRunConfiguration(context);
    if (!(configuration instanceof JavaScratchConfiguration)) {
        return true;
    }
    final JavaScratchConfiguration scratchConfig = (JavaScratchConfiguration) configuration;
    final String scratchUrl = scratchConfig.getScratchFileUrl();
    if (scratchUrl == null) {
        context.addMessage(CompilerMessageCategory.ERROR, "Associated scratch file not found", null, -1, -1);
        return false;
    }
    @Nullable final Module module = scratchConfig.getConfigurationModule().getModule();
    final Sdk targetSdk = module != null ? ModuleRootManager.getInstance(module).getSdk() : ProjectRootManager.getInstance(project).getProjectSdk();
    if (targetSdk == null) {
        final String message = module != null ? "Cannot find associated SDK for run configuration module \"" + module.getName() + "\".\nPlease check project settings." : "Cannot find associated project SDK for the run configuration.\nPlease check project settings.";
        context.addMessage(CompilerMessageCategory.ERROR, message, scratchUrl, -1, -1);
        return true;
    }
    if (!(targetSdk.getSdkType() instanceof JavaSdkType)) {
        final String message = module != null ? "Expected Java SDK for run configuration module \"" + module.getName() + "\".\nPlease check project settings." : "Expected Java SDK for project \"" + project.getName() + "\".\nPlease check project settings.";
        context.addMessage(CompilerMessageCategory.ERROR, message, scratchUrl, -1, -1);
        return true;
    }
    final File outputDir = getScratchOutputDirectory(project);
    if (outputDir == null) {
        // should not happen for normal projects
        return true;
    }
    // perform cleanup
    FileUtil.delete(outputDir);
    try {
        final File scratchFile = new File(VirtualFileManager.extractPath(scratchUrl));
        File srcFile = scratchFile;
        if (!StringUtil.endsWith(srcFile.getName(), ".java")) {
            final File srcDir = getScratchTempDirectory(project);
            if (srcDir == null) {
                // should not happen for normal projects
                return true;
            }
            // perform cleanup
            FileUtil.delete(srcDir);
            final String srcFileName = ApplicationManager.getApplication().runReadAction(new Computable<String>() {

                @Override
                public String compute() {
                    final VirtualFile vFile = VirtualFileManager.getInstance().findFileByUrl(scratchUrl);
                    if (vFile != null) {
                        final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
                        if (psiFile instanceof PsiJavaFile) {
                            String name = null;
                            // take the name of the first found public top-level class, otherwise the name of any available top-level class
                            for (PsiClass aClass : ((PsiJavaFile) psiFile).getClasses()) {
                                if (name == null) {
                                    name = aClass.getName();
                                    if (isPublic(aClass)) {
                                        break;
                                    }
                                } else if (isPublic(aClass)) {
                                    name = aClass.getName();
                                    break;
                                }
                            }
                            if (name != null) {
                                return name;
                            }
                        }
                    }
                    return FileUtil.getNameWithoutExtension(scratchFile);
                }
            });
            srcFile = new File(srcDir, srcFileName + ".java");
            FileUtil.copy(scratchFile, srcFile);
        }
        final Collection<File> files = Collections.singleton(srcFile);
        final Set<File> cp = new LinkedHashSet<>();
        final List<File> platformCp = new ArrayList<>();
        final Computable<OrderEnumerator> orderEnumerator = module != null ? (Computable<OrderEnumerator>) () -> ModuleRootManager.getInstance(module).orderEntries() : (Computable<OrderEnumerator>) () -> ProjectRootManager.getInstance(project).orderEntries();
        ApplicationManager.getApplication().runReadAction(() -> {
            for (String s : orderEnumerator.compute().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList().getPathList()) {
                cp.add(new File(s));
            }
            for (String s : orderEnumerator.compute().compileOnly().sdkOnly().getPathsList().getPathList()) {
                platformCp.add(new File(s));
            }
        });
        final List<String> options = new ArrayList<>();
        // always compile with debug info
        options.add("-g");
        final JavaSdkVersion sdkVersion = JavaSdk.getInstance().getVersion(targetSdk);
        if (sdkVersion != null) {
            final String langLevel = "1." + Integer.valueOf(3 + sdkVersion.getMaxLanguageLevel().ordinal());
            options.add("-source");
            options.add(langLevel);
            options.add("-target");
            options.add(langLevel);
        }
        // disable annotation processing
        options.add("-proc:none");
        final Collection<ClassObject> result = CompilerManager.getInstance(project).compileJavaCode(options, platformCp, cp, Collections.emptyList(), Collections.emptyList(), files, outputDir);
        for (ClassObject classObject : result) {
            final byte[] bytes = classObject.getContent();
            if (bytes != null) {
                FileUtil.writeToFile(new File(classObject.getPath()), bytes);
            }
        }
    } catch (CompilationException e) {
        for (CompilationException.Message m : e.getMessages()) {
            context.addMessage(m.getCategory(), m.getText(), scratchUrl, m.getLine(), m.getColumn());
        }
    } catch (IOException e) {
        context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), scratchUrl, -1, -1);
    }
    return true;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) JavaSdkVersion(com.intellij.openapi.projectRoots.JavaSdkVersion) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) OrderEnumerator(com.intellij.openapi.roots.OrderEnumerator) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) Sdk(com.intellij.openapi.projectRoots.Sdk) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

OrderEnumerator (com.intellij.openapi.roots.OrderEnumerator)7 VirtualFile (com.intellij.openapi.vfs.VirtualFile)7 Nullable (org.jetbrains.annotations.Nullable)4 Module (com.intellij.openapi.module.Module)3 Project (com.intellij.openapi.project.Project)3 THashSet (gnu.trove.THashSet)3 IOException (java.io.IOException)3 Sdk (com.intellij.openapi.projectRoots.Sdk)2 ModuleRootManager (com.intellij.openapi.roots.ModuleRootManager)2 File (java.io.File)2 NotNull (org.jetbrains.annotations.NotNull)2 ExecutionException (com.intellij.execution.ExecutionException)1 RunConfiguration (com.intellij.execution.configurations.RunConfiguration)1 ModuleManager (com.intellij.openapi.module.ModuleManager)1 JavaSdk (com.intellij.openapi.projectRoots.JavaSdk)1 JavaSdkType (com.intellij.openapi.projectRoots.JavaSdkType)1 JavaSdkVersion (com.intellij.openapi.projectRoots.JavaSdkVersion)1 SdkModificator (com.intellij.openapi.projectRoots.SdkModificator)1 ContentIterator (com.intellij.openapi.roots.ContentIterator)1 ProjectRootManager (com.intellij.openapi.roots.ProjectRootManager)1