Search in sources :

Example 1 with AbstractRunner

use of org.python.pydev.ast.runners.UniversalRunner.AbstractRunner in project Pydev by fabioz.

the class Py2To3 method confirmRun.

@Override
protected boolean confirmRun() {
    clearRunInput();
    PythonNature nature = null;
    for (IResource c : selectedResources) {
        PythonNature n2 = PythonNature.getPythonNature(c);
        if (n2 != null) {
            if (nature == null) {
                nature = n2;
            } else {
                if (n2 != nature) {
                    MessageBox message = new MessageBox(EditorUtils.getShell(), SWT.OK | SWT.ICON_ERROR);
                    message.setText("Multiple python natures");
                    message.setMessage("This action can only be applied in one project at a time.");
                    message.open();
                    return false;
                }
            }
        }
    }
    if (nature == null) {
        MessageBox message = new MessageBox(EditorUtils.getShell(), SWT.OK | SWT.ICON_ERROR);
        message.setText("No nature found");
        message.setMessage("This action can only be applied in a project that is configured as a Pydev project.");
        message.open();
        return false;
    }
    AbstractRunner runner = UniversalRunner.getRunner(nature);
    Tuple<String, String> tup = runner.runCodeAndGetOutput(RUN_2_TO_3_CODE, new String[] { "--help" }, null, new NullProgressMonitor());
    if (tup.o1.indexOf("ImportError") != -1 || tup.o2.indexOf("ImportError") != -1) {
        MessageBox message = new MessageBox(EditorUtils.getShell(), SWT.OK | SWT.ICON_ERROR);
        message.setText("Unable to run 2to3");
        message.setMessage("Unable to run 2to3. Details: \n" + tup.o1 + "\n" + tup.o2 + "\n\nNotes: check if lib2to3 is properly installed in your Python install.");
        message.open();
        return false;
    }
    String msg = "Please enter the parameters to be passed for 2to3.py\n\n" + tup.o1 + "\n\n" + "E.g.: \n" + "Leave empty for preview\n" + "-w to apply with backup\n" + "-w -n to apply without backup.";
    if (tup.o2.length() > 0) {
        msg += "\n";
        msg += tup.o2;
    }
    final List<String> splitInLines = StringUtils.splitInLines(msg);
    int max = 10;
    for (String string : splitInLines) {
        max = Math.max(string.length(), max);
    }
    final int maxChars = max;
    InputDialogWithLongMessage d = new InputDialogWithLongMessage(EditorUtils.getShell(), "Parameters for 2to3.py", msg, "", null) {

        int averageCharWidth;

        int height;

        @Override
        protected boolean isResizable() {
            return true;
        }

        @Override
        protected String getOkButtonLabel() {
            return "Run with specified parameters";
        }

        @Override
        protected Control createDialogArea(Composite parent) {
            try {
                FontData labelFontData = FontUtils.getFontData(IFontUsage.DIALOG, false);
                Display display = parent.getDisplay();
                Font font = new Font(display, labelFontData);
                parent.setFont(font);
                GC gc = new GC(display);
                gc.setFont(font);
                FontMetrics fontMetrics = gc.getFontMetrics();
                averageCharWidth = fontMetrics.getAverageCharWidth();
                height = fontMetrics.getHeight();
                gc.dispose();
            } catch (Throwable e) {
            // ignore
            }
            return super.createDialogArea(parent);
        }

        @Override
        protected Point getInitialSize() {
            Point result = super.getInitialSize();
            // Check if we were able to get proper values before changing it.
            if (averageCharWidth > 0 && maxChars > 0) {
                result.x = (int) (averageCharWidth * maxChars * 1.15);
            }
            if (height > 0 && splitInLines.size() > 0) {
                // put some lines extra (we need the input line too)
                result.y = Math.max(height * (int) (splitInLines.size() * 1.5), result.y);
            }
            return result;
        }
    };
    int retCode = d.open();
    if (retCode != InputDialog.OK) {
        return false;
    }
    MessageConsole console = MessageConsoles.getConsole("2To3", UIConstants.PY_INTERPRETER_ICON);
    console.clearConsole();
    parameters = StringUtils.split(d.getValue(), " ");
    natureUsed = nature;
    return true;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) MessageConsole(org.eclipse.ui.console.MessageConsole) PythonNature(org.python.pydev.plugin.nature.PythonNature) Composite(org.eclipse.swt.widgets.Composite) InputDialogWithLongMessage(org.python.pydev.shared_ui.dialogs.InputDialogWithLongMessage) FontData(org.eclipse.swt.graphics.FontData) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) Font(org.eclipse.swt.graphics.Font) MessageBox(org.eclipse.swt.widgets.MessageBox) AbstractRunner(org.python.pydev.ast.runners.UniversalRunner.AbstractRunner) FontMetrics(org.eclipse.swt.graphics.FontMetrics) GC(org.eclipse.swt.graphics.GC) IResource(org.eclipse.core.resources.IResource) Display(org.eclipse.swt.widgets.Display)

Example 2 with AbstractRunner

use of org.python.pydev.ast.runners.UniversalRunner.AbstractRunner in project Pydev by fabioz.

the class Py2To3 method doActionOnResource.

@Override
protected int doActionOnResource(IResource next, IProgressMonitor monitor) {
    this.refresh = new ArrayList<IContainer>();
    AbstractRunner runner = UniversalRunner.getRunner(natureUsed);
    if (next instanceof IContainer) {
        this.refresh.add((IContainer) next);
    } else {
        this.refresh.add(next.getParent());
    }
    String dir = next.getLocation().toOSString();
    File workingDir = new File(dir);
    if (!workingDir.exists()) {
        Log.log("Received file that does not exist for 2to3: " + workingDir);
        return 0;
    }
    if (!workingDir.isDirectory()) {
        workingDir = workingDir.getParentFile();
        if (!workingDir.isDirectory()) {
            Log.log("Unable to find working dir for 2to3. Found invalid: " + workingDir);
            return 0;
        }
    }
    ArrayList<String> parametersWithResource = new ArrayList<String>(parameters);
    parametersWithResource.add(0, dir);
    Tuple<String, String> tup = runner.runCodeAndGetOutput(RUN_2_TO_3_CODE, parametersWithResource.toArray(new String[0]), workingDir, monitor);
    IOConsoleOutputStream out = MessageConsoles.getConsoleOutputStream("2To3", UIConstants.PY_INTERPRETER_ICON);
    try {
        out.write(tup.o1);
        out.write("\n");
        out.write(tup.o2);
    } catch (IOException e) {
        Log.log(e);
    }
    return 1;
}
Also used : AbstractRunner(org.python.pydev.ast.runners.UniversalRunner.AbstractRunner) IOConsoleOutputStream(org.eclipse.ui.console.IOConsoleOutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IContainer(org.eclipse.core.resources.IContainer) File(java.io.File)

Example 3 with AbstractRunner

use of org.python.pydev.ast.runners.UniversalRunner.AbstractRunner in project Pydev by fabioz.

the class ProcessWindow method createProcess.

/**
 * @return the created process and a string representation of the command line.
 */
public Tuple<Process, String> createProcess(String[] arguments) {
    AbstractRunner universalRunner = UniversalRunner.getRunner(pythonPathNature.getNature());
    Tuple<Process, String> run = universalRunner.createProcess(targetExecutable.getAbsolutePath(), arguments, workingDir, new NullProgressMonitor());
    return run;
}
Also used : AbstractRunner(org.python.pydev.ast.runners.UniversalRunner.AbstractRunner) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor)

Example 4 with AbstractRunner

use of org.python.pydev.ast.runners.UniversalRunner.AbstractRunner in project Pydev by fabioz.

the class PythonUniversalRunnerTest method testUniversalRunnerWithJython.

public void testUniversalRunnerWithJython() throws Exception {
    AbstractRunner runner = UniversalRunner.getRunner(nature);
    assertEquals(nature.getInterpreterType(), IPythonNature.INTERPRETER_TYPE_PYTHON);
    Tuple<String, String> output = runner.runCodeAndGetOutput("import sys\nprint 'test'\nprint >> sys.stderr, 'err'", null, null, new NullProgressMonitor());
    assertEquals("test", output.o1.trim());
    assertEquals("err", output.o2.trim());
    Tuple<Process, String> createProcess = runner.createProcess(TestDependent.TEST_PYSRC_TESTING_LOC + "universal_runner_test.py", null, null, new NullProgressMonitor());
    output = SimpleRunner.getProcessOutput(createProcess.o1, "", new NullProgressMonitor(), "utf-8");
    assertEquals("stdout", output.o1.trim());
    assertEquals("stderr", output.o2.trim());
}
Also used : AbstractRunner(org.python.pydev.ast.runners.UniversalRunner.AbstractRunner) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor)

Example 5 with AbstractRunner

use of org.python.pydev.ast.runners.UniversalRunner.AbstractRunner in project Pydev by fabioz.

the class PyCoverage method refreshCoverageInfo.

/**
 * This method contacts the python server so that we get the information on the files that are below the directory passed as a parameter
 * and stores the information needed on the cache.
 *
 * @param file
 *            should be the root folder from where we want cache info.
 */
public void refreshCoverageInfo(IContainer container, IProgressMonitor monitor) throws CoverageException {
    int exitValue = 0;
    String stdOut = "";
    String stdErr = "";
    cache.clear();
    if (container == null) {
        return;
    }
    try {
        if (!container.exists()) {
            throw new RuntimeException("The directory passed: " + container + " no longer exists.");
        }
        File file = container.getLocation().toFile();
        PyFileListing pyFilesBelow = new PyFileListing();
        if (file.exists()) {
            pyFilesBelow = PyFileListing.getPyFilesBelow(file, monitor, true);
        }
        if (pyFilesBelow.getFoundPyFileInfos().size() == 0) {
            // no files
            return;
        }
        // add the folders to the cache
        boolean added = false;
        for (Iterator<File> it = pyFilesBelow.getFoundFolders().iterator(); it.hasNext(); ) {
            File f = it.next();
            if (!added) {
                cache.addFolder(f);
                added = true;
            } else {
                cache.addFolder(f, f.getParentFile());
            }
        }
        PythonNature nature = PythonNature.getPythonNature(container);
        if (nature == null) {
            throw new RuntimeException("The directory passed: " + container + " does not have an associated nature.");
        }
        AbstractRunner runner = UniversalRunner.getRunner(nature);
        // First, combine the results of the many runs we may have.
        Tuple<String, String> output = runner.runScriptAndGetOutput(PythonRunnerConfig.getCoverageScript(), new String[] { "combine", "--append" }, getCoverageDirLocation(), monitor);
        if (output.o1 != null && output.o1.length() > 0) {
            Log.logInfo(output.o1);
        }
        if (output.o2 != null && output.o2.length() > 0) {
            if (output.o2.startsWith("Coverage.py warning:")) {
                Log.logInfo(output.o2);
            } else {
                Log.log(output.o2);
            }
        }
        // we have to make a process to execute the script. it should look
        // like:
        // coverage.py -r [-m] FILE1 FILE2 ...
        // Report on the statement coverage for the given files. With the -m
        // option, show line numbers of the statements that weren't
        // executed.
        // python coverage.py -r -m files....
        monitor.setTaskName("Starting shell to get info...");
        File coverageDirLocation = getCoverageDirLocation();
        File coverageXmlLocation = new File(coverageDirLocation, "coverage.xml");
        if (coverageXmlLocation.exists()) {
            coverageXmlLocation.delete();
        }
        monitor.worked(1);
        Process p = null;
        try {
            // Will create the coverage.xml file for us to process later on.
            Tuple<Process, String> tup = runner.createProcess(PythonRunnerConfig.getCoverageScript(), new String[] { "--pydev-analyze" }, coverageDirLocation, monitor);
            p = tup.o1;
            String files = "";
            for (Iterator<PyFileInfo> iter = pyFilesBelow.getFoundPyFileInfos().iterator(); iter.hasNext(); ) {
                String fStr = iter.next().getFile().toString();
                files += fStr + "|";
            }
            files += "\r";
            monitor.setTaskName("Writing to shell...");
            // No need to synchronize as we'll waitFor() the process before getting the contents.
            ThreadStreamReader inputStream = new ThreadStreamReader(p.getInputStream(), false);
            inputStream.start();
            ThreadStreamReader errorStream = new ThreadStreamReader(p.getErrorStream(), false);
            errorStream.start();
            monitor.worked(1);
            OutputStream outputStream = p.getOutputStream();
            outputStream.write(files.getBytes());
            outputStream.close();
            monitor.setTaskName("Waiting for process to finish...");
            monitor.worked(1);
            while (true) {
                try {
                    exitValue = p.exitValue();
                    // process finished
                    break;
                } catch (IllegalThreadStateException e) {
                // not finished
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                // ignore
                }
                monitor.worked(1);
                if (monitor.isCanceled()) {
                    try {
                        p.destroy();
                    } catch (Exception e) {
                        Log.log(e);
                    }
                    break;
                }
            }
            stdOut = inputStream.getAndClearContents().trim();
            stdErr = errorStream.getAndClearContents().trim();
            if (stdOut.length() > 0) {
                Log.log(stdOut);
            }
            if (stdErr.length() > 0) {
                Log.log(stdErr);
            }
            monitor.setTaskName("Getting coverage info...(please wait, this could take a while)");
            monitor.worked(1);
            if (!coverageXmlLocation.exists()) {
                Log.log("Expected file: " + coverageXmlLocation + " to be written to analyze coverage info.");
            } else {
                CoverageXmlInfo.analyze(cache, coverageXmlLocation);
            }
            monitor.setTaskName("Finished");
        } catch (Exception e) {
            if (p != null) {
                p.destroy();
            }
            Log.log(e);
        }
    } catch (Exception e1) {
        Log.log(e1);
        throw new RuntimeException(e1);
    }
    if (exitValue != 0) {
        FastStringBuffer buf = new FastStringBuffer("Error with coverage action (exit value: ", stdErr.length() + stdOut.length() + 40);
        buf.append(exitValue).append(").");
        if (stdOut.length() > 0) {
            buf.append("\nStandard outputt:\n");
            buf.append(stdOut);
        }
        if (stdErr.length() > 0) {
            buf.append("\nError output:\n");
            buf.append(stdErr);
        }
        throw new CoverageException(buf.toString());
    }
}
Also used : ThreadStreamReader(org.python.pydev.shared_core.io.ThreadStreamReader) PythonNature(org.python.pydev.plugin.nature.PythonNature) FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) PyFileListing(org.python.pydev.ast.listing_utils.PyFileListing) OutputStream(java.io.OutputStream) AbstractRunner(org.python.pydev.ast.runners.UniversalRunner.AbstractRunner) PyFileInfo(org.python.pydev.ast.listing_utils.PyFileListing.PyFileInfo) File(java.io.File)

Aggregations

AbstractRunner (org.python.pydev.ast.runners.UniversalRunner.AbstractRunner)9 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 File (java.io.File)3 PythonNature (org.python.pydev.plugin.nature.PythonNature)3 IContainer (org.eclipse.core.resources.IContainer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 IFile (org.eclipse.core.resources.IFile)1 IProject (org.eclipse.core.resources.IProject)1 IResource (org.eclipse.core.resources.IResource)1 CoreException (org.eclipse.core.runtime.CoreException)1 IPath (org.eclipse.core.runtime.IPath)1 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)1 Path (org.eclipse.core.runtime.Path)1 IDocument (org.eclipse.jface.text.IDocument)1