Search in sources :

Example 1 with PythonNatureWithoutProjectException

use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.

the class AdditionalProjectInterpreterInfo method getAdditionalInfoAndNature.

public static List<Tuple<AbstractAdditionalTokensInfo, IPythonNature>> getAdditionalInfoAndNature(IPythonNature nature, boolean addSystemInfo, boolean addReferencingProjects, boolean addReferencedProjects) throws MisconfigurationException {
    List<Tuple<AbstractAdditionalTokensInfo, IPythonNature>> ret = new ArrayList<Tuple<AbstractAdditionalTokensInfo, IPythonNature>>();
    IProject project = nature.getProject();
    // get for the system info
    if (addSystemInfo) {
        AbstractAdditionalTokensInfo systemInfo;
        try {
            systemInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(InterpreterManagersAPI.getInterpreterManager(nature), nature.getProjectInterpreter().getExecutableOrJar());
        } catch (MisconfigurationException e) {
            throw e;
        } catch (PythonNatureWithoutProjectException e) {
            throw new RuntimeException(e);
        }
        ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(systemInfo, new SystemPythonNature(nature.getRelatedInterpreterManager())));
    }
    // get for the current project
    if (project != null) {
        AbstractAdditionalTokensInfo additionalInfoForProject = getAdditionalInfoForProject(nature);
        if (additionalInfoForProject != null) {
            ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, nature));
        }
        try {
            if (addReferencedProjects) {
                // get for the referenced projects
                Set<IProject> referencedProjects = ProjectModulesManager.getReferencedProjects(project);
                for (IProject refProject : referencedProjects) {
                    additionalInfoForProject = getAdditionalInfoForProject(PythonNature.getPythonNature(refProject));
                    if (additionalInfoForProject != null) {
                        ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, PythonNature.getPythonNature(refProject)));
                    }
                }
            }
            if (addReferencingProjects) {
                Set<IProject> referencingProjects = ProjectModulesManager.getReferencingProjects(project);
                for (IProject refProject : referencingProjects) {
                    additionalInfoForProject = getAdditionalInfoForProject(PythonNature.getPythonNature(refProject));
                    if (additionalInfoForProject != null) {
                        ret.add(new Tuple<AbstractAdditionalTokensInfo, IPythonNature>(additionalInfoForProject, PythonNature.getPythonNature(refProject)));
                    }
                }
            }
        } catch (Exception e) {
            Log.log(e);
        }
    }
    return ret;
}
Also used : MisconfigurationException(org.python.pydev.core.MisconfigurationException) ArrayList(java.util.ArrayList) IPythonNature(org.python.pydev.core.IPythonNature) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IProject(org.eclipse.core.resources.IProject) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) Tuple(org.python.pydev.shared_core.structure.Tuple)

Example 2 with PythonNatureWithoutProjectException

use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.

the class PythonNature method getVersionAndError.

@Override
public Tuple<String, String> getVersionAndError(boolean translateIfInterpreter) throws CoreException {
    if (project != null) {
        if (versionPropertyCache == null) {
            String storeVersion = getStore().getPropertyFromXml(getPythonProjectVersionQualifiedName());
            if (storeVersion == null) {
                // there is no such property set (let's set it to the default)
                // will set the versionPropertyCache too
                setVersion(getDefaultVersion(false), null);
            } else {
                // now, before returning and setting in the cache, let's make sure it's a valid version.
                if (!IPythonNature.Versions.ALL_VERSIONS_ANY_FLAVOR.contains(storeVersion)) {
                    Log.log("The stored version is invalid (" + storeVersion + "). Setting default.");
                    // will set the versionPropertyCache too
                    setVersion(getDefaultVersion(false), null);
                } else {
                    // Ok, it's correct.
                    versionPropertyCache = storeVersion;
                }
            }
        }
    } else {
        String msg = "Trying to get version without project set. Returning default.";
        Log.log(msg);
        return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
    }
    if (versionPropertyCache == null) {
        String msg = "The cached version is null. Returning default.";
        Log.log(msg);
        return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
    } else if (!IPythonNature.Versions.ALL_VERSIONS_ANY_FLAVOR.contains(versionPropertyCache)) {
        String msg = "The cached version (" + versionPropertyCache + ") is invalid. Returning default.";
        Log.log(msg);
        return new Tuple<String, String>(getDefaultVersion(translateIfInterpreter), msg);
    }
    if (translateIfInterpreter && versionPropertyCache.endsWith(IPythonNature.Versions.INTERPRETER_VERSION)) {
        Tuple<String, String> split = StringUtils.splitOnFirst(versionPropertyCache, ' ');
        String errorMessage;
        try {
            IInterpreterInfo info = this.getProjectInterpreter();
            String version = info.getVersion();
            if (version != null) {
                return new Tuple<String, String>(IPythonNature.Versions.convertToInternalVersion(new FastStringBuffer(split.o1, 6).append(' '), version), null);
            } else {
                errorMessage = "Unable to get version from interpreter info: " + info.getNameForUI() + " - " + info.getExecutableOrJar();
                Log.log(errorMessage);
            }
        } catch (MisconfigurationException | PythonNatureWithoutProjectException e) {
            Log.log(e);
            errorMessage = e.getMessage();
        }
        return new Tuple<String, String>(split.o1 + " " + "2.7", errorMessage + " (in project: " + getProject() + ")");
    }
    return new Tuple<String, String>(versionPropertyCache, null);
}
Also used : FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) MisconfigurationException(org.python.pydev.core.MisconfigurationException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) Tuple(org.python.pydev.shared_core.structure.Tuple)

Example 3 with PythonNatureWithoutProjectException

use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.

the class PyOrganizeImports method organizeImports.

@SuppressWarnings("unchecked")
private void organizeImports(PyEdit edit, final IDocument doc, IFile f, PySelection ps) throws MisconfigurationException, PythonNatureWithoutProjectException {
    DocumentRewriteSession session = null;
    String endLineDelim = ps.getEndLineDelim();
    List<IOrganizeImports> participants = null;
    if (f == null && !automatic) {
        // organizing single file ...
        // let's see if someone wants to make a better implementation in another plugin...
        participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_ORGANIZE_IMPORTS);
        for (IOrganizeImports organizeImports : participants) {
            if (!organizeImports.beforePerformArrangeImports(ps, edit, f)) {
                return;
            }
        }
    }
    String fileContents = doc.get();
    if (fileContents.contains("isort:skip_file") || fileContents.length() == 0) {
        return;
    }
    IAdaptable projectAdaptable = edit != null ? edit : f;
    String indentStr = edit != null ? edit.getIndentPrefs().getIndentationString() : DefaultIndentPrefs.get(f).getIndentationString();
    session = TextSelectionUtils.startWrite(doc);
    try {
        // Important: the remove and later update have to be done in the same session (since the remove
        // will just remove some names and he actual perform will remove the remaining if needed).
        // i.e.: from a import b <-- b will be removed by the OrganizeImportsFixesUnused and the
        // from a will be removed in the performArrangeImports later on.
        boolean removeUnusedImports = false;
        if (!automatic) {
            // Only go through the removal of unused imports if it's manually activated (not on automatic mode).
            removeUnusedImports = ImportsPreferencesPage.getDeleteUnusedImports(projectAdaptable);
            if (removeUnusedImports) {
                new OrganizeImportsFixesUnused().beforePerformArrangeImports(ps, edit, f);
            }
        }
        Set<String> knownThirdParty = new HashSet<String>();
        // isort itself already has a reasonable stdLib, so, don't do our own.
        String importEngine = ImportsPreferencesPage.getImportEngine(projectAdaptable);
        if (edit != null) {
            IPythonNature pythonNature = edit.getPythonNature();
            if (pythonNature != null) {
                IInterpreterInfo projectInterpreter = pythonNature.getProjectInterpreter();
                ISystemModulesManager modulesManager = projectInterpreter.getModulesManager();
                ModulesKey[] onlyDirectModules = modulesManager.getOnlyDirectModules();
                Set<String> stdLib = new HashSet<>();
                for (ModulesKey modulesKey : onlyDirectModules) {
                    if (modulesKey.file == null) {
                        int i = modulesKey.name.indexOf('.');
                        String name;
                        if (i < 0) {
                            name = modulesKey.name;
                        } else {
                            name = modulesKey.name.substring(0, i);
                        }
                        // Add all names to std lib
                        stdLib.add(name);
                    }
                }
                for (ModulesKey modulesKey : onlyDirectModules) {
                    int i = modulesKey.name.indexOf('.');
                    String name;
                    if (i < 0) {
                        name = modulesKey.name;
                    } else {
                        name = modulesKey.name.substring(0, i);
                    }
                    // Consider all in site-packages to be third party.
                    if (modulesKey.file != null && modulesKey.file.toString().contains("site-packages")) {
                        stdLib.remove(name);
                        knownThirdParty.add(name);
                    }
                }
            }
        }
        switch(importEngine) {
            case ImportsPreferencesPage.IMPORT_ENGINE_ISORT:
                if (fileContents.length() > 0) {
                    File targetFile = edit != null ? edit.getEditorFile() : null;
                    if (targetFile == null) {
                        if (f != null) {
                            IPath location = f.getLocation();
                            if (location != null) {
                                targetFile = location.toFile();
                            }
                        }
                    }
                    String isortResult = JythonModules.makeISort(fileContents, targetFile, knownThirdParty);
                    if (isortResult != null) {
                        try {
                            DocUtils.updateDocRangeWithContents(doc, fileContents, isortResult.toString());
                        } catch (Exception e) {
                            Log.log(StringUtils.format("Error trying to apply isort result. Curr doc:\n>>>%s\n<<<.\nNew doc:\\n>>>%s\\n<<<.", fileContents, isortResult.toString()), e);
                        }
                    }
                }
                break;
            case ImportsPreferencesPage.IMPORT_ENGINE_REGULAR_SORT:
                performArrangeImports(doc, removeUnusedImports, endLineDelim, indentStr, automatic, edit);
                break;
            default:
                // case ImportsPreferencesPage.IMPORT_ENGINE_PEP_8:
                if (f == null) {
                    f = edit.getIFile();
                }
                IProject p = f != null ? f.getProject() : null;
                pep8PerformArrangeImports(doc, removeUnusedImports, endLineDelim, p, indentStr, automatic, edit);
                break;
        }
        if (participants != null) {
            for (IOrganizeImports organizeImports : participants) {
                organizeImports.afterPerformArrangeImports(ps, edit);
            }
        }
    } finally {
        TextSelectionUtils.endWrite(doc, session);
    }
}
Also used : IAdaptable(org.eclipse.core.runtime.IAdaptable) IPath(org.eclipse.core.runtime.IPath) IPythonNature(org.python.pydev.core.IPythonNature) SyntaxErrorException(org.python.pydev.core.docutils.SyntaxErrorException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IProject(org.eclipse.core.resources.IProject) ISystemModulesManager(org.python.pydev.core.ISystemModulesManager) DocumentRewriteSession(org.eclipse.jface.text.DocumentRewriteSession) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) ModulesKey(org.python.pydev.core.ModulesKey) IFile(org.eclipse.core.resources.IFile) File(java.io.File) HashSet(java.util.HashSet)

Example 4 with PythonNatureWithoutProjectException

use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.

the class AbstractManageEnvEditorAction method run.

@Override
public void run() {
    try {
        final IPythonNature pythonNature = edit.getPythonNature();
        if (pythonNature == null) {
            PyDialogHelpers.openCritical("Unable to execute pip", "The related editor does not have an associated python nature.");
            return;
        }
        IInterpreterInfo projectInterpreter = pythonNature.getProjectInterpreter();
        if (projectInterpreter == null) {
            PyDialogHelpers.openCritical("Unable to execute pip", "The related editor does not have an associated interpreter.");
            return;
        }
        doRun(pythonNature, projectInterpreter);
    } catch (MisconfigurationException | PythonNatureWithoutProjectException e) {
        Log.log(e);
    }
}
Also used : IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException)

Example 5 with PythonNatureWithoutProjectException

use of org.python.pydev.core.PythonNatureWithoutProjectException in project Pydev by fabioz.

the class AbstractASTManager method getCompletionFromFuncDefReturn.

@Override
public TokensList getCompletionFromFuncDefReturn(ICompletionState state, IModule module, IDefinition definition, boolean considerYieldTheReturnType) throws CompletionRecursionException {
    TokensList ret = new TokensList();
    if (!(module instanceof SourceModule)) {
        return ret;
    }
    if (!(definition instanceof Definition)) {
        return ret;
    }
    Definition def = (Definition) definition;
    FunctionDef functionDef = (FunctionDef) def.ast;
    ITypeInfo type = NodeUtils.getReturnTypeFromFuncDefAST(functionDef);
    if (type != null) {
        ICompletionState copy = state.getCopy();
        copy.setActivationToken(type.getActTok());
        try (NoExceptionCloseable x = copy.pushLookingFor(LookingFor.LOOKING_FOR_INSTANCED_VARIABLE)) {
            stmtType[] body = functionDef.body;
            if (body.length > 0) {
                copy.setLine(body[0].beginLine - 1);
                copy.setCol(body[0].beginColumn - 1);
            }
            IModule definitionModule = def.module;
            state.checkDefinitionMemory(definitionModule, def);
            TokensList tks = this.getCompletionsForModule(definitionModule, copy);
            if (tks.notEmpty()) {
                // TODO: This is not ideal... ideally, we'd return this info along instead of setting
                // it in the token, but this may be hard as we have to touch LOTS of places for
                // this information to get to the needed place.
                tks.setGeneratorType(type);
                ret.addAll(tks);
                // Ok, resolved rtype!
                return ret;
            } else {
                // Try to deal with some token that's not imported
                List<IPyDevCompletionParticipant> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_COMPLETION);
                for (IPyDevCompletionParticipant participant : participants) {
                    TokensList collection = participant.getCompletionsForType(copy);
                    if (collection != null && collection.notEmpty()) {
                        ret.addAll(collection);
                        // Ok, resolved rtype!
                        return ret;
                    }
                }
            }
        }
    }
    List<Return> returns = ReturnVisitor.findReturns(functionDef);
    Stream<exprType> map = returns.stream().map(r -> r.value);
    if (considerYieldTheReturnType) {
        List<Yield> yields = YieldVisitor.findYields(functionDef);
        map = Stream.concat(map, yields.stream().map(yield -> yield.value));
    }
    for (Iterator<exprType> it = map.iterator(); it.hasNext(); ) {
        exprType value = it.next();
        if (value == null) {
            continue;
        }
        String act = NodeUtils.getFullRepresentationString(value);
        if (act == null) {
            // may happen if the return we're seeing is a return without anything (keep on going to check other returns)
            continue;
        }
        ITokenCompletionRequest request = new TokenCompletionRequest(act, def.module, state.getNature(), "", def.line - 1, def.col - 1);
        TokensList tokensList = new TokensList();
        ICompletionState copy = state.getCopy();
        copy.setActivationToken(act);
        copy.setLine(value.beginLine - 1);
        copy.setCol(value.beginColumn - 1);
        LookingFor lookingFor = null;
        if (value instanceof Call) {
            lookingFor = ICompletionState.LookingFor.LOOKING_FOR_INSTANCED_VARIABLE;
        }
        try (NoExceptionCloseable x = state.pushLookingFor(lookingFor)) {
            IModule definitionModule = def.module;
            state.checkDefinitionMemory(definitionModule, def);
            try {
                PyCodeCompletion.doTokenCompletion(request, this, tokensList, act, copy);
            } catch (MisconfigurationException | IOException | CoreException | PythonNatureWithoutProjectException e) {
                throw new RuntimeException(e);
            }
            if (lookingFor != null) {
                tokensList.setLookingFor(lookingFor);
            }
            ret.addAll(tokensList);
        }
    }
    return ret;
}
Also used : IPyDevCompletionParticipant(org.python.pydev.ast.codecompletion.IPyDevCompletionParticipant) org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) TokenCompletionRequest(org.python.pydev.ast.codecompletion.TokenCompletionRequest) ITokenCompletionRequest(org.python.pydev.core.ITokenCompletionRequest) IModule(org.python.pydev.core.IModule) MisconfigurationException(org.python.pydev.core.MisconfigurationException) LookingFor(org.python.pydev.core.ICompletionState.LookingFor) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) NoExceptionCloseable(org.python.pydev.core.NoExceptionCloseable) ICompletionState(org.python.pydev.core.ICompletionState) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) ITokenCompletionRequest(org.python.pydev.core.ITokenCompletionRequest) TokensList(org.python.pydev.core.TokensList) SourceModule(org.python.pydev.ast.codecompletion.revisited.modules.SourceModule) Call(org.python.pydev.parser.jython.ast.Call) Return(org.python.pydev.parser.jython.ast.Return) org.python.pydev.parser.jython.ast.stmtType(org.python.pydev.parser.jython.ast.stmtType) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) PyRefactoringFindDefinition(org.python.pydev.ast.refactoring.PyRefactoringFindDefinition) AssignDefinition(org.python.pydev.ast.codecompletion.revisited.visitors.AssignDefinition) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) ITypeInfo(org.python.pydev.core.ITypeInfo) Yield(org.python.pydev.parser.jython.ast.Yield)

Aggregations

PythonNatureWithoutProjectException (org.python.pydev.core.PythonNatureWithoutProjectException)10 MisconfigurationException (org.python.pydev.core.MisconfigurationException)8 CoreException (org.eclipse.core.runtime.CoreException)5 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)5 IProject (org.eclipse.core.resources.IProject)4 IPythonNature (org.python.pydev.core.IPythonNature)4 File (java.io.File)3 ArrayList (java.util.ArrayList)3 Tuple (org.python.pydev.shared_core.structure.Tuple)3 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 IFile (org.eclipse.core.resources.IFile)2 IPath (org.eclipse.core.runtime.IPath)2 TokensList (org.python.pydev.core.TokensList)2 ExternalAnalizerProcessWatchDoc (com.python.pydev.analysis.external.ExternalAnalizerProcessWatchDoc)1 List (java.util.List)1 StringTokenizer (java.util.StringTokenizer)1 IAdaptable (org.eclipse.core.runtime.IAdaptable)1 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1