Search in sources :

Example 1 with InterpreterInfo

use of org.python.pydev.ast.interpreter_managers.InterpreterInfo in project gda-core by openGDA.

the class ScriptProjectCreator method createInterpreter.

/**
 * We programmatically create a Jython Interpreter so that the user does not have to.
 */
private static void createInterpreter(IProgressMonitor monitor) throws Exception {
    logger.debug("Stating creation of Jython interpreter");
    final IPreferenceStore preferenceStore = GDAClientActivator.getDefault().getPreferenceStore();
    // Horrible Hack warning: This code is copied from parts of Pydev to set up the interpreter and save it.
    // Code copies from Pydev when the user chooses a Jython interpreter - these are the defaults.
    final Path interpreterPath = Paths.get(BundleUtils.getBundleLocation(JYTHON_BUNDLE).getAbsolutePath());
    final String executable = interpreterPath.resolve(JYTHON_JAR).toString();
    if (!(new File(executable)).exists())
        throw new Exception("Jython jar not found  :" + executable);
    final File script = CorePlugin.getScriptWithinPySrc("interpreterInfo.py");
    if (!script.exists()) {
        throw new RuntimeException("The file specified does not exist: " + script);
    }
    monitor.subTask("Creating interpreter");
    // gets the info for the python side
    String encoding = null;
    Tuple<String, String> outTup = new SimpleJythonRunner().runAndGetOutputWithJar(FileUtils.getFileAbsolutePath(script), executable, null, null, null, monitor, encoding);
    InterpreterInfo info = null;
    try {
        // HACK Otherwise Pydev shows a dialog to the user.
        ModulesManagerWithBuild.IN_TESTS = true;
        info = InterpreterInfo.fromString(outTup.o1, false);
    } catch (Exception e) {
        logger.error("Something went wrong creating the InterpreterInfo.", e);
    } finally {
        ModulesManagerWithBuild.IN_TESTS = false;
    }
    if (info == null) {
        // cancelled
        return;
    }
    // the executable is the jar itself
    info.executableOrJar = executable;
    // we have to find the jars before we restore the compiled libs
    if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_DEFAULT_JAVA_JARS)) {
        List<File> jars = JavaVmLocationFinder.findDefaultJavaJars();
        for (File jar : jars) {
            info.libs.add(FileUtils.getFileAbsolutePath(jar));
        }
    }
    List<String> allScriptProjectFolders = JythonServerFacade.getInstance().getAllScriptProjectFolders();
    for (String s : allScriptProjectFolders) {
        info.libs.add(s);
    }
    // java, java.lang, etc should be found now
    info.restoreCompiledLibs(monitor);
    info.setName(INTERPRETER_NAME);
    final JythonInterpreterManager man = (JythonInterpreterManager) InterpreterManagersAPI.getJythonInterpreterManager();
    HashSet<String> set = new HashSet<>();
    set.add(INTERPRETER_NAME);
    man.setInfos(new IInterpreterInfo[] { info }, set, monitor);
    logger.info("Jython interpreter registered: {}", INTERPRETER_NAME);
}
Also used : Path(java.nio.file.Path) JythonInterpreterManager(org.python.pydev.ast.interpreter_managers.JythonInterpreterManager) CoreException(org.eclipse.core.runtime.CoreException) SimpleJythonRunner(org.python.pydev.ast.runners.SimpleJythonRunner) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) File(java.io.File) HashSet(java.util.HashSet)

Example 2 with InterpreterInfo

use of org.python.pydev.ast.interpreter_managers.InterpreterInfo in project Pydev by fabioz.

the class AdditionalSystemInterpreterInfo method recreateAllInfo.

public static void recreateAllInfo(IInterpreterManager manager, String interpreter, IProgressMonitor monitor) {
    synchronized (additionalSystemInfoLock) {
        try (GlobalFeedbackReporter r = GlobalFeedback.start("Full system reindex...")) {
            final IInterpreterInfo interpreterInfo = manager.getInterpreterInfo(interpreter, monitor);
            int grammarVersion = interpreterInfo.getGrammarVersion();
            AbstractAdditionalTokensInfo currInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(manager, interpreter);
            if (currInfo != null) {
                currInfo.clearAllInfo();
            }
            InterpreterInfo defaultInterpreterInfo = (InterpreterInfo) manager.getInterpreterInfo(interpreter, monitor);
            ISystemModulesManager m = defaultInterpreterInfo.getModulesManager();
            AbstractAdditionalTokensInfo info = restoreInfoForModuleManager(monitor, m, "(system: " + manager.getManagerRelatedName() + " - " + interpreter + ")", new AdditionalSystemInterpreterInfo(manager, interpreter), null, grammarVersion);
            if (info != null) {
                // ok, set it and save it
                additionalSystemInfo.put(new Tuple<String, String>(manager.getManagerRelatedName(), interpreter), info);
                info.save();
            }
        } catch (Throwable e) {
            Log.log(e);
        }
    }
}
Also used : ISystemModulesManager(org.python.pydev.core.ISystemModulesManager) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) GlobalFeedbackReporter(org.python.pydev.shared_core.global_feedback.GlobalFeedback.GlobalFeedbackReporter)

Example 3 with InterpreterInfo

use of org.python.pydev.ast.interpreter_managers.InterpreterInfo in project Pydev by fabioz.

the class PythonRunnerConfigTestWorkbench method testPythonCommandLine.

public void testPythonCommandLine() throws Exception {
    PythonNature nature = PythonNature.getPythonNature(mod1);
    // Create a temporary variable for testing
    IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager();
    IValueVariable myCustomVariable = variableManager.newValueVariable("pydev_python_runner_config_test_var", "", true, "my_custom_value");
    variableManager.addVariables(new IValueVariable[] { myCustomVariable });
    try {
        IInterpreterManager manager = InterpreterManagersAPI.getPythonInterpreterManager(true);
        InterpreterInfo info = (InterpreterInfo) manager.getDefaultInterpreterInfo(false);
        info.setEnvVariables(new String[] { "MY_CUSTOM_VAR_FOR_TEST=FOO", "MY_CUSTOM_VAR_FOR_TEST2=FOO2", "MY_CUSTOM_VAR_WITH_VAR=${pydev_python_runner_config_test_var}" });
        // Make sure variable hasn't been expanded too early
        assertTrue(arrayContains(info.getEnvVariables(), "MY_CUSTOM_VAR_WITH_VAR=${pydev_python_runner_config_test_var}"));
        PythonRunnerConfig runnerConfig = createConfig();
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_FOR_TEST=FOO"));
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_FOR_TEST2=FOO2"));
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_WITH_VAR=my_custom_value"));
        String[] argv = runnerConfig.getCommandLine(false);
        assertFalse(arrayContains(argv, PythonRunnerConfig.getRunFilesScript()));
        assertTrue(arrayContains(argv, mod1.getLocation().toOSString()));
        nature.setVersion(IPythonNature.Versions.PYTHON_VERSION_LATEST, IPythonNature.DEFAULT_INTERPRETER);
        assertEquals(manager.getDefaultInterpreterInfo(false).getExecutableOrJar(), nature.getProjectInterpreter().getExecutableOrJar());
        runnerConfig = createConfig();
        argv = runnerConfig.getCommandLine(false);
        assertEquals(manager.getDefaultInterpreterInfo(false).getExecutableOrJar(), argv[0]);
        IInterpreterManager interpreterManager = nature.getRelatedInterpreterManager();
        InterpreterInfo info2 = new InterpreterInfo(IPythonNature.PYTHON_VERSION_2_6, "c:\\interpreter\\py25.exe", new ArrayList<String>());
        interpreterManager.setInfos(new IInterpreterInfo[] { info, info2 }, null, null);
        nature.setVersion(IPythonNature.Versions.PYTHON_VERSION_LATEST, "c:\\interpreter\\py25.exe");
        assertEquals("c:\\interpreter\\py25.exe", nature.getProjectInterpreter().getExecutableOrJar());
        runnerConfig = createConfig();
        argv = runnerConfig.getCommandLine(false);
        assertEquals("c:\\interpreter\\py25.exe", argv[0]);
        nature.setVersion(IPythonNature.Versions.PYTHON_VERSION_LATEST, IPythonNature.DEFAULT_INTERPRETER);
        ILaunchConfiguration config;
        config = new LaunchShortcut().createDefaultLaunchConfiguration(FileOrResource.createArray(new IResource[] { mod1 }));
        ILaunchConfigurationWorkingCopy workingCopy = config.getWorkingCopy();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("VAR_SPECIFIED_IN_LAUNCH", "BAR");
        // The one in the launch configuration always has preference.
        map.put("MY_CUSTOM_VAR_FOR_TEST2", "BAR2");
        workingCopy.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, map);
        config = workingCopy.doSave();
        runnerConfig = new PythonRunnerConfig(config, ILaunchManager.RUN_MODE, PythonRunnerConfig.RUN_REGULAR);
        assertTrue(arrayContains(runnerConfig.envp, "VAR_SPECIFIED_IN_LAUNCH=BAR"));
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_FOR_TEST=FOO"));
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_FOR_TEST2=BAR2"));
        assertTrue(arrayContains(runnerConfig.envp, "MY_CUSTOM_VAR_WITH_VAR=my_custom_value"));
    } catch (Throwable e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        // restore the default!
        nature.setVersion(IPythonNature.Versions.PYTHON_VERSION_LATEST, IPythonNature.DEFAULT_INTERPRETER);
        variableManager.removeVariables(new IValueVariable[] { myCustomVariable });
    }
}
Also used : ILaunchConfiguration(org.eclipse.debug.core.ILaunchConfiguration) IPythonNature(org.python.pydev.core.IPythonNature) PythonNature(org.python.pydev.plugin.nature.PythonNature) HashMap(java.util.HashMap) ILaunchConfigurationWorkingCopy(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) IInterpreterManager(org.python.pydev.core.IInterpreterManager) IStringVariableManager(org.eclipse.core.variables.IStringVariableManager) IValueVariable(org.eclipse.core.variables.IValueVariable) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo)

Example 4 with InterpreterInfo

use of org.python.pydev.ast.interpreter_managers.InterpreterInfo in project Pydev by fabioz.

the class AbstractInterpreterEditor method fillPathItemsFromName.

/**
 * @param s
 */
private void fillPathItemsFromName(String name) {
    treeWithLibs.removeAll();
    this.forcedBuiltins.removeAllFromList();
    this.predefinedCompletions.removeAllFromList();
    // before any change, apply the changes in the previous info (if not set, that's ok)
    InterpreterInfo workingCopyInfo = workingCopy.getInfo();
    if (workingCopyInfo != null) {
        environmentTab.performApply(workingCopy);
        Properties propertiesFromMap = PropertiesHelper.createPropertiesFromMap(this.tabVariables.getTreeItemsAsMap());
        Properties stringSubstitutionVariables = workingCopyInfo.getStringSubstitutionVariables(false);
        boolean equals = false;
        if (stringSubstitutionVariables == null) {
            if (propertiesFromMap == null || propertiesFromMap.size() == 0) {
                equals = true;
            }
        } else {
            equals = stringSubstitutionVariables.equals(propertiesFromMap);
        }
        if (!equals) {
            exeOrJarOfInterpretersWithStringSubstitutionChanged.add(workingCopyInfo.getExecutableOrJar());
            workingCopyInfo.setStringSubstitutionVariables(propertiesFromMap);
        }
    }
    if (name != null) {
        TreeItem item = new TreeItem(treeWithLibs, SWT.NONE);
        item.setText("System libs");
        item.setImage(ImageCache.asImage(imageSystemLibRoot));
        InterpreterInfo info = (InterpreterInfo) this.nameToInfo.get(name);
        if (info == null) {
            Log.log("Didn't expect interpreter info to be null in the memory: " + name);
        } else {
            for (Iterator<String> iter = info.libs.iterator(); iter.hasNext(); ) {
                TreeItem subItem = new TreeItem(item, SWT.NONE);
                subItem.setText(iter.next());
                subItem.setImage(ImageCache.asImage(imageSystemLib));
                subItem.setData(EnabledTreeDragReorder.DRAG_IMAGE_DATA_KEY, UIConstants.LIB_SYSTEM);
            }
            item.setExpanded(true);
            this.forcedBuiltins.update(info);
            this.predefinedCompletions.update(info);
            workingCopy.setInfo(info);
        }
        if (this.getShowPackageTab()) {
            packageTab.setInfo(info);
        }
        environmentTab.initializeFrom(workingCopy);
        Properties stringSubstitutionVariables = info.getStringSubstitutionVariables(false);
        if (stringSubstitutionVariables != null) {
            this.tabVariables.setTreeItemsFromMap(PropertiesHelper.createMapFromProperties(stringSubstitutionVariables));
        } else {
            this.tabVariables.setTreeItemsFromMap(new HashMap<String, String>());
        }
    }
}
Also used : TreeItem(org.eclipse.swt.widgets.TreeItem) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) Properties(java.util.Properties)

Example 5 with InterpreterInfo

use of org.python.pydev.ast.interpreter_managers.InterpreterInfo in project Pydev by fabioz.

the class AbstractInterpreterEditor method getSelectionListenerSystem.

/**
 * Returns this field editor's selection listener. The listener is created if necessary.
 *
 * @return the selection listener
 */
private SelectionListener getSelectionListenerSystem() {
    if (selectionListenerSystem == null) {
        selectionListenerSystem = new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                if (treeWithInterpreters.getSelectionCount() == 1) {
                    TreeItem[] selection = treeWithInterpreters.getSelection();
                    String nameFromTreeItem = getNameFromTreeItem(selection[0]);
                    InterpreterInfo info = (InterpreterInfo) nameToInfo.get(nameFromTreeItem);
                    exeOrJarOfInterpretersToRestore.add(info.getExecutableOrJar());
                    Widget widget = event.widget;
                    if (widget == addBtSystemFolder) {
                        DirectoryDialog dialog = new DirectoryDialog(getShell());
                        dialog.setFilterPath(lastDirectoryDialogPath);
                        String filePath = dialog.open();
                        if (filePath != null) {
                            lastDirectoryDialogPath = filePath;
                            if (!info.libs.contains(filePath)) {
                                info.libs.add(filePath);
                            }
                        }
                    } else if (widget == addBtSystemJar) {
                        FileDialog dialog = new FileDialog(getShell(), SWT.PRIMARY_MODAL | SWT.MULTI);
                        switch(AbstractInterpreterEditor.this.interpreterManager.getInterpreterType()) {
                            case IInterpreterManager.INTERPRETER_TYPE_JYTHON:
                                dialog.setFilterExtensions(FileTypesPreferences.getWildcardJythonValidZipFiles());
                                break;
                            default:
                                dialog.setFilterExtensions(FileTypesPreferences.getWildcardPythonValidZipFiles());
                        }
                        dialog.setFilterPath(lastFileDialogPath);
                        String filePath = dialog.open();
                        if (filePath != null) {
                            lastFileDialogPath = filePath;
                            File filePath1 = new File(filePath);
                            String dir = filePath1.getParent();
                            String[] fileNames = dialog.getFileNames();
                            for (String f : fileNames) {
                                f = dir + File.separatorChar + f;
                                if (!info.libs.contains(f)) {
                                    info.libs.add(f);
                                }
                            }
                        }
                    } else if (widget == removeBtSystemFolder) {
                        TreeItem[] libSelection = treeWithLibs.getSelection();
                        for (int i = 0; i < libSelection.length; i++) {
                            TreeItem s = libSelection[i];
                            String text = s.getText();
                            info.libs.remove(text);
                        // changed = true;
                        }
                    }
                    updateTree();
                }
            }
        };
    }
    return selectionListenerSystem;
}
Also used : TreeItem(org.eclipse.swt.widgets.TreeItem) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Widget(org.eclipse.swt.widgets.Widget) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) FileDialog(org.eclipse.swt.widgets.FileDialog) File(java.io.File) DirectoryDialog(org.eclipse.swt.widgets.DirectoryDialog)

Aggregations

InterpreterInfo (org.python.pydev.ast.interpreter_managers.InterpreterInfo)34 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)27 IInterpreterManager (org.python.pydev.core.IInterpreterManager)13 ArrayList (java.util.ArrayList)11 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)9 AdditionalSystemInterpreterInfo (com.python.pydev.analysis.additionalinfo.AdditionalSystemInterpreterInfo)7 HashMap (java.util.HashMap)5 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)5 File (java.io.File)4 Collection (java.util.Collection)4 HashSet (java.util.HashSet)4 IEclipsePreferences (org.eclipse.core.runtime.preferences.IEclipsePreferences)4 PythonInterpreterManager (org.python.pydev.ast.interpreter_managers.PythonInterpreterManager)4 MisconfigurationException (org.python.pydev.core.MisconfigurationException)4 DataAndImageTreeNode (org.python.pydev.shared_core.structure.DataAndImageTreeNode)4 TreeNode (org.python.pydev.shared_core.structure.TreeNode)4 Tuple (org.python.pydev.shared_core.structure.Tuple)4 Map (java.util.Map)3 SyncSystemModulesManager (org.python.pydev.ast.codecompletion.revisited.SyncSystemModulesManager)3 IInfo (org.python.pydev.core.IInfo)3