/** * Creates a string that can be passed as the PYTHONPATH * * @param project the project we want to get the settings from. If it is null, the system * pythonpath is returned * @param interpreter this is the interpreter to be used to create the env. * @return a string that can be used as the PYTHONPATH env variable */ public static String makePythonPathEnvString( IPythonNature pythonNature, IInterpreterInfo interpreter, IInterpreterManager manager) { if (pythonNature == null) { if (interpreter == null) { return makePythonPathEnvFromPaths( new ArrayList< String>()); // no pythonpath can be gotten (set to empty, so that the default is // gotten) } else { List<String> pythonPath = interpreter.getPythonPath(); return makePythonPathEnvFromPaths(pythonPath); } } List<String> paths; // if we have a project, get its complete pythonpath IPythonPathNature pythonPathNature = pythonNature.getPythonPathNature(); if (pythonPathNature == null) { IProject project = pythonNature.getProject(); String projectName; if (project == null) { projectName = "null?"; } else { projectName = project.getName(); } throw new RuntimeException( "The project " + projectName + " does not have the pythonpath configured, \n" + "please configure it correcly (please check the pydev getting started guide at \n" + "http://pydev.org/manual_101_root.html for better information on how to do it)."); } paths = pythonPathNature.getCompleteProjectPythonPath(interpreter, manager); return makePythonPathEnvFromPaths(paths); }
/** * 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; }
@Override public void addProps( MarkerAnnotationAndPosition markerAnnotation, IAnalysisPreferences analysisPreferences, String line, PySelection ps, int offset, IPythonNature nature, PyEdit edit, List<ICompletionProposal> props) throws BadLocationException, CoreException { if (nature == null) { return; } ICodeCompletionASTManager astManager = nature.getAstManager(); if (astManager == null) { return; } if (markerAnnotation.position == null) { return; } IMarker marker = markerAnnotation.markerAnnotation.getMarker(); Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE); int start = markerAnnotation.position.offset; int end = start + markerAnnotation.position.length; ps.setSelection(start, end); String markerContents; try { markerContents = ps.getSelectedText(); } catch (Exception e1) { return; // Selection may be wrong. } IDocument doc = ps.getDoc(); List<String> parametersAfterCall = ps.getParametersAfterCall(end); switch (id) { case IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE: addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall); addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall); break; case IAnalysisPreferences.TYPE_UNDEFINED_IMPORT_VARIABLE: // Say we had something as: // import sys // sys.Bar // in which case 'Bar' is undefined // in this situation, the activationTokenAndQual would be "sys." and "Bar" // and we want to get the definition for "sys" String[] activationTokenAndQual = ps.getActivationTokenAndQual(true); if (activationTokenAndQual[0].endsWith(".")) { ArrayList<IDefinition> selected = findDefinitions(nature, edit, start - 2, doc); for (IDefinition iDefinition : selected) { IModule module = iDefinition.getModule(); if (module.getFile() != null) { Definition definition = (Definition) iDefinition; File file = module.getFile(); if (definition.ast == null) { // if we have no ast in the definition, it means the module itself was found (global // scope) // Add option to create class at the given module! addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file); addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file); } else if (definition.ast instanceof ClassDef) { ClassDef classDef = (ClassDef) definition.ast; // Ok, we should create a field or method in this case (accessing a classmethod or // staticmethod) PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField(); String className = NodeUtils.getNameFromNameTok(classDef.name); pyCreateMethod.setCreateInClass(className); pyCreateMethod.setCreateAs(PyCreateMethodOrField.CLASSMETHOD); addCreateClassmethodOption( ps, edit, props, markerContents, parametersAfterCall, pyCreateMethod, file, className); } } } } break; case IAnalysisPreferences.TYPE_UNRESOLVED_IMPORT: // This case is the following: from other_module4 import Foo // with 'Foo' being undefined. // So, we have to suggest creating a Foo class/method in other_module4 PyImportsHandling importsHandling = new PyImportsHandling(ps.getDoc(), false); int offsetLine = ps.getLineOfOffset(start); String selectedText = ps.getSelectedText(); Tuple<IModule, String> found = null; String foundFromImportStr = null; boolean isImportFrom = false; OUT: for (ImportHandle handle : importsHandling) { if (handle.startFoundLine == offsetLine || handle.endFoundLine == offsetLine || (handle.startFoundLine < offsetLine && handle.endFoundLine > offsetLine)) { List<ImportHandleInfo> importInfo = handle.getImportInfo(); for (ImportHandleInfo importHandleInfo : importInfo) { String fromImportStr = importHandleInfo.getFromImportStr(); List<String> importedStr = importHandleInfo.getImportedStr(); for (String imported : importedStr) { if (selectedText.equals(imported)) { if (fromImportStr != null) { foundFromImportStr = fromImportStr + "." + imported; isImportFrom = true; } else { // if fromImportStr == null, it's not a from xxx import yyy (i.e.: simple // import) foundFromImportStr = imported; } try { String currentModule = nature.resolveModule(edit.getEditorFile()); ICompletionState state = CompletionStateFactory.getEmptyCompletionState( nature, new CompletionCache()); found = nature .getAstManager() .findModule( foundFromImportStr, currentModule, state, new SourceModule( currentModule, edit.getEditorFile(), edit.getAST(), null)); } catch (Exception e) { Log.log(e); } break OUT; } } } break OUT; } } boolean addOptionToCreateClassOrMethod = isImportFrom; if (found != null && found.o1 != null) { // Ok, we found a module, now, it may be that we still have to create some intermediary // modules // or just create a class or method at the end. if (found.o1 instanceof SourceModule) { // if all was found, there's nothing left to create. if (found.o2 != null && found.o2.length() > 0) { SourceModule sourceModule = (SourceModule) found.o1; File file = sourceModule.getFile(); if (found.o2.indexOf('.') != -1) { // We have to create some intermediary structure. if (!addOptionToCreateClassOrMethod) { // Cannot create class or method from the info (only the module structure). if (sourceModule.getName().endsWith(".__init__")) { File f = getFileStructure(file.getParentFile(), found.o2); addCreateModuleOption(ps, edit, props, markerContents, f); } } else { // Ok, the leaf may be a class or method. if (sourceModule.getName().endsWith(".__init__")) { String moduleName = FullRepIterable.getWithoutLastPart(sourceModule.getName()); String withoutLastPart = FullRepIterable.getWithoutLastPart(found.o2); moduleName += "." + withoutLastPart; String classOrMethodName = FullRepIterable.getLastPart(found.o2); File f = getFileStructure(file.getParentFile(), withoutLastPart); addCreateClassInNewModuleOption( ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f); addCreateMethodInNewModuleOption( ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f); } } } else { // Ok, it's all there, we just have to create the leaf. if (!addOptionToCreateClassOrMethod || sourceModule.getName().endsWith(".__init__")) { // Cannot create class or method from the info (only the module structure). if (sourceModule.getName().endsWith(".__init__")) { File f = new File( file.getParent(), found.o2 + FileTypesPreferencesPage.getDefaultDottedPythonExtension()); addCreateModuleOption(ps, edit, props, markerContents, f); } } else { // Ok, the leaf may be a class or method. addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file); addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file); } } } } } else if (foundFromImportStr != null) { // We couldn't find anything there, so, we have to create the modules structure as needed // and // maybe create a class or module at the end (but only if it's an import from). // Ok, it's all there, we just have to create the leaf. // Discover the source folder where we should create the structure. File editorFile = edit.getEditorFile(); String onlyProjectPythonPathStr = nature.getPythonPathNature().getOnlyProjectPythonPathStr(false); List<String> split = StringUtils.splitAndRemoveEmptyTrimmed(onlyProjectPythonPathStr, '|'); for (int i = 0; i < split.size(); i++) { String fullPath = FileUtils.getFileAbsolutePath(split.get(i)); fullPath = PythonPathHelper.getDefaultPathStr(fullPath); split.set(i, fullPath); } HashSet<String> projectSourcePath = new HashSet<String>(split); if (projectSourcePath.size() == 0) { return; // No source folder for editor... this shouldn't happen (code analysis wouldn't // even run on it). } String fullPath = FileUtils.getFileAbsolutePath(editorFile); fullPath = PythonPathHelper.getDefaultPathStr(fullPath); String foundSourceFolderFullPath = null; if (projectSourcePath.size() == 1) { foundSourceFolderFullPath = projectSourcePath.iterator().next(); } else { for (String string : projectSourcePath) { if (fullPath.startsWith(string)) { // Use this as the source folder foundSourceFolderFullPath = string; break; } } } if (foundSourceFolderFullPath != null) { if (!addOptionToCreateClassOrMethod) { // Cannot create class or method from the info (only the module structure). File f = getFileStructure(new File(foundSourceFolderFullPath), foundFromImportStr); addCreateModuleOption(ps, edit, props, foundFromImportStr, f); } else { // Ok, the leaf may be a class or method. String moduleName = FullRepIterable.getWithoutLastPart(foundFromImportStr); File file = getFileStructure(new File(foundSourceFolderFullPath), moduleName); String lastPart = FullRepIterable.getLastPart(foundFromImportStr); addCreateClassInNewModuleOption( ps, edit, props, lastPart, moduleName, parametersAfterCall, file); addCreateMethodInNewModuleOption( ps, edit, props, lastPart, moduleName, parametersAfterCall, file); } } } break; } }