Search in sources :

Example 26 with MisconfigurationException

use of org.python.pydev.core.MisconfigurationException 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 27 with MisconfigurationException

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

the class PreloadAdditionalInfoPyEditListener method onInputChanged.

@Override
public void onInputChanged(BaseEditor baseEditor, IEditorInput oldInput, IEditorInput input, IProgressMonitor monitor) {
    if (input != null) {
        IResource adapter = (IResource) input.getAdapter(IResource.class);
        if (adapter != null) {
            IProject project = adapter.getProject();
            final PythonNature nature = PythonNature.getPythonNature(project);
            if (nature != null) {
                Job job = new Job("Preload additional info") {

                    @Override
                    protected IStatus run(IProgressMonitor monitor) {
                        try {
                            AdditionalProjectInterpreterInfo.getAdditionalInfo(nature);
                        } catch (MisconfigurationException e) {
                            Log.log(e);
                        }
                        return Status.OK_STATUS;
                    }
                };
                job.setSystem(true);
                job.schedule(100);
            }
        }
    }
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) PythonNature(org.python.pydev.plugin.nature.PythonNature) MisconfigurationException(org.python.pydev.core.MisconfigurationException) Job(org.eclipse.core.runtime.jobs.Job) IResource(org.eclipse.core.resources.IResource) IProject(org.eclipse.core.resources.IProject)

Example 28 with MisconfigurationException

use of org.python.pydev.core.MisconfigurationException 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 29 with MisconfigurationException

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

the class PyRefactorAction method run.

/**
 * Actually executes this action.
 *
 * Checks preconditions... if
 */
@Override
public void run(final IAction action) {
    // Select from text editor
    // clear the cache from previous runs
    request = null;
    ps = PySelectionFromEditor.createPySelectionFromEditor(getTextEditor());
    RefactoringRequest req;
    try {
        req = getRefactoringRequest();
    } catch (MisconfigurationException e2) {
        Log.log(e2);
        return;
    }
    IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
    if (areRefactorPreconditionsOK(req, pyRefactoring) == false) {
        return;
    }
    UIJob job = new UIJob("Performing: " + this.getClass().getName()) {

        @Override
        public IStatus runInUIThread(final IProgressMonitor monitor) {
            try {
                Operation o = new Operation(action);
                o.execute(monitor);
            } catch (Exception e) {
                Log.log(e);
            }
            return Status.OK_STATUS;
        }
    };
    job.setSystem(true);
    job.schedule();
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) MisconfigurationException(org.python.pydev.core.MisconfigurationException) UIJob(org.eclipse.ui.progress.UIJob) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring) WorkspaceModifyOperation(org.eclipse.ui.actions.WorkspaceModifyOperation) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MisconfigurationException(org.python.pydev.core.MisconfigurationException)

Example 30 with MisconfigurationException

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

the class OverrideMethodCompletionProposal method applyOnDocument.

public int applyOnDocument(ITextViewer viewer, IDocument document, char trigger, int stateMask, int offset) {
    IGrammarVersionProvider versionProvider = null;
    IPyEdit edit = null;
    if (viewer instanceof IPySourceViewer) {
        IPySourceViewer pySourceViewer = (IPySourceViewer) viewer;
        versionProvider = edit = pySourceViewer.getEdit();
    } else {
        versionProvider = new IGrammarVersionProvider() {

            @Override
            public int getGrammarVersion() throws MisconfigurationException {
                return IGrammarVersionProvider.LATEST_GRAMMAR_PY3_VERSION;
            }

            @Override
            public AdditionalGrammarVersionsToCheck getAdditionalGrammarVersions() throws MisconfigurationException {
                return null;
            }
        };
    }
    String delimiter = PySelection.getDelimiter(document);
    PyAstFactory factory = new PyAstFactory(new AdapterPrefs(delimiter, versionProvider));
    // Note that the copy won't have a parent.
    stmtType overrideBody = factory.createOverrideBody(this.functionDef, parentClassName, currentClassName);
    FunctionDef functionDef = this.functionDef.createCopy(false);
    functionDef.body = new stmtType[] { overrideBody != null ? overrideBody : new Pass() };
    try {
        MakeAstValidForPrettyPrintingVisitor.makeValid(functionDef);
    } catch (Exception e) {
        Log.log(e);
    }
    IIndentPrefs indentPrefs;
    if (edit != null) {
        indentPrefs = edit.getIndentPrefs();
    } else {
        indentPrefs = DefaultIndentPrefs.get(null);
    }
    String printed = NodeUtils.printAst(indentPrefs, edit, functionDef, delimiter);
    PySelection ps = new PySelection(document, offset);
    try {
        String lineContentsToCursor = ps.getLineContentsToCursor();
        int defIndex = lineContentsToCursor.indexOf("def");
        int defOffset = ps.getLineOffset() + defIndex;
        printed = StringUtils.indentTo(printed, lineContentsToCursor.substring(0, defIndex), false);
        printed = StringUtils.rightTrim(printed);
        this.fLen += offset - defOffset;
        document.replace(defOffset, this.fLen, printed);
        return defOffset + printed.length();
    } catch (BadLocationException x) {
    // ignore
    }
    return -1;
}
Also used : IPySourceViewer(org.python.pydev.core.IPySourceViewer) IGrammarVersionProvider(org.python.pydev.core.IGrammarVersionProvider) MisconfigurationException(org.python.pydev.core.MisconfigurationException) org.python.pydev.parser.jython.ast.stmtType(org.python.pydev.parser.jython.ast.stmtType) IIndentPrefs(org.python.pydev.core.IIndentPrefs) IPyEdit(org.python.pydev.core.IPyEdit) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) BadLocationException(org.eclipse.jface.text.BadLocationException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) Point(org.eclipse.swt.graphics.Point) Pass(org.python.pydev.parser.jython.ast.Pass) AdapterPrefs(org.python.pydev.parser.jython.ast.factory.AdapterPrefs) PyAstFactory(org.python.pydev.parser.jython.ast.factory.PyAstFactory) PySelection(org.python.pydev.core.docutils.PySelection) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

MisconfigurationException (org.python.pydev.core.MisconfigurationException)99 IPythonNature (org.python.pydev.core.IPythonNature)28 ArrayList (java.util.ArrayList)23 File (java.io.File)21 CoreException (org.eclipse.core.runtime.CoreException)18 IOException (java.io.IOException)14 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)14 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)13 IDocument (org.eclipse.jface.text.IDocument)13 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)13 IInterpreterManager (org.python.pydev.core.IInterpreterManager)12 PythonNatureWithoutProjectException (org.python.pydev.core.PythonNatureWithoutProjectException)12 HashSet (java.util.HashSet)11 IModule (org.python.pydev.core.IModule)11 BadLocationException (org.eclipse.jface.text.BadLocationException)10 SimpleNode (org.python.pydev.parser.jython.SimpleNode)10 AbstractAdditionalDependencyInfo (com.python.pydev.analysis.additionalinfo.AbstractAdditionalDependencyInfo)9 IFile (org.eclipse.core.resources.IFile)9 IGrammarVersionProvider (org.python.pydev.core.IGrammarVersionProvider)9 TokensList (org.python.pydev.core.TokensList)9