Search in sources :

Example 1 with ICallback

use of org.python.pydev.shared_core.callbacks.ICallback in project Pydev by fabioz.

the class AnalysisBuilderVisitor method visitChangedResource.

public void visitChangedResource(final IResource resource, final ICallback0<IDocument> document, final IProgressMonitor monitor, boolean forceAnalysis) {
    // we may need to 'force' the analysis when a module is renamed, because the first message we receive is
    // a 'delete' and after that an 'add' -- which is later mapped to this method, so, if we don't have info
    // on the module we should analyze it because it is 'probably' a rename.
    final PythonNature nature = getPythonNature(resource);
    if (nature == null) {
        return;
    }
    // Put things from the memo to final variables as we might need them later on and we cannot get them from
    // the memo later.
    final String moduleName;
    final SourceModule[] module = new SourceModule[] { null };
    final IDocument doc;
    doc = document.call();
    if (doc == null) {
        return;
    }
    try {
        moduleName = getModuleName(resource, nature);
    } catch (MisconfigurationException e) {
        Log.log(e);
        return;
    }
    // depending on the level of analysis we have to do, we'll decide whether we want
    // to make the full parse (slower) or the definitions parse (faster but only with info
    // related to the definitions)
    ICallback<IModule, Integer> moduleCallback = new ICallback<IModule, Integer>() {

        @Override
        public IModule call(Integer arg) {
            if (arg == IAnalysisBuilderRunnable.FULL_MODULE) {
                if (module[0] != null) {
                    return module[0];
                } else {
                    try {
                        module[0] = getSourceModule(resource, doc, nature);
                    } catch (MisconfigurationException e1) {
                        throw new RuntimeException(e1);
                    }
                    if (module[0] != null) {
                        return module[0];
                    }
                    try {
                        module[0] = createSoureModule(resource, doc, moduleName);
                    } catch (MisconfigurationException e) {
                        throw new RuntimeException(e);
                    }
                    return module[0];
                }
            } else if (arg == IAnalysisBuilderRunnable.DEFINITIONS_MODULE) {
                if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) {
                    org.python.pydev.shared_core.log.ToLogFile.toLogFile(this, "PyDevBuilderPrefPage.getAnalyzeOnlyActiveEditor()");
                }
                IFile f = (IFile) resource;
                IPath location = f.getLocation();
                if (location != null) {
                    String file = location.toOSString();
                    File f2 = new File(file);
                    return new SourceModule(moduleName, f2, FastDefinitionsParser.parse(doc.get(), moduleName, f2), null, nature);
                }
                return null;
            } else {
                throw new RuntimeException("Unexpected parameter: " + arg);
            }
        }
    };
    long documentTime = this.getDocumentTime();
    if (documentTime == -1) {
        Log.log("Warning: The document time in the visitor is -1. Changing for current time.");
        documentTime = System.currentTimeMillis();
    }
    doVisitChangedResource(nature, resource, doc, moduleCallback, null, monitor, forceAnalysis, AnalysisBuilderRunnable.ANALYSIS_CAUSE_BUILDER, documentTime, false);
}
Also used : SourceModule(org.python.pydev.ast.codecompletion.revisited.modules.SourceModule) IModule(org.python.pydev.core.IModule) IFile(org.eclipse.core.resources.IFile) IPythonNature(org.python.pydev.core.IPythonNature) PythonNature(org.python.pydev.plugin.nature.PythonNature) IPath(org.eclipse.core.runtime.IPath) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ICallback(org.python.pydev.shared_core.callbacks.ICallback) File(java.io.File) IFile(org.eclipse.core.resources.IFile) IDocument(org.eclipse.jface.text.IDocument)

Example 2 with ICallback

use of org.python.pydev.shared_core.callbacks.ICallback in project Pydev by fabioz.

the class Pep8Runner method runWithPep8BaseScript.

/**
 * @param fileContents the contents to be passed in the stdin.
 * @param parameters the parameters to pass. Note that a '-' is always added to the parameters to signal we'll pass the file as the input in stdin.
 * @param script i.e.: pycodestyle.py, autopep8.py
 * @return null if there was some error, otherwise returns the process stdout output.
 */
public static String runWithPep8BaseScript(IDocument doc, String parameters, String script) {
    File autopep8File;
    try {
        autopep8File = CorePlugin.getScriptWithinPySrc(new Path("third_party").append("pep8").append(script).toString());
    } catch (CoreException e) {
        Log.log("Unable to get " + script + " location.");
        return null;
    }
    if (!autopep8File.exists()) {
        Log.log("Specified location for " + script + " does not exist (" + autopep8File + ").");
        return null;
    }
    SimplePythonRunner simplePythonRunner = new SimplePythonRunner();
    IInterpreterManager pythonInterpreterManager = InterpreterManagersAPI.getPythonInterpreterManager();
    IInterpreterInfo defaultInterpreterInfo;
    try {
        defaultInterpreterInfo = pythonInterpreterManager.getDefaultInterpreterInfo(false);
    } catch (MisconfigurationException e) {
        Log.log("No default Python interpreter configured to run " + script);
        return null;
    }
    String[] parseArguments = ProcessUtils.parseArguments(parameters);
    List<String> lst = new ArrayList<>(Arrays.asList(parseArguments));
    lst.add("-");
    String[] cmdarray = SimplePythonRunner.preparePythonCallParameters(defaultInterpreterInfo.getExecutableOrJar(), autopep8File.toString(), lst.toArray(new String[0]));
    // Try to find the file's encoding, but if none is given or the specified encoding is
    // unsupported, then just default to utf-8
    String pythonFileEncoding = null;
    try {
        pythonFileEncoding = FileUtils.getPythonFileEncoding(doc, null);
        if (pythonFileEncoding == null) {
            pythonFileEncoding = "utf-8";
        }
    } catch (UnsupportedEncodingException e) {
        pythonFileEncoding = "utf-8";
    }
    final String encodingUsed = pythonFileEncoding;
    SystemPythonNature nature = new SystemPythonNature(pythonInterpreterManager, defaultInterpreterInfo);
    ICallback<String[], String[]> updateEnv = new ICallback<String[], String[]>() {

        @Override
        public String[] call(String[] arg) {
            if (arg == null) {
                arg = new String[] { "PYTHONIOENCODING=" + encodingUsed };
            } else {
                arg = ProcessUtils.addOrReplaceEnvVar(arg, "PYTHONIOENCODING", encodingUsed);
            }
            return arg;
        }
    };
    Tuple<Process, String> r = simplePythonRunner.run(cmdarray, autopep8File.getParentFile(), nature, new NullProgressMonitor(), updateEnv);
    try {
        r.o1.getOutputStream().write(doc.get().getBytes(pythonFileEncoding));
        r.o1.getOutputStream().close();
    } catch (IOException e) {
        Log.log("Error writing contents to " + script);
        return null;
    }
    Tuple<String, String> processOutput = SimplePythonRunner.getProcessOutput(r.o1, r.o2, new NullProgressMonitor(), pythonFileEncoding);
    if (processOutput.o2.length() > 0) {
        Log.log(processOutput.o2);
    }
    if (processOutput.o1.length() > 0) {
        return processOutput.o1;
    }
    return null;
}
Also used : Path(org.eclipse.core.runtime.Path) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IOException(java.io.IOException) IInterpreterManager(org.python.pydev.core.IInterpreterManager) CoreException(org.eclipse.core.runtime.CoreException) ICallback(org.python.pydev.shared_core.callbacks.ICallback) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner) File(java.io.File)

Example 3 with ICallback

use of org.python.pydev.shared_core.callbacks.ICallback in project Pydev by fabioz.

the class AppEngineWizard method createAndConfigProject.

/**
 * Overridden to add the external source folders from google app engine.
 */
@Override
protected void createAndConfigProject(final IProject newProjectHandle, final IProjectDescription description, final String projectType, final String projectInterpreter, IProgressMonitor monitor, Object... additionalArgsToConfigProject) throws CoreException {
    ICallback<List<IContainer>, IProject> getSourceFolderHandlesCallback = super.getSourceFolderHandlesCallback;
    ICallback<List<IPath>, IProject> getExistingSourceFolderHandlesCallback = super.getExistingSourceFolderHandlesCallback;
    ICallback<List<String>, IProject> getExternalSourceFolderHandlesCallback = new ICallback<List<String>, IProject>() {

        @Override
        public List<String> call(IProject projectHandle) {
            return appEngineConfigWizardPage.getExternalSourceFolders();
        }
    };
    ICallback<Map<String, String>, IProject> getVariableSubstitutionCallback = new ICallback<Map<String, String>, IProject>() {

        @Override
        public Map<String, String> call(IProject projectHandle) {
            return appEngineConfigWizardPage.getVariableSubstitution();
        }
    };
    PyStructureConfigHelpers.createPydevProject(description, newProjectHandle, monitor, projectType, projectInterpreter, getSourceFolderHandlesCallback, getExternalSourceFolderHandlesCallback, getExistingSourceFolderHandlesCallback, getVariableSubstitutionCallback);
    // Ok, after the default is created, let's see if we have a template...
    IContainer sourceFolder;
    final int sourceFolderConfigurationStyle = projectPage.getSourceFolderConfigurationStyle();
    switch(sourceFolderConfigurationStyle) {
        case IWizardNewProjectNameAndLocationPage.PYDEV_NEW_PROJECT_CREATE_PROJECT_AS_SRC_FOLDER:
        case IWizardNewProjectNameAndLocationPage.PYDEV_NEW_PROJECT_NO_PYTHONPATH:
            sourceFolder = newProjectHandle;
            break;
        default:
            sourceFolder = newProjectHandle.getFolder("src");
    }
    appEngineTemplatePage.fillSourceFolder(sourceFolder);
}
Also used : ICallback(org.python.pydev.shared_core.callbacks.ICallback) List(java.util.List) IContainer(org.eclipse.core.resources.IContainer) Map(java.util.Map) IProject(org.eclipse.core.resources.IProject)

Example 4 with ICallback

use of org.python.pydev.shared_core.callbacks.ICallback in project Pydev by fabioz.

the class PyReloadCode method onSave.

@Override
public void onSave(BaseEditor baseEditor, IProgressMonitor monitor) {
    if (!DebugPrefsPage.getReloadModuleOnChange()) {
        return;
    }
    PyEdit edit = (PyEdit) baseEditor;
    File file = edit.getEditorFile();
    if (file != null) {
        IDebugTarget[] debugTargets = DebugPlugin.getDefault().getLaunchManager().getDebugTargets();
        if (debugTargets.length > 0) {
            ICallback<Boolean, IDebugTarget> callbackThatFilters = new ICallback<Boolean, IDebugTarget>() {

                @Override
                public Boolean call(IDebugTarget arg) {
                    return arg instanceof AbstractDebugTarget;
                }
            };
            List<IDebugTarget> filter = ArrayUtils.filter(debugTargets, callbackThatFilters);
            if (filter.size() > 0) {
                try {
                    IPythonNature pythonNature = edit.getPythonNature();
                    if (pythonNature != null) {
                        String moduleName = pythonNature.resolveModule(file);
                        if (moduleName != null) {
                            for (IDebugTarget iDebugTarget : filter) {
                                AbstractDebugTarget target = (AbstractDebugTarget) iDebugTarget;
                                target.postCommand(new ReloadCodeCommand(target, moduleName));
                            }
                        }
                    }
                } catch (MisconfigurationException e) {
                    Log.log(e);
                }
            }
        }
    }
}
Also used : MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature) ICallback(org.python.pydev.shared_core.callbacks.ICallback) IDebugTarget(org.eclipse.debug.core.model.IDebugTarget) ReloadCodeCommand(org.python.pydev.debug.model.remote.ReloadCodeCommand) File(java.io.File) PyEdit(org.python.pydev.editor.PyEdit)

Example 5 with ICallback

use of org.python.pydev.shared_core.callbacks.ICallback in project Pydev by fabioz.

the class PyUnitView2TestTestWorkbench method getPyUnitViewOkCallback.

private ICallback<Boolean, Object> getPyUnitViewOkCallback(final int historySize, final int methodsAppearingInTree) {
    return new ICallback<Boolean, Object>() {

        @Override
        public Boolean call(Object arg) {
            PyUnitView view = PyUnitView.getView();
            PyUnitTestRun currentTestRun = view.getCurrentTestRun();
            if (currentTestRun == null) {
                if (arg == THROW_ERROR) {
                    throw new AssertionError("currentTestRun == null");
                }
                return false;
            }
            if (!currentTestRun.getFinished()) {
                if (arg == THROW_ERROR) {
                    throw new AssertionError("!currentTestRun.getFinished()");
                }
                return false;
            }
            Tree tree = view.getTree();
            if (tree.getItemCount() != methodsAppearingInTree) {
                if (arg == THROW_ERROR) {
                    throw new AssertionError("tree.getItemCount() " + tree.getItemCount() + "!= methodsRun " + methodsAppearingInTree);
                }
                return false;
            }
            CounterPanel counterPanel = view.getCounterPanel();
            if (!counterPanel.fNumberOfErrors.getText().equals("1")) {
                if (arg == THROW_ERROR) {
                    throw new AssertionError("!counterPanel.fNumberOfErrors.getText().equals(\"1\")");
                }
                return false;
            }
            if (!counterPanel.fNumberOfFailures.getText().equals("1")) {
                if (arg == THROW_ERROR) {
                    throw new AssertionError("!counterPanel.fNumberOfFailures.getText().equals(\"1\")");
                }
                return false;
            }
            HistoryAction historyAction = (HistoryAction) getPyUnitViewAction(view, HistoryAction.class);
            HistoryAction.HistoryMenuCreator menuCreator = (HistoryMenuCreator) historyAction.getMenuCreator();
            final List<SetCurrentRunAction> actions = new ArrayList<SetCurrentRunAction>();
            final List<ClearTerminatedAction> terminatedActions = new ArrayList<ClearTerminatedAction>();
            IActionsMenu actionsMenu = new IActionsMenu() {

                @Override
                public void add(IAction action) {
                    if (action instanceof SetCurrentRunAction) {
                        actions.add((SetCurrentRunAction) action);
                    } else if (action instanceof ClearTerminatedAction) {
                        terminatedActions.add((ClearTerminatedAction) action);
                    }
                }
            };
            menuCreator.fillMenuManager(actionsMenu);
            if (historySize + 1 != actions.size()) {
                // +1 to count for the current!
                if (arg == THROW_ERROR) {
                    throw new AssertionError("historySize + 1 != actions.size()");
                }
                return false;
            }
            return true;
        }
    };
}
Also used : IAction(org.eclipse.jface.action.IAction) HistoryMenuCreator(org.python.pydev.debug.pyunit.HistoryAction.HistoryMenuCreator) ArrayList(java.util.ArrayList) IActionsMenu(org.python.pydev.debug.pyunit.HistoryAction.IActionsMenu) HistoryMenuCreator(org.python.pydev.debug.pyunit.HistoryAction.HistoryMenuCreator) ICallback(org.python.pydev.shared_core.callbacks.ICallback) Tree(org.eclipse.swt.widgets.Tree)

Aggregations

ICallback (org.python.pydev.shared_core.callbacks.ICallback)13 File (java.io.File)6 IDocument (org.eclipse.jface.text.IDocument)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 CoreException (org.eclipse.core.runtime.CoreException)3 IPath (org.eclipse.core.runtime.IPath)3 Path (org.eclipse.core.runtime.Path)3 MisconfigurationException (org.python.pydev.core.MisconfigurationException)3 InputStream (java.io.InputStream)2 List (java.util.List)2 Map (java.util.Map)2 IContainer (org.eclipse.core.resources.IContainer)2 IFile (org.eclipse.core.resources.IFile)2 IProject (org.eclipse.core.resources.IProject)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 Document (org.eclipse.jface.text.Document)2 IPythonNature (org.python.pydev.core.IPythonNature)2 PythonNature (org.python.pydev.plugin.nature.PythonNature)2 InterpreterResponse (org.python.pydev.shared_interactive_console.console.InterpreterResponse)2