/**
   * This method will wait some time until the given nature is properly configured with the ast
   * manager.
   */
  protected void waitForNatureToBeRecreated(PythonNature nature) {
    // Let's give it some time to run the jobs that restore the nature
    long finishAt = System.currentTimeMillis() + 5000; // 5 secs is the max time

    Display display = Display.getCurrent();
    if (display == null) {
      display = Display.getDefault();
    }
    Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
      if (finishAt < System.currentTimeMillis()) {
        break;
      }
      if (nature != null) {
        if (nature.getAstManager() != null) {
          break;
        }
      }
    }

    assertTrue(nature != null);
    assertTrue(nature.getAstManager() != null);
  }
 private String checkValidSourceFolder(String text) throws CoreException {
   validatedSourceFolder = null;
   if (text == null || text.trim().length() == 0) {
     return "The source folder must be filled.";
   }
   IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
   IResource resource = root.findMember(new Path(text));
   if (resource == null) {
     return "The source folder was not found in the workspace.";
   }
   if (!(resource instanceof IContainer)) {
     return "The source folder was found in the workspace but is not a container.";
   }
   IProject project = resource.getProject();
   if (project == null) {
     return "Unable to find the project related to the source folder.";
   }
   IPythonPathNature nature = PythonNature.getPythonPathNature(project);
   if (nature == null) {
     return "The pydev nature is not configured on the project: " + project.getName();
   }
   String full = resource.getFullPath().toString();
   String[] srcPaths = PythonNature.getStrAsStrItems(nature.getProjectSourcePath(true));
   for (String str : srcPaths) {
     if (str.equals(full)) {
       validatedSourceFolder = (IContainer) resource;
       return null;
     }
   }
   return "The selected source folder is not recognized as a valid source folder.";
 }
 /**
  * @param f
  * @return
  * @throws CoreException
  */
 public String getSrcFolderFromFolder(IFolder f) throws CoreException {
   IPythonPathNature nature = PythonNature.getPythonPathNature(f.getProject());
   if (nature != null) {
     String[] srcPaths = PythonNature.getStrAsStrItems(nature.getProjectSourcePath(true));
     String relFolder = f.getFullPath().toString() + "/";
     for (String src : srcPaths) {
       if (relFolder.startsWith(src + "/")) {
         return src;
       }
     }
   }
   return null;
 }
Beispiel #4
0
 /** @return the natures that were created. */
 public static List<PythonNature> getInitializedPythonNatures() {
   ArrayList<PythonNature> ret = new ArrayList<PythonNature>();
   synchronized (createdNatures) {
     for (Iterator<WeakReference<PythonNature>> it = createdNatures.iterator(); it.hasNext(); ) {
       PythonNature pythonNature = it.next().get();
       if (pythonNature == null) {
         it.remove();
       } else if (pythonNature.getProject() != null) {
         ret.add(pythonNature);
       }
     }
   }
   return ret;
 }
Beispiel #5
0
  public static List<IPythonNature> getPythonNaturesRelatedTo(int relatedTo) {
    ArrayList<IPythonNature> ret = new ArrayList<IPythonNature>();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject[] projects = root.getProjects();
    for (IProject project : projects) {
      PythonNature nature = getPythonNature(project);
      try {
        if (nature != null) {
          if (nature.getInterpreterType() == relatedTo) {
            ret.add(nature);
          }
        }
      } catch (CoreException e) {
        throw new RuntimeException(e);
      }
    }

    return ret;
  }
Beispiel #6
0
 /**
  * @return an array with the vm arguments in the given configuration.
  * @throws CoreException
  */
 private String[] getVMArguments(ILaunchConfiguration configuration) throws CoreException {
   String args = configuration.getAttribute(Constants.ATTR_VM_ARGUMENTS, (String) null);
   if (args != null && args.trim().length() > 0) {
     String expanded =
         getStringSubstitution(PythonNature.getPythonNature(project))
             .performStringSubstitution(args);
     return parseStringIntoList(expanded);
   }
   return null;
 }
Beispiel #7
0
  protected void discoverDefaultVersion(final String projectType, final String projectInterpreter) {
    defaultVersion =
        DJANGO_14; // It should be discovered below, but if not found for some reason, this will be
                   // the default.

    SystemPythonNature nature;
    try {
      final int interpreterType = PythonNature.getInterpreterTypeFromVersion(projectType);
      IInterpreterManager interpreterManagerFromType =
          PydevPlugin.getInterpreterManagerFromType(interpreterType);
      IInterpreterInfo interpreterInfo;
      if (IPythonNature.DEFAULT_INTERPRETER.equals(projectInterpreter)) {
        interpreterInfo = interpreterManagerFromType.getDefaultInterpreterInfo(false);

      } else {
        interpreterInfo = interpreterManagerFromType.getInterpreterInfo(projectInterpreter, null);
      }
      nature = new SystemPythonNature(interpreterManagerFromType, interpreterInfo);
      AbstractRunner runner = UniversalRunner.getRunner(nature);

      Tuple<String, String> output =
          runner.runCodeAndGetOutput(
              GET_DJANGO_VERSION, new String[] {}, null, new NullProgressMonitor());

      String err = output.o2.trim();
      String out = output.o1.trim();
      if (err.length() > 0) {
        Log.log("Error attempting to determine Django version: " + err);

      } else {
        // System.out.println("Gotten version: "+out);
        if (out.startsWith("0.")) {
          setDefaultVersion(DjangoSettingsPage.DJANGO_11_OR_EARLIER);

        } else if (out.startsWith("1.")) {
          out = out.substring(2);
          if (out.startsWith("0") || out.startsWith("1")) {
            setDefaultVersion(DjangoSettingsPage.DJANGO_11_OR_EARLIER);

          } else if (out.startsWith("2") || out.startsWith("3")) {
            setDefaultVersion(DjangoSettingsPage.DJANGO_12_OR_13);

          } else {
            // Later version
            setDefaultVersion(DjangoSettingsPage.DJANGO_14);
          }
        }
      }

    } catch (Exception e) {
      Log.log("Unable to determine Django version.", e);
    }
  }
Beispiel #8
0
 public static IPythonNature addNature(IEditorInput element) {
   if (element instanceof FileEditorInput) {
     IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
     if (file != null) {
       try {
         return PythonNature.addNature(file.getProject(), null, null, null, null, null, null);
       } catch (CoreException e) {
         Log.log(e);
       }
     }
   }
   return null;
 }
Beispiel #9
0
 /**
  * Can be used to extract the pythonpath used from a given configuration.
  *
  * @param conf the configuration from where we want to get the pythonpath
  * @return a string with the pythonpath used (with | as a separator)
  * @throws CoreException
  * @throws InvalidRunException
  * @throws MisconfigurationException
  */
 public static String getPythonpathFromConfiguration(
     ILaunchConfiguration conf, IInterpreterManager manager)
     throws CoreException, InvalidRunException, MisconfigurationException {
   IProject p = getProjectFromConfiguration(conf);
   PythonNature pythonNature = PythonNature.getPythonNature(p);
   if (pythonNature == null) {
     throw new CoreException(
         PydevDebugPlugin.makeStatus(
             IStatus.ERROR, "Project should have a python nature: " + p.getName(), null));
   }
   IInterpreterInfo l = getInterpreterLocation(conf, pythonNature, manager);
   return SimpleRunner.makePythonPathEnvString(pythonNature, l, manager);
 }
  /**
   * Create a project with the structure:
   *
   * <p>/pydev_unit_test_project junit.jar <-- set in pythonpath /src <-- set in pythonpath /pack1
   * __init__.py /pack2 __init__.py mod1.py
   *
   * <p>/java_unit_test_project /src <-- set in classpath JavaDefault.java (default package)
   * /javamod1/JavaClass.java /javamod2/JavaClass.java
   *
   * <p>Note: the initialization of the structure will happen only once and will be re-used in all
   * the tests after it.
   */
  @Override
  protected void setUp() throws Exception {
    closeWelcomeView();

    String mod1Contents = "import java.lang.Class\njava.lang.Class";
    if (editor == null) {
      InterpreterInfo.configurePathsCallback =
          new ICallback<Boolean, Tuple<List<String>, List<String>>>() {
            public Boolean call(Tuple<List<String>, List<String>> arg) {
              return Boolean.TRUE;
            }
          };
      PydevPlugin.setJythonInterpreterManager(
          new JythonInterpreterManager(PydevPlugin.getDefault().getPluginPreferences()));
      PydevPlugin.setPythonInterpreterManager(
          new PythonInterpreterManager(PydevPlugin.getDefault().getPluginPreferences()));

      ProjectModulesManager.IN_TESTS = true;
      NullProgressMonitor monitor = new NullProgressMonitor();

      createJythonInterpreterManager(monitor);
      createPythonInterpreterManager(monitor);

      IProject project = createProject(monitor, "pydev_unit_test_project");
      IJavaProject javaProject =
          configureAsJavaProject(createProject(monitor, "java_unit_test_project"), monitor);
      setProjectReference(monitor, project, javaProject);

      createJunitJar(monitor, project);
      createGrinderJar(monitor, project);

      IFolder sourceFolder = createSourceFolder(monitor, project);

      initFile = createPackageStructure(sourceFolder, "pack1.pack2", monitor);

      mod1 = initFile.getParent().getFile(new Path("mod1.py"));

      // OK, structure created, now, let's open mod1.py with a PyEdit so that the tests can begin...

      // create the contents and open the editor
      mod1.create(new ByteArrayInputStream(mod1Contents.getBytes()), true, monitor);

      PythonNature nature = PythonNature.getPythonNature(project);

      waitForNatureToBeRecreated(nature);

      editor = (PyEdit) PyOpenEditor.doOpenEditor(mod1);
    } else {
      setFileContents(mod1Contents); // just make sure that the contents of mod1 are correct.
    }
  }
Beispiel #11
0
  /** Utility routine to remove a PythonNature from a project. */
  public static synchronized void removeNature(IProject project, IProgressMonitor monitor)
      throws CoreException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }

    PythonNature nature = PythonNature.getPythonNature(project);
    if (nature == null) {
      return;
    }

    try {
      // we have to set the nature store to stop listening changes to .pydevproject
      nature.pythonNatureStore.setProject(null);
    } catch (Exception e) {
      Log.log(e);
    }

    try {
      // we have to remove the project from the pythonpath nature too...
      nature.pythonPathNature.setProject(null, null);
    } catch (Exception e) {
      Log.log(e);
    }

    // notify listeners that the pythonpath nature is now empty for this project
    try {
      PythonNatureListenersManager.notifyPythonPathRebuilt(project, null);
    } catch (Exception e) {
      Log.log(e);
    }

    try {
      // actually remove the pydev configurations
      IResource member = project.findMember(".pydevproject");
      if (member != null) {
        member.delete(true, null);
      }
    } catch (CoreException e) {
      Log.log(e);
    }

    // and finally... remove the nature

    IProjectDescription description = project.getDescription();
    List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));
    natures.remove(PYTHON_NATURE_ID);
    description.setNatureIds(natures.toArray(new String[natures.size()]));
    project.setDescription(description, monitor);
  }
 @Override
 public boolean select(Viewer viewer, Object parentElement, Object element) {
   if (element instanceof IAdaptable) {
     IAdaptable adaptable = (IAdaptable) element;
     Object adapted = adaptable.getAdapter(IProject.class);
     if (adapted instanceof IProject) {
       IProject project = (IProject) adapted;
       if (!project.isOpen()) {
         return true; // As we don't know about the nature of closed projects, don't filter it out.
       }
       return PythonNature.getPythonNature(project) != null;
     }
   }
   return true;
 }
 /**
  * Creates a source folder and configures the project to use it and the junit.jar
  *
  * @param addNature if false, no nature will be initially added to the project (if true, the
  *     nature will be added)
  */
 protected IFolder createSourceFolder(
     IProgressMonitor monitor, IProject project, boolean addNature) throws CoreException {
   IFolder sourceFolder = project.getFolder(new Path("src"));
   if (!sourceFolder.exists()) {
     sourceFolder.create(true, true, monitor);
   }
   if (addNature) {
     PythonNature.addNature(
         project,
         monitor,
         PythonNature.JYTHON_VERSION_2_1,
         "/pydev_unit_test_project/src|/pydev_unit_test_project/junit.jar|/pydev_unit_test_project/grinder.jar",
         null,
         null,
         null);
   }
   return sourceFolder;
 }
Beispiel #14
0
 /** @return The nature to be used for this breakpoint or null if it cannot be determined. */
 private IPythonNature getPythonNature() {
   IMarker marker = getMarker();
   IPythonNature nature = PythonNature.getPythonNature(marker.getResource());
   if (nature == null) {
     try {
       String externalPath = (String) marker.getAttribute(PyBreakpoint.PY_BREAK_EXTERNAL_PATH_ID);
       if (externalPath != null) {
         Tuple<IPythonNature, String> infoForFile =
             PydevPlugin.getInfoForFile(new File(externalPath));
         if (infoForFile != null) {
           nature = infoForFile.o1;
         }
       }
     } catch (CoreException e) {
       throw new RuntimeException(e);
     }
   }
   return nature;
 }
Beispiel #15
0
  /** Actually remove the python nature from the project. */
  public void run(IAction action) {
    if (selectedProject == null) {
      return;
    }

    if (!MessageDialog.openConfirm(
        null,
        "Confirm Remove Pydev Nature",
        org.python.pydev.shared_core.string.StringUtils.format(
            "Are you sure that you want to remove the Pydev nature from %s?",
            selectedProject.getName()))) {
      return;
    }

    try {
      PythonNature.removeNature(selectedProject, null);
    } catch (Throwable e) {
      Log.log(e);
    }
  }
Beispiel #16
0
  /**
   * Gets it using all the natures that match a given interpreter manager.
   *
   * @throws MisconfigurationException
   */
  private static void getFromManagerAndRelatedNatures(
      String selectedText, IInterpreterManager useManager) {
    AbstractAdditionalTokensInfo additionalSystemInfo;
    try {
      additionalSystemInfo =
          AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(
              useManager, useManager.getDefaultInterpreterInfo().getExecutableOrJar());
    } catch (MisconfigurationException e) {
      MessageDialog.openError(
          getShell(),
          "Error",
          "Additional info is not available (default interpreter not configured).");
      handle(e);
      return;
    }

    List<AbstractAdditionalTokensInfo> additionalInfo =
        new ArrayList<AbstractAdditionalTokensInfo>();
    additionalInfo.add(additionalSystemInfo);

    List<IPythonNature> natures =
        PythonNature.getPythonNaturesRelatedTo(useManager.getInterpreterType());
    for (IPythonNature nature : natures) {
      AbstractAdditionalDependencyInfo info;
      try {
        info = AdditionalProjectInterpreterInfo.getAdditionalInfoForProject(nature);
        if (info != null) {
          additionalInfo.add(info);
        }
      } catch (MisconfigurationException e) {
        // just go on to the next nature if one is not properly configured.
        handle(e);
      }
    }
    doSelect(natures, additionalInfo, selectedText);
  }
Beispiel #17
0
  /*
   * (non-Javadoc)
   * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
   */
  public void initializeFrom(ILaunchConfiguration configuration) {

    try {
      String id = configuration.getType().getIdentifier();
      IInterpreterManager manager = null;
      if (Constants.ID_JYTHON_LAUNCH_CONFIGURATION_TYPE.equals(id)
          || Constants.ID_JYTHON_UNITTEST_LAUNCH_CONFIGURATION_TYPE.equals(id)) {
        manager = PydevPlugin.getJythonInterpreterManager();

      } else if (Constants.ID_IRONPYTHON_LAUNCH_CONFIGURATION_TYPE.equals(id)
          || Constants.ID_IRONPYTHON_UNITTEST_LAUNCH_CONFIGURATION_TYPE.equals(id)) {
        manager = PydevPlugin.getIronpythonInterpreterManager();

      } else if (Constants.ID_PYTHON_REGULAR_LAUNCH_CONFIGURATION_TYPE.equals(id)
          || Constants.ID_PYTHON_COVERAGE_LAUNCH_CONFIGURATION_TYPE.equals(id)
          || Constants.ID_PYTHON_UNITTEST_LAUNCH_CONFIGURATION_TYPE.equals(id)) {
        manager = PydevPlugin.getPythonInterpreterManager();
      } else {
        // Get from the project
        try {
          // could throw core exception if project does not exist.
          IProject project = PythonRunnerConfig.getProjectFromConfiguration(configuration);
          PythonNature nature = PythonNature.getPythonNature(project);
          if (nature != null) {
            manager = PydevPlugin.getInterpreterManager(nature);
          }
        } catch (Exception e) {
          Log.log(e);
        }

        if (manager == null) {
          Log.log("Could not recognize: '" + id + "' using default python interpreter manager.");
          manager = PydevPlugin.getPythonInterpreterManager();
        }
      }
      String pythonPath = PythonRunnerConfig.getPythonpathFromConfiguration(configuration, manager);

      fPythonPathList.removeAll();
      java.util.List<String> paths = SimpleRunner.splitPythonpath(pythonPath);
      for (String p : paths) {
        fPythonPathList.add(p);
      }
      setErrorMessage(null);
    } catch (Exception e) {
      // Exceptions here may have several reasons
      // - The interpreter is incorrectly configured
      // - The arguments use an unresolved variable.
      // In each case, the exception contains a meaningful message, that is displayed
      Log.log(e);

      String message = e.getMessage();
      if (message == null) {
        message = "null (see error log for the traceback).";
      }
      String errorMsg =
          org.python.pydev.shared_core.string.StringUtils.replaceNewLines(message, " ");

      fPythonPathList.removeAll();
      fPythonPathList.add(errorMsg);
      setErrorMessage(errorMsg);
    }
  }
Beispiel #18
0
  /**
   * Utility routine to add PythonNature to the project
   *
   * @param projectPythonpath: @see {@link IPythonPathNature#setProjectSourcePath(String)}
   */
  public static synchronized IPythonNature addNature(
      IProject project,
      IProgressMonitor monitor,
      String version,
      String projectPythonpath,
      String externalProjectPythonpath,
      String projectInterpreter,
      Map<String, String> variableSubstitution)
      throws CoreException {

    if (project == null || !project.isOpen()) {
      return null;
    }
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    if (projectInterpreter == null) {
      projectInterpreter = IPythonNature.DEFAULT_INTERPRETER;
    }

    IProjectDescription desc = project.getDescription();

    // only add the nature if it still hasn't been added.
    if (project.hasNature(PYTHON_NATURE_ID) == false) {

      String[] natures = desc.getNatureIds();
      String[] newNatures = new String[natures.length + 1];
      System.arraycopy(natures, 0, newNatures, 0, natures.length);
      newNatures[natures.length] = PYTHON_NATURE_ID;
      desc.setNatureIds(newNatures);
      project.setDescription(desc, monitor);
    } else {
      // Return if it already has the nature configured.
      IProjectNature n = getPythonNature(project);
      if (n instanceof IPythonNature) {
        return (IPythonNature) n;
      }
    }

    // add the builder. It is used for pylint, pychecker, code completion, etc.
    ICommand[] commands = desc.getBuildSpec();

    // now, add the builder if it still hasn't been added.
    if (hasBuilder(commands) == false && PyDevBuilderPrefPage.usePydevBuilders()) {

      ICommand command = desc.newCommand();
      command.setBuilderName(BUILDER_ID);
      ICommand[] newCommands = new ICommand[commands.length + 1];

      System.arraycopy(commands, 0, newCommands, 1, commands.length);
      newCommands[0] = command;
      desc.setBuildSpec(newCommands);
      project.setDescription(desc, monitor);
    }

    IProjectNature n = getPythonNature(project);
    if (n instanceof PythonNature) {
      PythonNature nature = (PythonNature) n;
      // call initialize always - let it do the control.
      nature.init(
          version,
          projectPythonpath,
          externalProjectPythonpath,
          monitor,
          projectInterpreter,
          variableSubstitution);
      return nature;
    }
    return null;
  }
Beispiel #19
0
  /**
   * Create a command line for launching.
   *
   * @param actualRun if true it'll make the variable substitution and start the listen connector in
   *     the case of a debug session.
   * @return command line ready to be exec'd
   * @throws CoreException
   * @throws JDTNotAvailableException
   */
  public String[] getCommandLine(boolean actualRun) throws CoreException, JDTNotAvailableException {
    List<String> cmdArgs = new ArrayList<String>();

    if (isJython()) {
      // "java.exe" -classpath "C:\bin\jython21\jython.jar" org.python.util.jython script %ARGS%
      String javaLoc = JavaVmLocationFinder.findDefaultJavaExecutable().getAbsolutePath();
      if (!InterpreterInfo.isJythonExecutable(interpreter.toOSString())) {
        throw new RuntimeException(
            "The jython jar must be specified as the interpreter to run. Found: " + interpreter);
      }
      cmdArgs.add(javaLoc);

      // some nice things on the classpath config: http://mindprod.com/jgloss/classpath.html
      cmdArgs.add("-classpath");
      String cpath;

      // TODO: add some option in the project so that the user can choose to use the
      // classpath specified in the java project instead of the pythonpath itself

      //            if (project.getNature(Constants.JAVA_NATURE) != null){
      //                cpath  = getClasspath(JavaCore.create(project));
      //            } else {
      cpath = interpreter + SimpleRunner.getPythonPathSeparator() + pythonpathUsed;
      //            }
      cmdArgs.add(cpath);
      cmdArgs.add(
          "-Dpython.path="
              + pythonpathUsed); // will be added to the env variables in the run (check if this
      // works on all platforms...)

      addVmArgs(cmdArgs);

      if (isDebug) {
        // This was removed because it cannot be used. See:
        // http://bugs.jython.org/issue1438
        // cmdArgs.add("-Dpython.security.respectJavaAccessibility=false");

        cmdArgs.add("org.python.util.jython");
        addDebugArgs(cmdArgs, "jython", actualRun);
      } else {
        cmdArgs.add("org.python.util.jython");
      }

    } else {
      // python or iron python

      cmdArgs.add(interpreter.toOSString());
      // Next option is for unbuffered stdout, otherwise Eclipse will not see any output until done
      cmdArgs.add("-u");

      addVmArgs(cmdArgs);
      if (isDebug && isIronpython()) {
        addIronPythonDebugVmArgs(cmdArgs);
      }

      addDebugArgs(cmdArgs, "python", actualRun);
    }

    // Check if we should do code-coverage...
    boolean coverageRun = PyCoveragePreferences.getAllRunsDoCoverage();
    if (coverageRun && isDebug) {
      if (actualRun) {
        RunInUiThread.async(
            new Runnable() {

              public void run() {
                PyDialogHelpers.openWarning(
                    "Conflicting options: coverage with debug.",
                    "Making a debug run with coverage enabled will not yield the expected results.\n\n"
                        + "They'll conflict because both use the python tracing facility (i.e.: sys.settrace()).\n"
                        + "\n"
                        + "To debug a coverage run, do a regular run and use the remote debugger "
                        + "(but note that the coverage will stop when it's enabled).\n"
                        + "\n"
                        + "Note: the run will be continued anyways.");
              }
            });
      }
    }

    if (isUnittest()) {
      cmdArgs.add(getRunFilesScript());
    } else {
      if (coverageRun) {
        // Separate support (unittest has the coverage support builtin).
        cmdArgs.add(getCoverageScript());
        cmdArgs.add(PyCoverage.getCoverageFileLocation().getAbsolutePath());
        cmdArgs.add("run");
        cmdArgs.add("--source");
        cmdArgs.add(PyCodeCoverageView.getChosenDir().getLocation().toOSString());
      }
    }

    for (IPath p : resource) {
      cmdArgs.add(p.toOSString());
    }

    if (!isUnittest()) {
      // The program arguments are not used when running a unittest (excluded from the tab group in
      // favor
      // of a way to overriding the default unittest arguments).
      String runArguments[] = null;
      if (actualRun && arguments != null) {
        String expanded =
            getStringSubstitution(PythonNature.getPythonNature(project))
                .performStringSubstitution(arguments);
        runArguments = parseStringIntoList(expanded);
      }

      for (int i = 0; runArguments != null && i < runArguments.length; i++) {
        cmdArgs.add(runArguments[i]);
      }

    } else {
      // Last thing (first the files and last the special parameters the user passed -- i.e.: nose
      // parameters)
      addUnittestArgs(cmdArgs, actualRun, coverageRun);
    }

    String[] retVal = new String[cmdArgs.size()];
    cmdArgs.toArray(retVal);

    if (actualRun) {
      CreatedCommandLineParams createdCommandLineParams =
          new CreatedCommandLineParams(retVal, coverageRun);
      // Provide a way for clients to alter the command line.
      List<Object> participants =
          ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_COMMAND_LINE_PARTICIPANT);
      for (Object object : participants) {
        try {
          IPyCommandLineParticipant c = (IPyCommandLineParticipant) object;
          createdCommandLineParams = c.updateCommandLine(createdCommandLineParams);
        } catch (Exception e) {
          Log.log(e);
        }
      }

      retVal = createdCommandLineParams.cmdLine;
      PythonRunnerCallbacks.onCreatedCommandLine.call(createdCommandLineParams);
    }

    return retVal;
  }
Beispiel #20
0
  /**
   * Sets defaults.
   *
   * @throws InvalidRunException
   * @throws MisconfigurationException
   */
  @SuppressWarnings("unchecked")
  public PythonRunnerConfig(
      ILaunchConfiguration conf, String mode, String run, boolean makeArgumentsVariableSubstitution)
      throws CoreException, InvalidRunException, MisconfigurationException {
    // 1st thing, see if this is a valid run.
    project = getProjectFromConfiguration(conf);

    if (project == null) { // Ok, we could not find it out
      throw Log.log("Could not get project for configuration: " + conf);
    }

    // We need the project to find out the default interpreter from the InterpreterManager.
    IPythonNature pythonNature = PythonNature.getPythonNature(project);
    if (pythonNature == null) {
      CoreException e = Log.log("No python nature for project: " + project.getName());
      throw e;
    }

    // now, go on configuring other things
    this.configuration = conf;
    this.run = run;
    isDebug = mode.equals(ILaunchManager.DEBUG_MODE);
    isInteractive = mode.equals("interactive");

    resource = getLocation(conf, pythonNature);
    arguments = getArguments(conf, makeArgumentsVariableSubstitution);
    IPath workingPath = getWorkingDirectory(conf, pythonNature);
    workingDirectory = workingPath == null ? null : workingPath.toFile();
    acceptTimeout = PydevPrefs.getPreferences().getInt(PydevEditorPrefs.CONNECT_TIMEOUT);

    interpreterLocation =
        getInterpreterLocation(conf, pythonNature, this.getRelatedInterpreterManager());
    interpreter = getInterpreter(interpreterLocation, conf, pythonNature);

    // make the environment
    ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
    envp = launchManager.getEnvironment(conf);
    IInterpreterManager manager;
    if (isJython()) {
      manager = PydevPlugin.getJythonInterpreterManager();
    } else if (isIronpython()) {
      manager = PydevPlugin.getIronpythonInterpreterManager();
    } else {
      manager = PydevPlugin.getPythonInterpreterManager();
    }

    boolean win32 = PlatformUtils.isWindowsPlatform();

    if (envp == null) {
      // ok, the user has done nothing to the environment, just get all the default environment
      // which has the pythonpath in it
      envp = SimpleRunner.getEnvironment(pythonNature, interpreterLocation, manager);

    } else {
      // ok, the user has done something to configure it, so, just add the pythonpath to the
      // current env (if he still didn't do so)
      Map envMap = conf.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map) null);

      String pythonpath =
          SimpleRunner.makePythonPathEnvString(pythonNature, interpreterLocation, manager);
      updateVar(pythonNature, manager, win32, envMap, "PYTHONPATH", pythonpath);
      if (isJython()) {
        // Also update the classpath env variable.
        updateVar(pythonNature, manager, win32, envMap, "CLASSPATH", pythonpath);
        // And the jythonpath env variable
        updateVar(pythonNature, manager, win32, envMap, "JYTHONPATH", pythonpath);

      } else if (isIronpython()) {
        // Also update the ironpythonpath env variable.
        updateVar(pythonNature, manager, win32, envMap, "IRONPYTHONPATH", pythonpath);
      }

      // And we also must get the environment variables specified in the interpreter manager.
      envp = interpreterLocation.updateEnv(envp, envMap.keySet());
    }

    boolean hasDjangoNature = project.hasNature(PythonNature.DJANGO_NATURE_ID);

    String settingsModule = null;
    Map<String, String> variableSubstitution = null;
    final String djangoSettingsKey = "DJANGO_SETTINGS_MODULE";
    String djangoSettingsEnvEntry = null;
    try {
      variableSubstitution = pythonNature.getPythonPathNature().getVariableSubstitution();
      settingsModule = variableSubstitution.get(djangoSettingsKey);
      if (settingsModule != null) {
        if (settingsModule.trim().length() > 0) {
          djangoSettingsEnvEntry = djangoSettingsKey + "=" + settingsModule.trim();
        }
      }
    } catch (Exception e1) {
      Log.log(e1);
    }
    if (djangoSettingsEnvEntry == null && hasDjangoNature) {
      // Default if not specified (only add it if the nature is there).
      djangoSettingsEnvEntry = djangoSettingsKey + "=" + project.getName() + ".settings";
    }

    // Note: set flag even if not debugging as the user may use remote-debugging later on.
    boolean geventSupport =
        DebugPrefsPage.getGeventDebugging()
            && pythonNature.getInterpreterType() == IPythonNature.INTERPRETER_TYPE_PYTHON;

    // Now, set the pythonpathUsed according to what's in the environment.
    String p = "";
    for (int i = 0; i < envp.length; i++) {
      String s = envp[i];
      Tuple<String, String> tup = StringUtils.splitOnFirst(s, '=');
      String var = tup.o1;
      if (win32) {
        // On windows it doesn't matter, always consider uppercase.
        var = var.toUpperCase();
      }

      if (var.equals("PYTHONPATH")) {
        p = tup.o2;

      } else if (var.equals(djangoSettingsKey)) {
        // Update it.
        if (djangoSettingsEnvEntry != null) {
          envp[i] = djangoSettingsEnvEntry;
          djangoSettingsEnvEntry = null;
        }
      }

      if (geventSupport) {
        if (var.equals("GEVENT_SUPPORT")) {
          // Flag already set in the environment
          geventSupport = false;
        }
      }
    }

    // Still not added, let's do that now.
    if (djangoSettingsEnvEntry != null) {
      envp = StringUtils.addString(envp, djangoSettingsEnvEntry);
    }
    if (geventSupport) {
      envp = StringUtils.addString(envp, "GEVENT_SUPPORT=True");
    }
    this.pythonpathUsed = p;
  }
  /**
   * @param topLevel
   * @return
   */
  private boolean createSourceFolderSelect(Composite topLevel) {
    Label label;
    label = new Label(topLevel, SWT.NONE);
    label.setText("Source Folder");
    textSourceFolder = new Text(topLevel, SWT.BORDER);
    textSourceFolder.addKeyListener(this);
    btBrowseSourceFolder = new Button(topLevel, SWT.NONE);
    setLayout(label, textSourceFolder, btBrowseSourceFolder);

    btBrowseSourceFolder.addSelectionListener(
        new SelectionListener() {

          public void widgetSelected(SelectionEvent e) {
            try {
              PythonPackageSelectionDialog dialog =
                  new PythonPackageSelectionDialog(getShell(), true);
              dialog.open();
              Object firstResult = dialog.getFirstResult();
              if (firstResult instanceof SourceFolder) {
                SourceFolder f = (SourceFolder) firstResult;
                textSourceFolder.setText(f.folder.getFullPath().toString());
              }
            } catch (Exception e1) {
              Log.log(e1);
            }
          }

          public void widgetDefaultSelected(SelectionEvent e) {}
        });

    Object element = selection.getFirstElement();

    try {

      if (element instanceof IAdaptable) {
        IAdaptable adaptable = (IAdaptable) element;
        element = adaptable.getAdapter(IFile.class);
        if (element == null) {
          element = adaptable.getAdapter(IProject.class);
        }
        if (element == null) {
          element = adaptable.getAdapter(IFolder.class);
        }
      }

      if (element instanceof IFile) {
        IFile f = (IFile) element;
        element = f.getParent();
      }

      if (element instanceof IProject) {
        IPythonPathNature nature = PythonNature.getPythonPathNature((IProject) element);
        if (nature != null) {
          String[] srcPaths = PythonNature.getStrAsStrItems(nature.getProjectSourcePath(true));
          if (srcPaths.length > 0) {
            textSourceFolder.setText(srcPaths[0]);
            return true;
          }
        }
      }

      if (element instanceof IFolder) {
        IFolder f = (IFolder) element;
        String srcPath = getSrcFolderFromFolder(f);
        if (srcPath == null) {
          return true;
        }
        textSourceFolder.setText(srcPath);
        return true;
      }

    } catch (Exception e) {
      Log.log(e);
    }
    return false;
  }
  /** When a console page is initialized, */
  public void init(IPageBookViewPage page, final IConsole console) {
    if (!(console instanceof ProcessConsole)) {
      return;
    }
    ProcessConsole processConsole = (ProcessConsole) console;
    IProcess process = processConsole.getProcess();
    if (process == null) {
      return;
    }
    if (!PyCodeCompletionPreferencesPage.useCodeCompletion()
        || !PyCodeCompletionPreferencesPage.useCodeCompletionOnDebug()) {
      return;
    }
    String attribute = process.getAttribute(Constants.PYDEV_DEBUG_IPROCESS_ATTR);
    if (!Constants.PYDEV_DEBUG_IPROCESS_ATTR_TRUE.equals(attribute)) {
      // Only provide code-completion for pydev debug processes.
      return;
    }
    Control control = page.getControl();
    if (page instanceof IOConsolePage) {

      // Note that completions on "all letters and '_'" are already activated just by installing
      // the content assist, but the completions on the default keybinding is not, so, we have to
      // call it ourselves here.
      control.addKeyListener(
          new KeyListener() {
            public void keyPressed(KeyEvent e) {

              if (KeyBindingHelper.matchesContentAssistKeybinding(e)) {
                contentAssist.showPossibleCompletions();
              }
            }

            public void keyReleased(KeyEvent e) {}
          });

      IOConsolePage consolePage = (IOConsolePage) page;
      TextConsoleViewer viewer = consolePage.getViewer();

      contentAssist =
          new PyContentAssistant() {
            public String showPossibleCompletions() {
              // Only show completions if we're in a suspended console.
              if (getCurrentSuspendedPyStackFrame(console) == null) {
                return null;
              }
              return super.showPossibleCompletions();
            };
          };
      contentAssist.setInformationControlCreator(
          PyContentAssistant.createInformationControlCreator(viewer));
      ILaunch launch = process.getLaunch();
      IDebugTarget debugTarget = launch.getDebugTarget();
      IInterpreterInfo projectInterpreter = null;
      if (debugTarget instanceof PyDebugTarget) {
        PyDebugTarget pyDebugTarget = (PyDebugTarget) debugTarget;
        PythonNature nature = PythonNature.getPythonNature(pyDebugTarget.project);
        if (nature != null) {
          try {
            projectInterpreter = nature.getProjectInterpreter();
          } catch (Throwable e1) {
            Log.log(e1);
          }
        }
      }
      contentAssist.install(new ScriptConsoleViewerWrapper(viewer, projectInterpreter));

      PydevConsoleInterpreter interpreter = new PydevConsoleInterpreter();
      interpreter.setConsoleCommunication(new GetCompletionsInDebug());

      IContentAssistProcessor processor =
          new PydevConsoleCompletionProcessor(interpreter, contentAssist);
      contentAssist.setContentAssistProcessor(processor, IOConsolePartition.INPUT_PARTITION_TYPE);
      contentAssist.setContentAssistProcessor(processor, IOConsolePartition.OUTPUT_PARTITION_TYPE);

      contentAssist.enableAutoActivation(true);
      contentAssist.enableAutoInsert(false);
      contentAssist.setAutoActivationDelay(PyCodeCompletionPreferencesPage.getAutocompleteDelay());
    }
  }
Beispiel #23
0
  /**
   * @param name determines the name of the method to visit (added removed or changed)
   * @param resource the resource to visit
   * @param document the document from the resource
   * @param monitor
   */
  private void visitWith(
      int visitType,
      final IResource resource,
      ICallback0<IDocument> document,
      IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
      return; // it's already cancelled
    }
    IPythonNature nature = PythonNature.getPythonNature(resource);
    if (nature == null) {
      return;
    }
    if (!nature.startRequests()) {
      return;
    }

    try {

      try {
        // we visit external because we must index them
        if (!isResourceInPythonpathProjectSources(resource, nature, true)) {
          return; // we only analyze resources that are in the pythonpath
        }
      } catch (Exception e1) {
        Log.log(e1);
        return; // we only analyze resources that are in the pythonpath
      }

      VisitorMemo copyMemo = new VisitorMemo(this.memo);
      FastStringBuffer bufferToCommunicateProgress = new FastStringBuffer();

      for (PyDevBuilderVisitor visitor : visitors) {
        // some visitors cannot visit too many elements because they do a lot of processing
        if (visitor.maxResourcesToVisit() == PyDevBuilderVisitor.MAX_TO_VISIT_INFINITE
            || visitor.maxResourcesToVisit() >= totalResources) {
          visitor.memo = copyMemo; // setting the memo must be the first thing.
          try {
            // communicate progress for each visitor
            PyDevBuilder.communicateProgress(
                monitor,
                totalResources,
                currentResourcesVisited,
                resource,
                visitor,
                bufferToCommunicateProgress);
            switch (visitType) {
              case VISIT_ADD:
                visitor.visitAddedResource(resource, document, monitor);
                break;

              case VISIT_CHANGE:
                visitor.visitChangedResource(resource, document, monitor);
                break;

              case VISIT_REMOVE:
                visitor.visitRemovedResource(resource, document, monitor);
                break;

              default:
                throw new RuntimeException("Error: visit type not properly given!"); // $NON-NLS-1$
            }
          } catch (Exception e) {
            Log.log(e);
          }
        }
      }

    } finally {
      nature.endRequests();
    }
  }