Search in sources :

Example 16 with IPythonNature

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

the class AdditionalInfoIntegrityChecker method onCreateActions.

@Override
public void onCreateActions(ListResourceBundle resources, final BaseEditor baseEditor, IProgressMonitor monitor) {
    IPyEdit edit = (IPyEdit) baseEditor;
    edit.addOfflineActionListener("--internal-test-modules", new Action() {

        @Override
        public void run() {
            List<IPythonNature> allPythonNatures = PythonNature.getAllPythonNatures();
            StringBuffer buf = new StringBuffer();
            try {
                for (IPythonNature nature : allPythonNatures) {
                    buf.append(checkIntegrity(nature, new NullProgressMonitor(), true));
                }
            } catch (MisconfigurationException e) {
                buf.append(e.getMessage());
            }
            PyDialogHelpers.showString(buf.toString());
        }
    }, "Used just for testing (do not use).", true);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) Action(org.eclipse.jface.action.Action) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPyEdit(org.python.pydev.core.IPyEdit) IPythonNature(org.python.pydev.core.IPythonNature) ArrayList(java.util.ArrayList) List(java.util.List)

Example 17 with IPythonNature

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

the class InfoFactory method createElement.

public AdditionalInfoAndIInfo createElement(IMemento memento) {
    String[] attributeKeys = null;
    try {
        attributeKeys = memento.getAttributeKeys();
        HashSet<String> keys = new HashSet<String>(Arrays.asList(attributeKeys));
        if (!keys.contains(TAG_NAME) || !keys.contains(TAG_MODULE_NAME) || !keys.contains(TAG_PATH) || !keys.contains(TAG_TYPE) || !keys.contains(TAG_FILE) || !keys.contains(TAG_LINE) || !keys.contains(TAG_COL)) {
            return null;
        }
        final String name = memento.getString(TAG_NAME);
        final String moduleName = memento.getString(TAG_MODULE_NAME);
        final String path = memento.getString(TAG_PATH);
        final String file = memento.getString(TAG_FILE);
        final int line = memento.getInteger(TAG_LINE);
        final int col = memento.getInteger(TAG_COL);
        final int type = memento.getInteger(TAG_TYPE);
        String infoName = null;
        String infoModule = null;
        String infoPath = null;
        if (name != null && name.length() > 0) {
            infoName = name;
        }
        if (moduleName != null && moduleName.length() > 0) {
            infoModule = moduleName;
        }
        if (path != null && path.length() > 0) {
            infoPath = path;
        }
        String projectName = null;
        if (keys.contains(TAG_PROJECT_NAME)) {
            projectName = memento.getString(TAG_PROJECT_NAME);
        }
        IPythonNature nature = null;
        if (projectName != null) {
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            if (project != null) {
                nature = PythonNature.getPythonNature(project);
            }
        }
        AbstractInfo info;
        if (type == IInfo.ATTRIBUTE_WITH_IMPORT_TYPE) {
            info = new AttrInfo(infoName, infoModule, infoPath, nature, file, line, col);
        } else if (type == IInfo.CLASS_WITH_IMPORT_TYPE) {
            info = new ClassInfo(infoName, infoModule, infoPath, nature, file, line, col);
        } else if (type == IInfo.METHOD_WITH_IMPORT_TYPE) {
            info = new FuncInfo(infoName, infoModule, infoPath, nature, file, line, col);
        } else if (type == IInfo.NAME_WITH_IMPORT_TYPE) {
            info = new NameInfo(infoName, infoModule, infoPath, nature, file, line, col);
        } else if (type == IInfo.MOD_IMPORT_TYPE) {
            info = new ModInfo(infoModule, nature, file, line, col);
        } else {
            throw new AssertionError("Cannot restore type: " + type);
        }
        IInterpreterManager manager = null;
        if (projectName != null) {
            if (nature != null) {
                AbstractAdditionalDependencyInfo additionalInfo;
                try {
                    additionalInfo = AdditionalProjectInterpreterInfo.getAdditionalInfoForProject(nature);
                } catch (Exception e) {
                    // don't even report the error (this could happen if a saved option doesn't exist anymore)
                    return null;
                }
                return new AdditionalInfoAndIInfo(additionalInfo, info);
            }
        } else if (keys.contains(TAG_MANAGER_INTERPRETER_TYPE) && keys.contains(TAG_MANAGER_INTERPRETER)) {
            Integer interpreterType = memento.getInteger(TAG_MANAGER_INTERPRETER_TYPE);
            if (interpreterType != null) {
                switch(interpreterType) {
                    case IInterpreterManager.INTERPRETER_TYPE_PYTHON:
                        manager = InterpreterManagersAPI.getPythonInterpreterManager();
                        break;
                    case IInterpreterManager.INTERPRETER_TYPE_JYTHON:
                        manager = InterpreterManagersAPI.getJythonInterpreterManager();
                        break;
                    case IInterpreterManager.INTERPRETER_TYPE_IRONPYTHON:
                        manager = InterpreterManagersAPI.getIronpythonInterpreterManager();
                        break;
                }
            }
        } else if (keys.contains(TAG_MANAGER_IS_PYTHON) && keys.contains(TAG_MANAGER_INTERPRETER)) {
            // Kept for backward compatibility
            Boolean isTagPython = memento.getBoolean(TAG_MANAGER_IS_PYTHON);
            if (isTagPython != null) {
                if (isTagPython) {
                    manager = InterpreterManagersAPI.getPythonInterpreterManager();
                } else {
                    manager = InterpreterManagersAPI.getJythonInterpreterManager();
                }
            }
        }
        // If it gets here, it MUST contain the TAG_MANAGER_INTERPRETER
        if (manager != null) {
            String interpreter = memento.getString(TAG_MANAGER_INTERPRETER);
            AbstractAdditionalTokensInfo additionalInfo;
            try {
                additionalInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(manager, interpreter);
            } catch (Exception e) {
                // don't even report the error (this could happen if a saved option doesn't exist anymore)
                return null;
            }
            if (additionalInfo != null) {
                return new AdditionalInfoAndIInfo(additionalInfo, info);
            }
        }
    } catch (Throwable e) {
        // Don't fail because we weren't able to restore some info, just log and return null (which clients should expect).
        Log.log(e);
        return null;
    }
    return null;
}
Also used : IPythonNature(org.python.pydev.core.IPythonNature) IInterpreterManager(org.python.pydev.core.IInterpreterManager) IProject(org.eclipse.core.resources.IProject) HashSet(java.util.HashSet)

Example 18 with IPythonNature

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

the class AnalysisParserObserver method parserChanged.

@Override
public void parserChanged(final ChangedParserInfoForObservers info) {
    if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) {
        System.out.println("AnalysisParserObserver: parserChanged");
    }
    final SimpleNode root = (SimpleNode) info.root;
    if (info.file == null) {
        return;
    }
    IFile fileAdapter = null;
    if (info.file instanceof IFile) {
        fileAdapter = (IFile) info.file;
    }
    if (fileAdapter == null) {
        fileAdapter = info.file.getAdapter(IFile.class);
        if (fileAdapter == null) {
            return;
        }
    }
    boolean force = false;
    boolean forceAnalyzeInThisThread = false;
    if (info.argsToReparse != null && info.argsToReparse.length > 0) {
        if (info.argsToReparse[0] instanceof Tuple) {
            Tuple t = (Tuple) info.argsToReparse[0];
            if (t.o1 instanceof String && t.o2 instanceof Boolean) {
                if (t.o1.equals(IMiscConstants.ANALYSIS_PARSER_OBSERVER_FORCE)) {
                    // if this message is passed, it will decide whether we will force the analysis or not
                    force = (Boolean) t.o2;
                }
                if (t.o1.equals(IMiscConstants.ANALYSIS_PARSER_OBSERVER_FORCE_IN_THIS_THREAD)) {
                    // if this message is passed, it will decide whether we will force the analysis or not
                    forceAnalyzeInThisThread = force = (Boolean) t.o2;
                }
            }
        }
    }
    // Note: whenever there's a successful reparse, analyze the files.
    // create the module
    final IPythonNature nature = PythonNature.getPythonNature(fileAdapter);
    if (nature == null) {
        return;
    }
    // don't analyze it if we're still not 'all set'
    if (!nature.isOkToUse()) {
        Job job = new AnalyzeLaterJob("Analyze later", info, root, fileAdapter, force, nature);
        job.schedule(100);
        return;
    }
    analyze(info, root, fileAdapter, force, nature, forceAnalyzeInThisThread);
}
Also used : IFile(org.eclipse.core.resources.IFile) IPythonNature(org.python.pydev.core.IPythonNature) Job(org.eclipse.core.runtime.jobs.Job) Tuple(org.python.pydev.shared_core.structure.Tuple) ISimpleNode(org.python.pydev.shared_core.model.ISimpleNode) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Example 19 with IPythonNature

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

the class PyNatureReindexer method onCreateActions.

@Override
public void onCreateActions(ListResourceBundle resources, BaseEditor baseEditor, IProgressMonitor monitor) {
    IPyEditOfflineActionListener edit = (IPyEditOfflineActionListener) baseEditor;
    edit.addOfflineActionListener("--reindex", new Action() {

        @Override
        public void run() {
            for (IPythonNature nature : PythonNature.getAllPythonNatures()) {
                nature.rebuildPath();
            }
        }
    }, "Rebuilds the internal structure for all Pydev projects.", true);
}
Also used : IPyEditOfflineActionListener(org.python.pydev.core.IPyEditOfflineActionListener) Action(org.eclipse.jface.action.Action) IPythonNature(org.python.pydev.core.IPythonNature)

Example 20 with IPythonNature

use of org.python.pydev.core.IPythonNature 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)

Aggregations

IPythonNature (org.python.pydev.core.IPythonNature)85 MisconfigurationException (org.python.pydev.core.MisconfigurationException)33 ArrayList (java.util.ArrayList)30 File (java.io.File)26 IProject (org.eclipse.core.resources.IProject)20 IFile (org.eclipse.core.resources.IFile)18 CoreException (org.eclipse.core.runtime.CoreException)17 Tuple (org.python.pydev.shared_core.structure.Tuple)14 IDocument (org.eclipse.jface.text.IDocument)12 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)12 ICodeCompletionASTManager (org.python.pydev.core.ICodeCompletionASTManager)11 IModule (org.python.pydev.core.IModule)10 TokensList (org.python.pydev.core.TokensList)10 HashSet (java.util.HashSet)9 List (java.util.List)9 BadLocationException (org.eclipse.jface.text.BadLocationException)9 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)9 SimpleNode (org.python.pydev.parser.jython.SimpleNode)9 PyEdit (org.python.pydev.editor.PyEdit)8 SystemPythonNature (org.python.pydev.plugin.nature.SystemPythonNature)8